httplib.h 274 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2022 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.11.4"
  10. /*
  11. * Configuration
  12. */
  13. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  14. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  15. #endif
  16. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  17. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  18. #endif
  19. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  20. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  21. #endif
  22. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  23. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  24. #endif
  25. #ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
  26. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
  27. #endif
  28. #ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
  29. #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
  30. #endif
  31. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_SECOND
  32. #define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 5
  33. #endif
  34. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_USECOND
  35. #define CPPHTTPLIB_WRITE_TIMEOUT_USECOND 0
  36. #endif
  37. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  38. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  39. #endif
  40. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  41. #ifdef _WIN32
  42. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
  43. #else
  44. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  45. #endif
  46. #endif
  47. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  48. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  49. #endif
  50. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  51. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  52. #endif
  53. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  54. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  55. #endif
  56. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  57. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  58. #endif
  59. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  60. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  61. #endif
  62. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  63. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  64. #endif
  65. #ifndef CPPHTTPLIB_TCP_NODELAY
  66. #define CPPHTTPLIB_TCP_NODELAY false
  67. #endif
  68. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  69. #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
  70. #endif
  71. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  72. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  73. #endif
  74. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  75. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  76. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  77. ? std::thread::hardware_concurrency() - 1 \
  78. : 0))
  79. #endif
  80. #ifndef CPPHTTPLIB_RECV_FLAGS
  81. #define CPPHTTPLIB_RECV_FLAGS 0
  82. #endif
  83. #ifndef CPPHTTPLIB_SEND_FLAGS
  84. #define CPPHTTPLIB_SEND_FLAGS 0
  85. #endif
  86. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  87. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  88. #endif
  89. /*
  90. * Headers
  91. */
  92. #ifdef _WIN32
  93. #ifndef _CRT_SECURE_NO_WARNINGS
  94. #define _CRT_SECURE_NO_WARNINGS
  95. #endif //_CRT_SECURE_NO_WARNINGS
  96. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  97. #define _CRT_NONSTDC_NO_DEPRECATE
  98. #endif //_CRT_NONSTDC_NO_DEPRECATE
  99. #if defined(_MSC_VER)
  100. #if _MSC_VER < 1900
  101. #error Sorry, Visual Studio versions prior to 2015 are not supported
  102. #endif
  103. #pragma comment(lib, "ws2_32.lib")
  104. #ifdef _WIN64
  105. using ssize_t = __int64;
  106. #else
  107. using ssize_t = long;
  108. #endif
  109. #endif // _MSC_VER
  110. #ifndef S_ISREG
  111. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  112. #endif // S_ISREG
  113. #ifndef S_ISDIR
  114. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  115. #endif // S_ISDIR
  116. #ifndef NOMINMAX
  117. #define NOMINMAX
  118. #endif // NOMINMAX
  119. #include <io.h>
  120. #include <winsock2.h>
  121. #include <ws2tcpip.h>
  122. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  123. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  124. #endif
  125. #ifndef strcasecmp
  126. #define strcasecmp _stricmp
  127. #endif // strcasecmp
  128. using socket_t = SOCKET;
  129. #ifdef CPPHTTPLIB_USE_POLL
  130. #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
  131. #endif
  132. #else // not _WIN32
  133. #include <arpa/inet.h>
  134. #ifndef _AIX
  135. #include <ifaddrs.h>
  136. #endif
  137. #include <net/if.h>
  138. #include <netdb.h>
  139. #include <netinet/in.h>
  140. #ifdef __linux__
  141. #include <resolv.h>
  142. #endif
  143. #include <netinet/tcp.h>
  144. #ifdef CPPHTTPLIB_USE_POLL
  145. #include <poll.h>
  146. #endif
  147. #include <csignal>
  148. #include <pthread.h>
  149. #include <sys/select.h>
  150. #include <sys/socket.h>
  151. #include <sys/un.h>
  152. #include <unistd.h>
  153. using socket_t = int;
  154. #ifndef INVALID_SOCKET
  155. #define INVALID_SOCKET (-1)
  156. #endif
  157. #endif //_WIN32
  158. #include <algorithm>
  159. #include <array>
  160. #include <atomic>
  161. #include <cassert>
  162. #include <cctype>
  163. #include <climits>
  164. #include <condition_variable>
  165. #include <cstring>
  166. #include <errno.h>
  167. #include <fcntl.h>
  168. #include <fstream>
  169. #include <functional>
  170. #include <iomanip>
  171. #include <iostream>
  172. #include <list>
  173. #include <map>
  174. #include <memory>
  175. #include <mutex>
  176. #include <random>
  177. #include <regex>
  178. #include <set>
  179. #include <sstream>
  180. #include <string>
  181. #include <sys/stat.h>
  182. #include <thread>
  183. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  184. #ifdef _WIN32
  185. #include <wincrypt.h>
  186. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  187. // used
  188. #undef X509_NAME
  189. #undef X509_CERT_PAIR
  190. #undef X509_EXTENSIONS
  191. #undef PKCS7_SIGNER_INFO
  192. #ifdef _MSC_VER
  193. #pragma comment(lib, "crypt32.lib")
  194. #pragma comment(lib, "cryptui.lib")
  195. #endif
  196. #endif //_WIN32
  197. #include <openssl/err.h>
  198. #include <openssl/evp.h>
  199. #include <openssl/ssl.h>
  200. #include <openssl/x509v3.h>
  201. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  202. #include <openssl/applink.c>
  203. #endif
  204. #include <iostream>
  205. #include <sstream>
  206. #if OPENSSL_VERSION_NUMBER < 0x1010100fL
  207. #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
  208. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  209. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  210. #endif
  211. #endif
  212. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  213. #include <zlib.h>
  214. #endif
  215. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  216. #include <brotli/decode.h>
  217. #include <brotli/encode.h>
  218. #endif
  219. /*
  220. * Declaration
  221. */
  222. namespace httplib {
  223. namespace detail {
  224. /*
  225. * Backport std::make_unique from C++14.
  226. *
  227. * NOTE: This code came up with the following stackoverflow post:
  228. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  229. *
  230. */
  231. template <class T, class... Args>
  232. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  233. make_unique(Args &&...args) {
  234. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  235. }
  236. template <class T>
  237. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  238. make_unique(std::size_t n) {
  239. typedef typename std::remove_extent<T>::type RT;
  240. return std::unique_ptr<T>(new RT[n]);
  241. }
  242. struct ci {
  243. bool operator()(const std::string &s1, const std::string &s2) const {
  244. return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(),
  245. s2.end(),
  246. [](unsigned char c1, unsigned char c2) {
  247. return ::tolower(c1) < ::tolower(c2);
  248. });
  249. }
  250. };
  251. } // namespace detail
  252. using Headers = std::multimap<std::string, std::string, detail::ci>;
  253. using Params = std::multimap<std::string, std::string>;
  254. using Match = std::smatch;
  255. using Progress = std::function<bool(uint64_t current, uint64_t total)>;
  256. struct Response;
  257. using ResponseHandler = std::function<bool(const Response &response)>;
  258. struct MultipartFormData {
  259. std::string name;
  260. std::string content;
  261. std::string filename;
  262. std::string content_type;
  263. };
  264. using MultipartFormDataItems = std::vector<MultipartFormData>;
  265. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  266. class DataSink {
  267. public:
  268. DataSink() : os(&sb_), sb_(*this) {}
  269. DataSink(const DataSink &) = delete;
  270. DataSink &operator=(const DataSink &) = delete;
  271. DataSink(DataSink &&) = delete;
  272. DataSink &operator=(DataSink &&) = delete;
  273. std::function<bool(const char *data, size_t data_len)> write;
  274. std::function<void()> done;
  275. std::ostream os;
  276. private:
  277. class data_sink_streambuf : public std::streambuf {
  278. public:
  279. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  280. protected:
  281. std::streamsize xsputn(const char *s, std::streamsize n) {
  282. sink_.write(s, static_cast<size_t>(n));
  283. return n;
  284. }
  285. private:
  286. DataSink &sink_;
  287. };
  288. data_sink_streambuf sb_;
  289. };
  290. using ContentProvider =
  291. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  292. using ContentProviderWithoutLength =
  293. std::function<bool(size_t offset, DataSink &sink)>;
  294. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  295. struct MultipartFormDataProvider {
  296. std::string name;
  297. ContentProviderWithoutLength provider;
  298. std::string filename;
  299. std::string content_type;
  300. };
  301. using MultipartFormDataProviderItems = std::vector<MultipartFormDataProvider>;
  302. using ContentReceiverWithProgress =
  303. std::function<bool(const char *data, size_t data_length, uint64_t offset,
  304. uint64_t total_length)>;
  305. using ContentReceiver =
  306. std::function<bool(const char *data, size_t data_length)>;
  307. using MultipartContentHeader =
  308. std::function<bool(const MultipartFormData &file)>;
  309. class ContentReader {
  310. public:
  311. using Reader = std::function<bool(ContentReceiver receiver)>;
  312. using MultipartReader = std::function<bool(MultipartContentHeader header,
  313. ContentReceiver receiver)>;
  314. ContentReader(Reader reader, MultipartReader multipart_reader)
  315. : reader_(std::move(reader)),
  316. multipart_reader_(std::move(multipart_reader)) {}
  317. bool operator()(MultipartContentHeader header,
  318. ContentReceiver receiver) const {
  319. return multipart_reader_(std::move(header), std::move(receiver));
  320. }
  321. bool operator()(ContentReceiver receiver) const {
  322. return reader_(std::move(receiver));
  323. }
  324. Reader reader_;
  325. MultipartReader multipart_reader_;
  326. };
  327. using Range = std::pair<ssize_t, ssize_t>;
  328. using Ranges = std::vector<Range>;
  329. struct Request {
  330. std::string method;
  331. std::string path;
  332. Headers headers;
  333. std::string body;
  334. std::string remote_addr;
  335. int remote_port = -1;
  336. std::string local_addr;
  337. int local_port = -1;
  338. // for server
  339. std::string version;
  340. std::string target;
  341. Params params;
  342. MultipartFormDataMap files;
  343. Ranges ranges;
  344. Match matches;
  345. // for client
  346. ResponseHandler response_handler;
  347. ContentReceiverWithProgress content_receiver;
  348. Progress progress;
  349. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  350. const SSL *ssl = nullptr;
  351. #endif
  352. bool has_header(const std::string &key) const;
  353. std::string get_header_value(const std::string &key, size_t id = 0) const;
  354. template <typename T>
  355. T get_header_value(const std::string &key, size_t id = 0) const;
  356. size_t get_header_value_count(const std::string &key) const;
  357. void set_header(const std::string &key, const std::string &val);
  358. bool has_param(const std::string &key) const;
  359. std::string get_param_value(const std::string &key, size_t id = 0) const;
  360. size_t get_param_value_count(const std::string &key) const;
  361. bool is_multipart_form_data() const;
  362. bool has_file(const std::string &key) const;
  363. MultipartFormData get_file_value(const std::string &key) const;
  364. // private members...
  365. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  366. size_t content_length_ = 0;
  367. ContentProvider content_provider_;
  368. bool is_chunked_content_provider_ = false;
  369. size_t authorization_count_ = 0;
  370. };
  371. struct Response {
  372. std::string version;
  373. int status = -1;
  374. std::string reason;
  375. Headers headers;
  376. std::string body;
  377. std::string location; // Redirect location
  378. bool has_header(const std::string &key) const;
  379. std::string get_header_value(const std::string &key, size_t id = 0) const;
  380. template <typename T>
  381. T get_header_value(const std::string &key, size_t id = 0) const;
  382. size_t get_header_value_count(const std::string &key) const;
  383. void set_header(const std::string &key, const std::string &val);
  384. void set_redirect(const std::string &url, int status = 302);
  385. void set_content(const char *s, size_t n, const std::string &content_type);
  386. void set_content(const std::string &s, const std::string &content_type);
  387. void set_content_provider(
  388. size_t length, const std::string &content_type, ContentProvider provider,
  389. ContentProviderResourceReleaser resource_releaser = nullptr);
  390. void set_content_provider(
  391. const std::string &content_type, ContentProviderWithoutLength provider,
  392. ContentProviderResourceReleaser resource_releaser = nullptr);
  393. void set_chunked_content_provider(
  394. const std::string &content_type, ContentProviderWithoutLength provider,
  395. ContentProviderResourceReleaser resource_releaser = nullptr);
  396. Response() = default;
  397. Response(const Response &) = default;
  398. Response &operator=(const Response &) = default;
  399. Response(Response &&) = default;
  400. Response &operator=(Response &&) = default;
  401. ~Response() {
  402. if (content_provider_resource_releaser_) {
  403. content_provider_resource_releaser_(content_provider_success_);
  404. }
  405. }
  406. // private members...
  407. size_t content_length_ = 0;
  408. ContentProvider content_provider_;
  409. ContentProviderResourceReleaser content_provider_resource_releaser_;
  410. bool is_chunked_content_provider_ = false;
  411. bool content_provider_success_ = false;
  412. };
  413. class Stream {
  414. public:
  415. virtual ~Stream() = default;
  416. virtual bool is_readable() const = 0;
  417. virtual bool is_writable() const = 0;
  418. virtual ssize_t read(char *ptr, size_t size) = 0;
  419. virtual ssize_t write(const char *ptr, size_t size) = 0;
  420. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  421. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  422. virtual socket_t socket() const = 0;
  423. template <typename... Args>
  424. ssize_t write_format(const char *fmt, const Args &...args);
  425. ssize_t write(const char *ptr);
  426. ssize_t write(const std::string &s);
  427. };
  428. class TaskQueue {
  429. public:
  430. TaskQueue() = default;
  431. virtual ~TaskQueue() = default;
  432. virtual void enqueue(std::function<void()> fn) = 0;
  433. virtual void shutdown() = 0;
  434. virtual void on_idle() {}
  435. };
  436. class ThreadPool : public TaskQueue {
  437. public:
  438. explicit ThreadPool(size_t n) : shutdown_(false) {
  439. while (n) {
  440. threads_.emplace_back(worker(*this));
  441. n--;
  442. }
  443. }
  444. ThreadPool(const ThreadPool &) = delete;
  445. ~ThreadPool() override = default;
  446. void enqueue(std::function<void()> fn) override {
  447. {
  448. std::unique_lock<std::mutex> lock(mutex_);
  449. jobs_.push_back(std::move(fn));
  450. }
  451. cond_.notify_one();
  452. }
  453. void shutdown() override {
  454. // Stop all worker threads...
  455. {
  456. std::unique_lock<std::mutex> lock(mutex_);
  457. shutdown_ = true;
  458. }
  459. cond_.notify_all();
  460. // Join...
  461. for (auto &t : threads_) {
  462. t.join();
  463. }
  464. }
  465. private:
  466. struct worker {
  467. explicit worker(ThreadPool &pool) : pool_(pool) {}
  468. void operator()() {
  469. for (;;) {
  470. std::function<void()> fn;
  471. {
  472. std::unique_lock<std::mutex> lock(pool_.mutex_);
  473. pool_.cond_.wait(
  474. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  475. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  476. fn = std::move(pool_.jobs_.front());
  477. pool_.jobs_.pop_front();
  478. }
  479. assert(true == static_cast<bool>(fn));
  480. fn();
  481. }
  482. }
  483. ThreadPool &pool_;
  484. };
  485. friend struct worker;
  486. std::vector<std::thread> threads_;
  487. std::list<std::function<void()>> jobs_;
  488. bool shutdown_;
  489. std::condition_variable cond_;
  490. std::mutex mutex_;
  491. };
  492. using Logger = std::function<void(const Request &, const Response &)>;
  493. using SocketOptions = std::function<void(socket_t sock)>;
  494. void default_socket_options(socket_t sock);
  495. class Server {
  496. public:
  497. using Handler = std::function<void(const Request &, Response &)>;
  498. using ExceptionHandler =
  499. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  500. enum class HandlerResponse {
  501. Handled,
  502. Unhandled,
  503. };
  504. using HandlerWithResponse =
  505. std::function<HandlerResponse(const Request &, Response &)>;
  506. using HandlerWithContentReader = std::function<void(
  507. const Request &, Response &, const ContentReader &content_reader)>;
  508. using Expect100ContinueHandler =
  509. std::function<int(const Request &, Response &)>;
  510. Server();
  511. virtual ~Server();
  512. virtual bool is_valid() const;
  513. Server &Get(const std::string &pattern, Handler handler);
  514. Server &Post(const std::string &pattern, Handler handler);
  515. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  516. Server &Put(const std::string &pattern, Handler handler);
  517. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  518. Server &Patch(const std::string &pattern, Handler handler);
  519. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  520. Server &Delete(const std::string &pattern, Handler handler);
  521. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  522. Server &Options(const std::string &pattern, Handler handler);
  523. bool set_base_dir(const std::string &dir,
  524. const std::string &mount_point = std::string());
  525. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  526. Headers headers = Headers());
  527. bool remove_mount_point(const std::string &mount_point);
  528. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  529. const std::string &mime);
  530. Server &set_file_request_handler(Handler handler);
  531. Server &set_error_handler(HandlerWithResponse handler);
  532. Server &set_error_handler(Handler handler);
  533. Server &set_exception_handler(ExceptionHandler handler);
  534. Server &set_pre_routing_handler(HandlerWithResponse handler);
  535. Server &set_post_routing_handler(Handler handler);
  536. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  537. Server &set_logger(Logger logger);
  538. Server &set_address_family(int family);
  539. Server &set_tcp_nodelay(bool on);
  540. Server &set_socket_options(SocketOptions socket_options);
  541. Server &set_default_headers(Headers headers);
  542. Server &set_keep_alive_max_count(size_t count);
  543. Server &set_keep_alive_timeout(time_t sec);
  544. Server &set_read_timeout(time_t sec, time_t usec = 0);
  545. template <class Rep, class Period>
  546. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  547. Server &set_write_timeout(time_t sec, time_t usec = 0);
  548. template <class Rep, class Period>
  549. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  550. Server &set_idle_interval(time_t sec, time_t usec = 0);
  551. template <class Rep, class Period>
  552. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  553. Server &set_payload_max_length(size_t length);
  554. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  555. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  556. bool listen_after_bind();
  557. bool listen(const std::string &host, int port, int socket_flags = 0);
  558. bool is_running() const;
  559. void stop();
  560. std::function<TaskQueue *(void)> new_task_queue;
  561. protected:
  562. bool process_request(Stream &strm, bool close_connection,
  563. bool &connection_closed,
  564. const std::function<void(Request &)> &setup_request);
  565. std::atomic<socket_t> svr_sock_;
  566. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  567. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  568. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  569. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  570. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  571. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  572. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  573. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  574. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  575. private:
  576. using Handlers = std::vector<std::pair<std::regex, Handler>>;
  577. using HandlersForContentReader =
  578. std::vector<std::pair<std::regex, HandlerWithContentReader>>;
  579. socket_t create_server_socket(const std::string &host, int port,
  580. int socket_flags,
  581. SocketOptions socket_options) const;
  582. int bind_internal(const std::string &host, int port, int socket_flags);
  583. bool listen_internal();
  584. bool routing(Request &req, Response &res, Stream &strm);
  585. bool handle_file_request(const Request &req, Response &res,
  586. bool head = false);
  587. bool dispatch_request(Request &req, Response &res, const Handlers &handlers);
  588. bool
  589. dispatch_request_for_content_reader(Request &req, Response &res,
  590. ContentReader content_reader,
  591. const HandlersForContentReader &handlers);
  592. bool parse_request_line(const char *s, Request &req);
  593. void apply_ranges(const Request &req, Response &res,
  594. std::string &content_type, std::string &boundary);
  595. bool write_response(Stream &strm, bool close_connection, const Request &req,
  596. Response &res);
  597. bool write_response_with_content(Stream &strm, bool close_connection,
  598. const Request &req, Response &res);
  599. bool write_response_core(Stream &strm, bool close_connection,
  600. const Request &req, Response &res,
  601. bool need_apply_ranges);
  602. bool write_content_with_provider(Stream &strm, const Request &req,
  603. Response &res, const std::string &boundary,
  604. const std::string &content_type);
  605. bool read_content(Stream &strm, Request &req, Response &res);
  606. bool
  607. read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
  608. ContentReceiver receiver,
  609. MultipartContentHeader multipart_header,
  610. ContentReceiver multipart_receiver);
  611. bool read_content_core(Stream &strm, Request &req, Response &res,
  612. ContentReceiver receiver,
  613. MultipartContentHeader mulitpart_header,
  614. ContentReceiver multipart_receiver);
  615. virtual bool process_and_close_socket(socket_t sock);
  616. struct MountPointEntry {
  617. std::string mount_point;
  618. std::string base_dir;
  619. Headers headers;
  620. };
  621. std::vector<MountPointEntry> base_dirs_;
  622. std::atomic<bool> is_running_;
  623. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  624. Handler file_request_handler_;
  625. Handlers get_handlers_;
  626. Handlers post_handlers_;
  627. HandlersForContentReader post_handlers_for_content_reader_;
  628. Handlers put_handlers_;
  629. HandlersForContentReader put_handlers_for_content_reader_;
  630. Handlers patch_handlers_;
  631. HandlersForContentReader patch_handlers_for_content_reader_;
  632. Handlers delete_handlers_;
  633. HandlersForContentReader delete_handlers_for_content_reader_;
  634. Handlers options_handlers_;
  635. HandlerWithResponse error_handler_;
  636. ExceptionHandler exception_handler_;
  637. HandlerWithResponse pre_routing_handler_;
  638. Handler post_routing_handler_;
  639. Logger logger_;
  640. Expect100ContinueHandler expect_100_continue_handler_;
  641. int address_family_ = AF_UNSPEC;
  642. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  643. SocketOptions socket_options_ = default_socket_options;
  644. Headers default_headers_;
  645. };
  646. enum class Error {
  647. Success = 0,
  648. Unknown,
  649. Connection,
  650. BindIPAddress,
  651. Read,
  652. Write,
  653. ExceedRedirectCount,
  654. Canceled,
  655. SSLConnection,
  656. SSLLoadingCerts,
  657. SSLServerVerification,
  658. UnsupportedMultipartBoundaryChars,
  659. Compression,
  660. ConnectionTimeout,
  661. };
  662. std::string to_string(const Error error);
  663. std::ostream &operator<<(std::ostream &os, const Error &obj);
  664. class Result {
  665. public:
  666. Result(std::unique_ptr<Response> &&res, Error err,
  667. Headers &&request_headers = Headers{})
  668. : res_(std::move(res)), err_(err),
  669. request_headers_(std::move(request_headers)) {}
  670. // Response
  671. operator bool() const { return res_ != nullptr; }
  672. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  673. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  674. const Response &value() const { return *res_; }
  675. Response &value() { return *res_; }
  676. const Response &operator*() const { return *res_; }
  677. Response &operator*() { return *res_; }
  678. const Response *operator->() const { return res_.get(); }
  679. Response *operator->() { return res_.get(); }
  680. // Error
  681. Error error() const { return err_; }
  682. // Request Headers
  683. bool has_request_header(const std::string &key) const;
  684. std::string get_request_header_value(const std::string &key,
  685. size_t id = 0) const;
  686. template <typename T>
  687. T get_request_header_value(const std::string &key, size_t id = 0) const;
  688. size_t get_request_header_value_count(const std::string &key) const;
  689. private:
  690. std::unique_ptr<Response> res_;
  691. Error err_;
  692. Headers request_headers_;
  693. };
  694. class ClientImpl {
  695. public:
  696. explicit ClientImpl(const std::string &host);
  697. explicit ClientImpl(const std::string &host, int port);
  698. explicit ClientImpl(const std::string &host, int port,
  699. const std::string &client_cert_path,
  700. const std::string &client_key_path);
  701. virtual ~ClientImpl();
  702. virtual bool is_valid() const;
  703. Result Get(const std::string &path);
  704. Result Get(const std::string &path, const Headers &headers);
  705. Result Get(const std::string &path, Progress progress);
  706. Result Get(const std::string &path, const Headers &headers,
  707. Progress progress);
  708. Result Get(const std::string &path, ContentReceiver content_receiver);
  709. Result Get(const std::string &path, const Headers &headers,
  710. ContentReceiver content_receiver);
  711. Result Get(const std::string &path, ContentReceiver content_receiver,
  712. Progress progress);
  713. Result Get(const std::string &path, const Headers &headers,
  714. ContentReceiver content_receiver, Progress progress);
  715. Result Get(const std::string &path, ResponseHandler response_handler,
  716. ContentReceiver content_receiver);
  717. Result Get(const std::string &path, const Headers &headers,
  718. ResponseHandler response_handler,
  719. ContentReceiver content_receiver);
  720. Result Get(const std::string &path, ResponseHandler response_handler,
  721. ContentReceiver content_receiver, Progress progress);
  722. Result Get(const std::string &path, const Headers &headers,
  723. ResponseHandler response_handler, ContentReceiver content_receiver,
  724. Progress progress);
  725. Result Get(const std::string &path, const Params &params,
  726. const Headers &headers, Progress progress = nullptr);
  727. Result Get(const std::string &path, const Params &params,
  728. const Headers &headers, ContentReceiver content_receiver,
  729. Progress progress = nullptr);
  730. Result Get(const std::string &path, const Params &params,
  731. const Headers &headers, ResponseHandler response_handler,
  732. ContentReceiver content_receiver, Progress progress = nullptr);
  733. Result Head(const std::string &path);
  734. Result Head(const std::string &path, const Headers &headers);
  735. Result Post(const std::string &path);
  736. Result Post(const std::string &path, const Headers &headers);
  737. Result Post(const std::string &path, const char *body, size_t content_length,
  738. const std::string &content_type);
  739. Result Post(const std::string &path, const Headers &headers, const char *body,
  740. size_t content_length, const std::string &content_type);
  741. Result Post(const std::string &path, const std::string &body,
  742. const std::string &content_type);
  743. Result Post(const std::string &path, const Headers &headers,
  744. const std::string &body, const std::string &content_type);
  745. Result Post(const std::string &path, size_t content_length,
  746. ContentProvider content_provider,
  747. const std::string &content_type);
  748. Result Post(const std::string &path,
  749. ContentProviderWithoutLength content_provider,
  750. const std::string &content_type);
  751. Result Post(const std::string &path, const Headers &headers,
  752. size_t content_length, ContentProvider content_provider,
  753. const std::string &content_type);
  754. Result Post(const std::string &path, const Headers &headers,
  755. ContentProviderWithoutLength content_provider,
  756. const std::string &content_type);
  757. Result Post(const std::string &path, const Params &params);
  758. Result Post(const std::string &path, const Headers &headers,
  759. const Params &params);
  760. Result Post(const std::string &path, const MultipartFormDataItems &items);
  761. Result Post(const std::string &path, const Headers &headers,
  762. const MultipartFormDataItems &items);
  763. Result Post(const std::string &path, const Headers &headers,
  764. const MultipartFormDataItems &items, const std::string &boundary);
  765. Result Post(const std::string &path, const Headers &headers,
  766. const MultipartFormDataItems &items,
  767. const MultipartFormDataProviderItems &provider_items);
  768. Result Put(const std::string &path);
  769. Result Put(const std::string &path, const char *body, size_t content_length,
  770. const std::string &content_type);
  771. Result Put(const std::string &path, const Headers &headers, const char *body,
  772. size_t content_length, const std::string &content_type);
  773. Result Put(const std::string &path, const std::string &body,
  774. const std::string &content_type);
  775. Result Put(const std::string &path, const Headers &headers,
  776. const std::string &body, const std::string &content_type);
  777. Result Put(const std::string &path, size_t content_length,
  778. ContentProvider content_provider, const std::string &content_type);
  779. Result Put(const std::string &path,
  780. ContentProviderWithoutLength content_provider,
  781. const std::string &content_type);
  782. Result Put(const std::string &path, const Headers &headers,
  783. size_t content_length, ContentProvider content_provider,
  784. const std::string &content_type);
  785. Result Put(const std::string &path, const Headers &headers,
  786. ContentProviderWithoutLength content_provider,
  787. const std::string &content_type);
  788. Result Put(const std::string &path, const Params &params);
  789. Result Put(const std::string &path, const Headers &headers,
  790. const Params &params);
  791. Result Put(const std::string &path, const MultipartFormDataItems &items);
  792. Result Put(const std::string &path, const Headers &headers,
  793. const MultipartFormDataItems &items);
  794. Result Put(const std::string &path, const Headers &headers,
  795. const MultipartFormDataItems &items, const std::string &boundary);
  796. Result Put(const std::string &path, const Headers &headers,
  797. const MultipartFormDataItems &items,
  798. const MultipartFormDataProviderItems &provider_items);
  799. Result Patch(const std::string &path);
  800. Result Patch(const std::string &path, const char *body, size_t content_length,
  801. const std::string &content_type);
  802. Result Patch(const std::string &path, const Headers &headers,
  803. const char *body, size_t content_length,
  804. const std::string &content_type);
  805. Result Patch(const std::string &path, const std::string &body,
  806. const std::string &content_type);
  807. Result Patch(const std::string &path, const Headers &headers,
  808. const std::string &body, const std::string &content_type);
  809. Result Patch(const std::string &path, size_t content_length,
  810. ContentProvider content_provider,
  811. const std::string &content_type);
  812. Result Patch(const std::string &path,
  813. ContentProviderWithoutLength content_provider,
  814. const std::string &content_type);
  815. Result Patch(const std::string &path, const Headers &headers,
  816. size_t content_length, ContentProvider content_provider,
  817. const std::string &content_type);
  818. Result Patch(const std::string &path, const Headers &headers,
  819. ContentProviderWithoutLength content_provider,
  820. const std::string &content_type);
  821. Result Delete(const std::string &path);
  822. Result Delete(const std::string &path, const Headers &headers);
  823. Result Delete(const std::string &path, const char *body,
  824. size_t content_length, const std::string &content_type);
  825. Result Delete(const std::string &path, const Headers &headers,
  826. const char *body, size_t content_length,
  827. const std::string &content_type);
  828. Result Delete(const std::string &path, const std::string &body,
  829. const std::string &content_type);
  830. Result Delete(const std::string &path, const Headers &headers,
  831. const std::string &body, const std::string &content_type);
  832. Result Options(const std::string &path);
  833. Result Options(const std::string &path, const Headers &headers);
  834. bool send(Request &req, Response &res, Error &error);
  835. Result send(const Request &req);
  836. size_t is_socket_open() const;
  837. socket_t socket() const;
  838. void stop();
  839. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  840. void set_default_headers(Headers headers);
  841. void set_address_family(int family);
  842. void set_tcp_nodelay(bool on);
  843. void set_socket_options(SocketOptions socket_options);
  844. void set_connection_timeout(time_t sec, time_t usec = 0);
  845. template <class Rep, class Period>
  846. void
  847. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  848. void set_read_timeout(time_t sec, time_t usec = 0);
  849. template <class Rep, class Period>
  850. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  851. void set_write_timeout(time_t sec, time_t usec = 0);
  852. template <class Rep, class Period>
  853. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  854. void set_basic_auth(const std::string &username, const std::string &password);
  855. void set_bearer_token_auth(const std::string &token);
  856. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  857. void set_digest_auth(const std::string &username,
  858. const std::string &password);
  859. #endif
  860. void set_keep_alive(bool on);
  861. void set_follow_location(bool on);
  862. void set_url_encode(bool on);
  863. void set_compress(bool on);
  864. void set_decompress(bool on);
  865. void set_interface(const std::string &intf);
  866. void set_proxy(const std::string &host, int port);
  867. void set_proxy_basic_auth(const std::string &username,
  868. const std::string &password);
  869. void set_proxy_bearer_token_auth(const std::string &token);
  870. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  871. void set_proxy_digest_auth(const std::string &username,
  872. const std::string &password);
  873. #endif
  874. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  875. void set_ca_cert_path(const std::string &ca_cert_file_path,
  876. const std::string &ca_cert_dir_path = std::string());
  877. void set_ca_cert_store(X509_STORE *ca_cert_store);
  878. #endif
  879. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  880. void enable_server_certificate_verification(bool enabled);
  881. #endif
  882. void set_logger(Logger logger);
  883. protected:
  884. struct Socket {
  885. socket_t sock = INVALID_SOCKET;
  886. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  887. SSL *ssl = nullptr;
  888. #endif
  889. bool is_open() const { return sock != INVALID_SOCKET; }
  890. };
  891. Result send_(Request &&req);
  892. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  893. // All of:
  894. // shutdown_ssl
  895. // shutdown_socket
  896. // close_socket
  897. // should ONLY be called when socket_mutex_ is locked.
  898. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  899. // with a DIFFERENT thread sending requests using that socket.
  900. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  901. void shutdown_socket(Socket &socket);
  902. void close_socket(Socket &socket);
  903. bool process_request(Stream &strm, Request &req, Response &res,
  904. bool close_connection, Error &error);
  905. bool write_content_with_provider(Stream &strm, const Request &req,
  906. Error &error);
  907. void copy_settings(const ClientImpl &rhs);
  908. // Socket endoint information
  909. const std::string host_;
  910. const int port_;
  911. const std::string host_and_port_;
  912. // Current open socket
  913. Socket socket_;
  914. mutable std::mutex socket_mutex_;
  915. std::recursive_mutex request_mutex_;
  916. // These are all protected under socket_mutex
  917. size_t socket_requests_in_flight_ = 0;
  918. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  919. bool socket_should_be_closed_when_request_is_done_ = false;
  920. // Hostname-IP map
  921. std::map<std::string, std::string> addr_map_;
  922. // Default headers
  923. Headers default_headers_;
  924. // Settings
  925. std::string client_cert_path_;
  926. std::string client_key_path_;
  927. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  928. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  929. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  930. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  931. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  932. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  933. std::string basic_auth_username_;
  934. std::string basic_auth_password_;
  935. std::string bearer_token_auth_token_;
  936. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  937. std::string digest_auth_username_;
  938. std::string digest_auth_password_;
  939. #endif
  940. bool keep_alive_ = false;
  941. bool follow_location_ = false;
  942. bool url_encode_ = true;
  943. int address_family_ = AF_UNSPEC;
  944. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  945. SocketOptions socket_options_ = nullptr;
  946. bool compress_ = false;
  947. bool decompress_ = true;
  948. std::string interface_;
  949. std::string proxy_host_;
  950. int proxy_port_ = -1;
  951. std::string proxy_basic_auth_username_;
  952. std::string proxy_basic_auth_password_;
  953. std::string proxy_bearer_token_auth_token_;
  954. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  955. std::string proxy_digest_auth_username_;
  956. std::string proxy_digest_auth_password_;
  957. #endif
  958. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  959. std::string ca_cert_file_path_;
  960. std::string ca_cert_dir_path_;
  961. X509_STORE *ca_cert_store_ = nullptr;
  962. #endif
  963. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  964. bool server_certificate_verification_ = true;
  965. #endif
  966. Logger logger_;
  967. private:
  968. socket_t create_client_socket(Error &error) const;
  969. bool read_response_line(Stream &strm, const Request &req, Response &res);
  970. bool write_request(Stream &strm, Request &req, bool close_connection,
  971. Error &error);
  972. bool redirect(Request &req, Response &res, Error &error);
  973. bool handle_request(Stream &strm, Request &req, Response &res,
  974. bool close_connection, Error &error);
  975. std::unique_ptr<Response> send_with_content_provider(
  976. Request &req, const char *body, size_t content_length,
  977. ContentProvider content_provider,
  978. ContentProviderWithoutLength content_provider_without_length,
  979. const std::string &content_type, Error &error);
  980. Result send_with_content_provider(
  981. const std::string &method, const std::string &path,
  982. const Headers &headers, const char *body, size_t content_length,
  983. ContentProvider content_provider,
  984. ContentProviderWithoutLength content_provider_without_length,
  985. const std::string &content_type);
  986. ContentProviderWithoutLength get_multipart_content_provider(
  987. const std::string &boundary, const MultipartFormDataItems &items,
  988. const MultipartFormDataProviderItems &provider_items);
  989. std::string adjust_host_string(const std::string &host) const;
  990. virtual bool process_socket(const Socket &socket,
  991. std::function<bool(Stream &strm)> callback);
  992. virtual bool is_ssl() const;
  993. };
  994. class Client {
  995. public:
  996. // Universal interface
  997. explicit Client(const std::string &scheme_host_port);
  998. explicit Client(const std::string &scheme_host_port,
  999. const std::string &client_cert_path,
  1000. const std::string &client_key_path);
  1001. // HTTP only interface
  1002. explicit Client(const std::string &host, int port);
  1003. explicit Client(const std::string &host, int port,
  1004. const std::string &client_cert_path,
  1005. const std::string &client_key_path);
  1006. Client(Client &&) = default;
  1007. ~Client();
  1008. bool is_valid() const;
  1009. Result Get(const std::string &path);
  1010. Result Get(const std::string &path, const Headers &headers);
  1011. Result Get(const std::string &path, Progress progress);
  1012. Result Get(const std::string &path, const Headers &headers,
  1013. Progress progress);
  1014. Result Get(const std::string &path, ContentReceiver content_receiver);
  1015. Result Get(const std::string &path, const Headers &headers,
  1016. ContentReceiver content_receiver);
  1017. Result Get(const std::string &path, ContentReceiver content_receiver,
  1018. Progress progress);
  1019. Result Get(const std::string &path, const Headers &headers,
  1020. ContentReceiver content_receiver, Progress progress);
  1021. Result Get(const std::string &path, ResponseHandler response_handler,
  1022. ContentReceiver content_receiver);
  1023. Result Get(const std::string &path, const Headers &headers,
  1024. ResponseHandler response_handler,
  1025. ContentReceiver content_receiver);
  1026. Result Get(const std::string &path, const Headers &headers,
  1027. ResponseHandler response_handler, ContentReceiver content_receiver,
  1028. Progress progress);
  1029. Result Get(const std::string &path, ResponseHandler response_handler,
  1030. ContentReceiver content_receiver, Progress progress);
  1031. Result Get(const std::string &path, const Params &params,
  1032. const Headers &headers, Progress progress = nullptr);
  1033. Result Get(const std::string &path, const Params &params,
  1034. const Headers &headers, ContentReceiver content_receiver,
  1035. Progress progress = nullptr);
  1036. Result Get(const std::string &path, const Params &params,
  1037. const Headers &headers, ResponseHandler response_handler,
  1038. ContentReceiver content_receiver, Progress progress = nullptr);
  1039. Result Head(const std::string &path);
  1040. Result Head(const std::string &path, const Headers &headers);
  1041. Result Post(const std::string &path);
  1042. Result Post(const std::string &path, const Headers &headers);
  1043. Result Post(const std::string &path, const char *body, size_t content_length,
  1044. const std::string &content_type);
  1045. Result Post(const std::string &path, const Headers &headers, const char *body,
  1046. size_t content_length, const std::string &content_type);
  1047. Result Post(const std::string &path, const std::string &body,
  1048. const std::string &content_type);
  1049. Result Post(const std::string &path, const Headers &headers,
  1050. const std::string &body, const std::string &content_type);
  1051. Result Post(const std::string &path, size_t content_length,
  1052. ContentProvider content_provider,
  1053. const std::string &content_type);
  1054. Result Post(const std::string &path,
  1055. ContentProviderWithoutLength content_provider,
  1056. const std::string &content_type);
  1057. Result Post(const std::string &path, const Headers &headers,
  1058. size_t content_length, ContentProvider content_provider,
  1059. const std::string &content_type);
  1060. Result Post(const std::string &path, const Headers &headers,
  1061. ContentProviderWithoutLength content_provider,
  1062. const std::string &content_type);
  1063. Result Post(const std::string &path, const Params &params);
  1064. Result Post(const std::string &path, const Headers &headers,
  1065. const Params &params);
  1066. Result Post(const std::string &path, const MultipartFormDataItems &items);
  1067. Result Post(const std::string &path, const Headers &headers,
  1068. const MultipartFormDataItems &items);
  1069. Result Post(const std::string &path, const Headers &headers,
  1070. const MultipartFormDataItems &items, const std::string &boundary);
  1071. Result Post(const std::string &path, const Headers &headers,
  1072. const MultipartFormDataItems &items,
  1073. const MultipartFormDataProviderItems &provider_items);
  1074. Result Put(const std::string &path);
  1075. Result Put(const std::string &path, const char *body, size_t content_length,
  1076. const std::string &content_type);
  1077. Result Put(const std::string &path, const Headers &headers, const char *body,
  1078. size_t content_length, const std::string &content_type);
  1079. Result Put(const std::string &path, const std::string &body,
  1080. const std::string &content_type);
  1081. Result Put(const std::string &path, const Headers &headers,
  1082. const std::string &body, const std::string &content_type);
  1083. Result Put(const std::string &path, size_t content_length,
  1084. ContentProvider content_provider, const std::string &content_type);
  1085. Result Put(const std::string &path,
  1086. ContentProviderWithoutLength content_provider,
  1087. const std::string &content_type);
  1088. Result Put(const std::string &path, const Headers &headers,
  1089. size_t content_length, ContentProvider content_provider,
  1090. const std::string &content_type);
  1091. Result Put(const std::string &path, const Headers &headers,
  1092. ContentProviderWithoutLength content_provider,
  1093. const std::string &content_type);
  1094. Result Put(const std::string &path, const Params &params);
  1095. Result Put(const std::string &path, const Headers &headers,
  1096. const Params &params);
  1097. Result Put(const std::string &path, const MultipartFormDataItems &items);
  1098. Result Put(const std::string &path, const Headers &headers,
  1099. const MultipartFormDataItems &items);
  1100. Result Put(const std::string &path, const Headers &headers,
  1101. const MultipartFormDataItems &items, const std::string &boundary);
  1102. Result Put(const std::string &path, const Headers &headers,
  1103. const MultipartFormDataItems &items,
  1104. const MultipartFormDataProviderItems &provider_items);
  1105. Result Patch(const std::string &path);
  1106. Result Patch(const std::string &path, const char *body, size_t content_length,
  1107. const std::string &content_type);
  1108. Result Patch(const std::string &path, const Headers &headers,
  1109. const char *body, size_t content_length,
  1110. const std::string &content_type);
  1111. Result Patch(const std::string &path, const std::string &body,
  1112. const std::string &content_type);
  1113. Result Patch(const std::string &path, const Headers &headers,
  1114. const std::string &body, const std::string &content_type);
  1115. Result Patch(const std::string &path, size_t content_length,
  1116. ContentProvider content_provider,
  1117. const std::string &content_type);
  1118. Result Patch(const std::string &path,
  1119. ContentProviderWithoutLength content_provider,
  1120. const std::string &content_type);
  1121. Result Patch(const std::string &path, const Headers &headers,
  1122. size_t content_length, ContentProvider content_provider,
  1123. const std::string &content_type);
  1124. Result Patch(const std::string &path, const Headers &headers,
  1125. ContentProviderWithoutLength content_provider,
  1126. const std::string &content_type);
  1127. Result Delete(const std::string &path);
  1128. Result Delete(const std::string &path, const Headers &headers);
  1129. Result Delete(const std::string &path, const char *body,
  1130. size_t content_length, const std::string &content_type);
  1131. Result Delete(const std::string &path, const Headers &headers,
  1132. const char *body, size_t content_length,
  1133. const std::string &content_type);
  1134. Result Delete(const std::string &path, const std::string &body,
  1135. const std::string &content_type);
  1136. Result Delete(const std::string &path, const Headers &headers,
  1137. const std::string &body, const std::string &content_type);
  1138. Result Options(const std::string &path);
  1139. Result Options(const std::string &path, const Headers &headers);
  1140. bool send(Request &req, Response &res, Error &error);
  1141. Result send(const Request &req);
  1142. size_t is_socket_open() const;
  1143. socket_t socket() const;
  1144. void stop();
  1145. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1146. void set_default_headers(Headers headers);
  1147. void set_address_family(int family);
  1148. void set_tcp_nodelay(bool on);
  1149. void set_socket_options(SocketOptions socket_options);
  1150. void set_connection_timeout(time_t sec, time_t usec = 0);
  1151. template <class Rep, class Period>
  1152. void
  1153. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1154. void set_read_timeout(time_t sec, time_t usec = 0);
  1155. template <class Rep, class Period>
  1156. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1157. void set_write_timeout(time_t sec, time_t usec = 0);
  1158. template <class Rep, class Period>
  1159. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1160. void set_basic_auth(const std::string &username, const std::string &password);
  1161. void set_bearer_token_auth(const std::string &token);
  1162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1163. void set_digest_auth(const std::string &username,
  1164. const std::string &password);
  1165. #endif
  1166. void set_keep_alive(bool on);
  1167. void set_follow_location(bool on);
  1168. void set_url_encode(bool on);
  1169. void set_compress(bool on);
  1170. void set_decompress(bool on);
  1171. void set_interface(const std::string &intf);
  1172. void set_proxy(const std::string &host, int port);
  1173. void set_proxy_basic_auth(const std::string &username,
  1174. const std::string &password);
  1175. void set_proxy_bearer_token_auth(const std::string &token);
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. void set_proxy_digest_auth(const std::string &username,
  1178. const std::string &password);
  1179. #endif
  1180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1181. void enable_server_certificate_verification(bool enabled);
  1182. #endif
  1183. void set_logger(Logger logger);
  1184. // SSL
  1185. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1186. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1187. const std::string &ca_cert_dir_path = std::string());
  1188. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1189. long get_openssl_verify_result() const;
  1190. SSL_CTX *ssl_context() const;
  1191. #endif
  1192. private:
  1193. std::unique_ptr<ClientImpl> cli_;
  1194. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1195. bool is_ssl_ = false;
  1196. #endif
  1197. };
  1198. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1199. class SSLServer : public Server {
  1200. public:
  1201. SSLServer(const char *cert_path, const char *private_key_path,
  1202. const char *client_ca_cert_file_path = nullptr,
  1203. const char *client_ca_cert_dir_path = nullptr,
  1204. const char *private_key_password = nullptr);
  1205. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1206. X509_STORE *client_ca_cert_store = nullptr);
  1207. SSLServer(
  1208. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1209. ~SSLServer() override;
  1210. bool is_valid() const override;
  1211. SSL_CTX *ssl_context() const;
  1212. private:
  1213. bool process_and_close_socket(socket_t sock) override;
  1214. SSL_CTX *ctx_;
  1215. std::mutex ctx_mutex_;
  1216. };
  1217. class SSLClient : public ClientImpl {
  1218. public:
  1219. explicit SSLClient(const std::string &host);
  1220. explicit SSLClient(const std::string &host, int port);
  1221. explicit SSLClient(const std::string &host, int port,
  1222. const std::string &client_cert_path,
  1223. const std::string &client_key_path);
  1224. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1225. EVP_PKEY *client_key);
  1226. ~SSLClient() override;
  1227. bool is_valid() const override;
  1228. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1229. long get_openssl_verify_result() const;
  1230. SSL_CTX *ssl_context() const;
  1231. private:
  1232. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1233. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1234. void shutdown_ssl_impl(Socket &socket, bool shutdown_socket);
  1235. bool process_socket(const Socket &socket,
  1236. std::function<bool(Stream &strm)> callback) override;
  1237. bool is_ssl() const override;
  1238. bool connect_with_proxy(Socket &sock, Response &res, bool &success,
  1239. Error &error);
  1240. bool initialize_ssl(Socket &socket, Error &error);
  1241. bool load_certs();
  1242. bool verify_host(X509 *server_cert) const;
  1243. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1244. bool verify_host_with_common_name(X509 *server_cert) const;
  1245. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1246. SSL_CTX *ctx_;
  1247. std::mutex ctx_mutex_;
  1248. std::once_flag initialize_cert_;
  1249. std::vector<std::string> host_components_;
  1250. long verify_result_ = 0;
  1251. friend class ClientImpl;
  1252. };
  1253. #endif
  1254. /*
  1255. * Implementation of template methods.
  1256. */
  1257. namespace detail {
  1258. template <typename T, typename U>
  1259. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1260. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1261. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1262. duration - std::chrono::seconds(sec))
  1263. .count();
  1264. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1265. }
  1266. template <typename T>
  1267. inline T get_header_value(const Headers & /*headers*/,
  1268. const std::string & /*key*/, size_t /*id*/ = 0,
  1269. uint64_t /*def*/ = 0) {}
  1270. template <>
  1271. inline uint64_t get_header_value<uint64_t>(const Headers &headers,
  1272. const std::string &key, size_t id,
  1273. uint64_t def) {
  1274. auto rng = headers.equal_range(key);
  1275. auto it = rng.first;
  1276. std::advance(it, static_cast<ssize_t>(id));
  1277. if (it != rng.second) {
  1278. return std::strtoull(it->second.data(), nullptr, 10);
  1279. }
  1280. return def;
  1281. }
  1282. } // namespace detail
  1283. template <typename T>
  1284. inline T Request::get_header_value(const std::string &key, size_t id) const {
  1285. return detail::get_header_value<T>(headers, key, id, 0);
  1286. }
  1287. template <typename T>
  1288. inline T Response::get_header_value(const std::string &key, size_t id) const {
  1289. return detail::get_header_value<T>(headers, key, id, 0);
  1290. }
  1291. template <typename... Args>
  1292. inline ssize_t Stream::write_format(const char *fmt, const Args &...args) {
  1293. const auto bufsiz = 2048;
  1294. std::array<char, bufsiz> buf{};
  1295. auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...);
  1296. if (sn <= 0) { return sn; }
  1297. auto n = static_cast<size_t>(sn);
  1298. if (n >= buf.size() - 1) {
  1299. std::vector<char> glowable_buf(buf.size());
  1300. while (n >= glowable_buf.size() - 1) {
  1301. glowable_buf.resize(glowable_buf.size() * 2);
  1302. n = static_cast<size_t>(
  1303. snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...));
  1304. }
  1305. return write(&glowable_buf[0], n);
  1306. } else {
  1307. return write(buf.data(), n);
  1308. }
  1309. }
  1310. inline void default_socket_options(socket_t sock) {
  1311. int yes = 1;
  1312. #ifdef _WIN32
  1313. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
  1314. sizeof(yes));
  1315. setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  1316. reinterpret_cast<char *>(&yes), sizeof(yes));
  1317. #else
  1318. #ifdef SO_REUSEPORT
  1319. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<void *>(&yes),
  1320. sizeof(yes));
  1321. #else
  1322. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void *>(&yes),
  1323. sizeof(yes));
  1324. #endif
  1325. #endif
  1326. }
  1327. template <class Rep, class Period>
  1328. inline Server &
  1329. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1330. detail::duration_to_sec_and_usec(
  1331. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1332. return *this;
  1333. }
  1334. template <class Rep, class Period>
  1335. inline Server &
  1336. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1337. detail::duration_to_sec_and_usec(
  1338. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1339. return *this;
  1340. }
  1341. template <class Rep, class Period>
  1342. inline Server &
  1343. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1344. detail::duration_to_sec_and_usec(
  1345. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1346. return *this;
  1347. }
  1348. inline std::string to_string(const Error error) {
  1349. switch (error) {
  1350. case Error::Success: return "Success (no error)";
  1351. case Error::Connection: return "Could not establish connection";
  1352. case Error::BindIPAddress: return "Failed to bind IP address";
  1353. case Error::Read: return "Failed to read connection";
  1354. case Error::Write: return "Failed to write connection";
  1355. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  1356. case Error::Canceled: return "Connection handling canceled";
  1357. case Error::SSLConnection: return "SSL connection failed";
  1358. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  1359. case Error::SSLServerVerification: return "SSL server verification failed";
  1360. case Error::UnsupportedMultipartBoundaryChars:
  1361. return "Unsupported HTTP multipart boundary characters";
  1362. case Error::Compression: return "Compression failed";
  1363. case Error::ConnectionTimeout: return "Connection timed out";
  1364. case Error::Unknown: return "Unknown";
  1365. default: break;
  1366. }
  1367. return "Invalid";
  1368. }
  1369. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  1370. os << to_string(obj);
  1371. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  1372. return os;
  1373. }
  1374. template <typename T>
  1375. inline T Result::get_request_header_value(const std::string &key,
  1376. size_t id) const {
  1377. return detail::get_header_value<T>(request_headers_, key, id, 0);
  1378. }
  1379. template <class Rep, class Period>
  1380. inline void ClientImpl::set_connection_timeout(
  1381. const std::chrono::duration<Rep, Period> &duration) {
  1382. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1383. set_connection_timeout(sec, usec);
  1384. });
  1385. }
  1386. template <class Rep, class Period>
  1387. inline void ClientImpl::set_read_timeout(
  1388. const std::chrono::duration<Rep, Period> &duration) {
  1389. detail::duration_to_sec_and_usec(
  1390. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1391. }
  1392. template <class Rep, class Period>
  1393. inline void ClientImpl::set_write_timeout(
  1394. const std::chrono::duration<Rep, Period> &duration) {
  1395. detail::duration_to_sec_and_usec(
  1396. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1397. }
  1398. template <class Rep, class Period>
  1399. inline void Client::set_connection_timeout(
  1400. const std::chrono::duration<Rep, Period> &duration) {
  1401. cli_->set_connection_timeout(duration);
  1402. }
  1403. template <class Rep, class Period>
  1404. inline void
  1405. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1406. cli_->set_read_timeout(duration);
  1407. }
  1408. template <class Rep, class Period>
  1409. inline void
  1410. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1411. cli_->set_write_timeout(duration);
  1412. }
  1413. /*
  1414. * Forward declarations and types that will be part of the .h file if split into
  1415. * .h + .cc.
  1416. */
  1417. std::string hosted_at(const std::string &hostname);
  1418. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1419. std::string append_query_params(const std::string &path, const Params &params);
  1420. std::pair<std::string, std::string> make_range_header(Ranges ranges);
  1421. std::pair<std::string, std::string>
  1422. make_basic_authentication_header(const std::string &username,
  1423. const std::string &password,
  1424. bool is_proxy = false);
  1425. namespace detail {
  1426. std::string encode_query_param(const std::string &value);
  1427. std::string decode_url(const std::string &s, bool convert_plus_to_space);
  1428. void read_file(const std::string &path, std::string &out);
  1429. std::string trim_copy(const std::string &s);
  1430. void split(const char *b, const char *e, char d,
  1431. std::function<void(const char *, const char *)> fn);
  1432. bool process_client_socket(socket_t sock, time_t read_timeout_sec,
  1433. time_t read_timeout_usec, time_t write_timeout_sec,
  1434. time_t write_timeout_usec,
  1435. std::function<bool(Stream &)> callback);
  1436. socket_t create_client_socket(
  1437. const std::string &host, const std::string &ip, int port,
  1438. int address_family, bool tcp_nodelay, SocketOptions socket_options,
  1439. time_t connection_timeout_sec, time_t connection_timeout_usec,
  1440. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  1441. time_t write_timeout_usec, const std::string &intf, Error &error);
  1442. const char *get_header_value(const Headers &headers, const std::string &key,
  1443. size_t id = 0, const char *def = nullptr);
  1444. std::string params_to_query_str(const Params &params);
  1445. void parse_query_text(const std::string &s, Params &params);
  1446. bool parse_range_header(const std::string &s, Ranges &ranges);
  1447. int close_socket(socket_t sock);
  1448. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  1449. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  1450. enum class EncodingType { None = 0, Gzip, Brotli };
  1451. EncodingType encoding_type(const Request &req, const Response &res);
  1452. class BufferStream : public Stream {
  1453. public:
  1454. BufferStream() = default;
  1455. ~BufferStream() override = default;
  1456. bool is_readable() const override;
  1457. bool is_writable() const override;
  1458. ssize_t read(char *ptr, size_t size) override;
  1459. ssize_t write(const char *ptr, size_t size) override;
  1460. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1461. void get_local_ip_and_port(std::string &ip, int &port) const override;
  1462. socket_t socket() const override;
  1463. const std::string &get_buffer() const;
  1464. private:
  1465. std::string buffer;
  1466. size_t position = 0;
  1467. };
  1468. class compressor {
  1469. public:
  1470. virtual ~compressor() = default;
  1471. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1472. virtual bool compress(const char *data, size_t data_length, bool last,
  1473. Callback callback) = 0;
  1474. };
  1475. class decompressor {
  1476. public:
  1477. virtual ~decompressor() = default;
  1478. virtual bool is_valid() const = 0;
  1479. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1480. virtual bool decompress(const char *data, size_t data_length,
  1481. Callback callback) = 0;
  1482. };
  1483. class nocompressor : public compressor {
  1484. public:
  1485. virtual ~nocompressor() = default;
  1486. bool compress(const char *data, size_t data_length, bool /*last*/,
  1487. Callback callback) override;
  1488. };
  1489. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1490. class gzip_compressor : public compressor {
  1491. public:
  1492. gzip_compressor();
  1493. ~gzip_compressor();
  1494. bool compress(const char *data, size_t data_length, bool last,
  1495. Callback callback) override;
  1496. private:
  1497. bool is_valid_ = false;
  1498. z_stream strm_;
  1499. };
  1500. class gzip_decompressor : public decompressor {
  1501. public:
  1502. gzip_decompressor();
  1503. ~gzip_decompressor();
  1504. bool is_valid() const override;
  1505. bool decompress(const char *data, size_t data_length,
  1506. Callback callback) override;
  1507. private:
  1508. bool is_valid_ = false;
  1509. z_stream strm_;
  1510. };
  1511. #endif
  1512. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1513. class brotli_compressor : public compressor {
  1514. public:
  1515. brotli_compressor();
  1516. ~brotli_compressor();
  1517. bool compress(const char *data, size_t data_length, bool last,
  1518. Callback callback) override;
  1519. private:
  1520. BrotliEncoderState *state_ = nullptr;
  1521. };
  1522. class brotli_decompressor : public decompressor {
  1523. public:
  1524. brotli_decompressor();
  1525. ~brotli_decompressor();
  1526. bool is_valid() const override;
  1527. bool decompress(const char *data, size_t data_length,
  1528. Callback callback) override;
  1529. private:
  1530. BrotliDecoderResult decoder_r;
  1531. BrotliDecoderState *decoder_s = nullptr;
  1532. };
  1533. #endif
  1534. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  1535. // to store data. The call can set memory on stack for performance.
  1536. class stream_line_reader {
  1537. public:
  1538. stream_line_reader(Stream &strm, char *fixed_buffer,
  1539. size_t fixed_buffer_size);
  1540. const char *ptr() const;
  1541. size_t size() const;
  1542. bool end_with_crlf() const;
  1543. bool getline();
  1544. private:
  1545. void append(char c);
  1546. Stream &strm_;
  1547. char *fixed_buffer_;
  1548. const size_t fixed_buffer_size_;
  1549. size_t fixed_buffer_used_size_ = 0;
  1550. std::string glowable_buffer_;
  1551. };
  1552. } // namespace detail
  1553. // ----------------------------------------------------------------------------
  1554. /*
  1555. * Implementation that will be part of the .cc file if split into .h + .cc.
  1556. */
  1557. namespace detail {
  1558. inline bool is_hex(char c, int &v) {
  1559. if (0x20 <= c && isdigit(c)) {
  1560. v = c - '0';
  1561. return true;
  1562. } else if ('A' <= c && c <= 'F') {
  1563. v = c - 'A' + 10;
  1564. return true;
  1565. } else if ('a' <= c && c <= 'f') {
  1566. v = c - 'a' + 10;
  1567. return true;
  1568. }
  1569. return false;
  1570. }
  1571. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  1572. int &val) {
  1573. if (i >= s.size()) { return false; }
  1574. val = 0;
  1575. for (; cnt; i++, cnt--) {
  1576. if (!s[i]) { return false; }
  1577. int v = 0;
  1578. if (is_hex(s[i], v)) {
  1579. val = val * 16 + v;
  1580. } else {
  1581. return false;
  1582. }
  1583. }
  1584. return true;
  1585. }
  1586. inline std::string from_i_to_hex(size_t n) {
  1587. const char *charset = "0123456789abcdef";
  1588. std::string ret;
  1589. do {
  1590. ret = charset[n & 15] + ret;
  1591. n >>= 4;
  1592. } while (n > 0);
  1593. return ret;
  1594. }
  1595. inline size_t to_utf8(int code, char *buff) {
  1596. if (code < 0x0080) {
  1597. buff[0] = (code & 0x7F);
  1598. return 1;
  1599. } else if (code < 0x0800) {
  1600. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  1601. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  1602. return 2;
  1603. } else if (code < 0xD800) {
  1604. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  1605. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1606. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  1607. return 3;
  1608. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  1609. return 0;
  1610. } else if (code < 0x10000) {
  1611. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  1612. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1613. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  1614. return 3;
  1615. } else if (code < 0x110000) {
  1616. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  1617. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  1618. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1619. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  1620. return 4;
  1621. }
  1622. // NOTREACHED
  1623. return 0;
  1624. }
  1625. // NOTE: This code came up with the following stackoverflow post:
  1626. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  1627. inline std::string base64_encode(const std::string &in) {
  1628. static const auto lookup =
  1629. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1630. std::string out;
  1631. out.reserve(in.size());
  1632. int val = 0;
  1633. int valb = -6;
  1634. for (auto c : in) {
  1635. val = (val << 8) + static_cast<uint8_t>(c);
  1636. valb += 8;
  1637. while (valb >= 0) {
  1638. out.push_back(lookup[(val >> valb) & 0x3F]);
  1639. valb -= 6;
  1640. }
  1641. }
  1642. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  1643. while (out.size() % 4) {
  1644. out.push_back('=');
  1645. }
  1646. return out;
  1647. }
  1648. inline bool is_file(const std::string &path) {
  1649. #ifdef _WIN32
  1650. return _access_s(path.c_str(), 0) == 0;
  1651. #else
  1652. struct stat st;
  1653. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  1654. #endif
  1655. }
  1656. inline bool is_dir(const std::string &path) {
  1657. struct stat st;
  1658. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  1659. }
  1660. inline bool is_valid_path(const std::string &path) {
  1661. size_t level = 0;
  1662. size_t i = 0;
  1663. // Skip slash
  1664. while (i < path.size() && path[i] == '/') {
  1665. i++;
  1666. }
  1667. while (i < path.size()) {
  1668. // Read component
  1669. auto beg = i;
  1670. while (i < path.size() && path[i] != '/') {
  1671. i++;
  1672. }
  1673. auto len = i - beg;
  1674. assert(len > 0);
  1675. if (!path.compare(beg, len, ".")) {
  1676. ;
  1677. } else if (!path.compare(beg, len, "..")) {
  1678. if (level == 0) { return false; }
  1679. level--;
  1680. } else {
  1681. level++;
  1682. }
  1683. // Skip slash
  1684. while (i < path.size() && path[i] == '/') {
  1685. i++;
  1686. }
  1687. }
  1688. return true;
  1689. }
  1690. inline std::string encode_query_param(const std::string &value) {
  1691. std::ostringstream escaped;
  1692. escaped.fill('0');
  1693. escaped << std::hex;
  1694. for (auto c : value) {
  1695. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  1696. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  1697. c == ')') {
  1698. escaped << c;
  1699. } else {
  1700. escaped << std::uppercase;
  1701. escaped << '%' << std::setw(2)
  1702. << static_cast<int>(static_cast<unsigned char>(c));
  1703. escaped << std::nouppercase;
  1704. }
  1705. }
  1706. return escaped.str();
  1707. }
  1708. inline std::string encode_url(const std::string &s) {
  1709. std::string result;
  1710. result.reserve(s.size());
  1711. for (size_t i = 0; s[i]; i++) {
  1712. switch (s[i]) {
  1713. case ' ': result += "%20"; break;
  1714. case '+': result += "%2B"; break;
  1715. case '\r': result += "%0D"; break;
  1716. case '\n': result += "%0A"; break;
  1717. case '\'': result += "%27"; break;
  1718. case ',': result += "%2C"; break;
  1719. // case ':': result += "%3A"; break; // ok? probably...
  1720. case ';': result += "%3B"; break;
  1721. default:
  1722. auto c = static_cast<uint8_t>(s[i]);
  1723. if (c >= 0x80) {
  1724. result += '%';
  1725. char hex[4];
  1726. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  1727. assert(len == 2);
  1728. result.append(hex, static_cast<size_t>(len));
  1729. } else {
  1730. result += s[i];
  1731. }
  1732. break;
  1733. }
  1734. }
  1735. return result;
  1736. }
  1737. inline std::string decode_url(const std::string &s,
  1738. bool convert_plus_to_space) {
  1739. std::string result;
  1740. for (size_t i = 0; i < s.size(); i++) {
  1741. if (s[i] == '%' && i + 1 < s.size()) {
  1742. if (s[i + 1] == 'u') {
  1743. int val = 0;
  1744. if (from_hex_to_i(s, i + 2, 4, val)) {
  1745. // 4 digits Unicode codes
  1746. char buff[4];
  1747. size_t len = to_utf8(val, buff);
  1748. if (len > 0) { result.append(buff, len); }
  1749. i += 5; // 'u0000'
  1750. } else {
  1751. result += s[i];
  1752. }
  1753. } else {
  1754. int val = 0;
  1755. if (from_hex_to_i(s, i + 1, 2, val)) {
  1756. // 2 digits hex codes
  1757. result += static_cast<char>(val);
  1758. i += 2; // '00'
  1759. } else {
  1760. result += s[i];
  1761. }
  1762. }
  1763. } else if (convert_plus_to_space && s[i] == '+') {
  1764. result += ' ';
  1765. } else {
  1766. result += s[i];
  1767. }
  1768. }
  1769. return result;
  1770. }
  1771. inline void read_file(const std::string &path, std::string &out) {
  1772. std::ifstream fs(path, std::ios_base::binary);
  1773. fs.seekg(0, std::ios_base::end);
  1774. auto size = fs.tellg();
  1775. fs.seekg(0);
  1776. out.resize(static_cast<size_t>(size));
  1777. fs.read(&out[0], static_cast<std::streamsize>(size));
  1778. }
  1779. inline std::string file_extension(const std::string &path) {
  1780. std::smatch m;
  1781. static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  1782. if (std::regex_search(path, m, re)) { return m[1].str(); }
  1783. return std::string();
  1784. }
  1785. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  1786. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  1787. size_t right) {
  1788. while (b + left < e && is_space_or_tab(b[left])) {
  1789. left++;
  1790. }
  1791. while (right > 0 && is_space_or_tab(b[right - 1])) {
  1792. right--;
  1793. }
  1794. return std::make_pair(left, right);
  1795. }
  1796. inline std::string trim_copy(const std::string &s) {
  1797. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  1798. return s.substr(r.first, r.second - r.first);
  1799. }
  1800. inline void split(const char *b, const char *e, char d,
  1801. std::function<void(const char *, const char *)> fn) {
  1802. size_t i = 0;
  1803. size_t beg = 0;
  1804. while (e ? (b + i < e) : (b[i] != '\0')) {
  1805. if (b[i] == d) {
  1806. auto r = trim(b, e, beg, i);
  1807. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  1808. beg = i + 1;
  1809. }
  1810. i++;
  1811. }
  1812. if (i) {
  1813. auto r = trim(b, e, beg, i);
  1814. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  1815. }
  1816. }
  1817. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  1818. size_t fixed_buffer_size)
  1819. : strm_(strm), fixed_buffer_(fixed_buffer),
  1820. fixed_buffer_size_(fixed_buffer_size) {}
  1821. inline const char *stream_line_reader::ptr() const {
  1822. if (glowable_buffer_.empty()) {
  1823. return fixed_buffer_;
  1824. } else {
  1825. return glowable_buffer_.data();
  1826. }
  1827. }
  1828. inline size_t stream_line_reader::size() const {
  1829. if (glowable_buffer_.empty()) {
  1830. return fixed_buffer_used_size_;
  1831. } else {
  1832. return glowable_buffer_.size();
  1833. }
  1834. }
  1835. inline bool stream_line_reader::end_with_crlf() const {
  1836. auto end = ptr() + size();
  1837. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  1838. }
  1839. inline bool stream_line_reader::getline() {
  1840. fixed_buffer_used_size_ = 0;
  1841. glowable_buffer_.clear();
  1842. for (size_t i = 0;; i++) {
  1843. char byte;
  1844. auto n = strm_.read(&byte, 1);
  1845. if (n < 0) {
  1846. return false;
  1847. } else if (n == 0) {
  1848. if (i == 0) {
  1849. return false;
  1850. } else {
  1851. break;
  1852. }
  1853. }
  1854. append(byte);
  1855. if (byte == '\n') { break; }
  1856. }
  1857. return true;
  1858. }
  1859. inline void stream_line_reader::append(char c) {
  1860. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  1861. fixed_buffer_[fixed_buffer_used_size_++] = c;
  1862. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  1863. } else {
  1864. if (glowable_buffer_.empty()) {
  1865. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  1866. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  1867. }
  1868. glowable_buffer_ += c;
  1869. }
  1870. }
  1871. inline int close_socket(socket_t sock) {
  1872. #ifdef _WIN32
  1873. return closesocket(sock);
  1874. #else
  1875. return close(sock);
  1876. #endif
  1877. }
  1878. template <typename T> inline ssize_t handle_EINTR(T fn) {
  1879. ssize_t res = false;
  1880. while (true) {
  1881. res = fn();
  1882. if (res < 0 && errno == EINTR) { continue; }
  1883. break;
  1884. }
  1885. return res;
  1886. }
  1887. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  1888. return handle_EINTR([&]() {
  1889. return recv(sock,
  1890. #ifdef _WIN32
  1891. static_cast<char *>(ptr), static_cast<int>(size),
  1892. #else
  1893. ptr, size,
  1894. #endif
  1895. flags);
  1896. });
  1897. }
  1898. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  1899. int flags) {
  1900. return handle_EINTR([&]() {
  1901. return send(sock,
  1902. #ifdef _WIN32
  1903. static_cast<const char *>(ptr), static_cast<int>(size),
  1904. #else
  1905. ptr, size,
  1906. #endif
  1907. flags);
  1908. });
  1909. }
  1910. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  1911. #ifdef CPPHTTPLIB_USE_POLL
  1912. struct pollfd pfd_read;
  1913. pfd_read.fd = sock;
  1914. pfd_read.events = POLLIN;
  1915. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1916. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1917. #else
  1918. #ifndef _WIN32
  1919. if (sock >= FD_SETSIZE) { return 1; }
  1920. #endif
  1921. fd_set fds;
  1922. FD_ZERO(&fds);
  1923. FD_SET(sock, &fds);
  1924. timeval tv;
  1925. tv.tv_sec = static_cast<long>(sec);
  1926. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1927. return handle_EINTR([&]() {
  1928. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  1929. });
  1930. #endif
  1931. }
  1932. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  1933. #ifdef CPPHTTPLIB_USE_POLL
  1934. struct pollfd pfd_read;
  1935. pfd_read.fd = sock;
  1936. pfd_read.events = POLLOUT;
  1937. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1938. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1939. #else
  1940. #ifndef _WIN32
  1941. if (sock >= FD_SETSIZE) { return 1; }
  1942. #endif
  1943. fd_set fds;
  1944. FD_ZERO(&fds);
  1945. FD_SET(sock, &fds);
  1946. timeval tv;
  1947. tv.tv_sec = static_cast<long>(sec);
  1948. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1949. return handle_EINTR([&]() {
  1950. return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
  1951. });
  1952. #endif
  1953. }
  1954. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  1955. time_t usec) {
  1956. #ifdef CPPHTTPLIB_USE_POLL
  1957. struct pollfd pfd_read;
  1958. pfd_read.fd = sock;
  1959. pfd_read.events = POLLIN | POLLOUT;
  1960. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1961. auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1962. if (poll_res == 0) { return Error::ConnectionTimeout; }
  1963. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  1964. int error = 0;
  1965. socklen_t len = sizeof(error);
  1966. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1967. reinterpret_cast<char *>(&error), &len);
  1968. auto successful = res >= 0 && !error;
  1969. return successful ? Error::Success : Error::Connection;
  1970. }
  1971. return Error::Connection;
  1972. #else
  1973. #ifndef _WIN32
  1974. if (sock >= FD_SETSIZE) { return Error::Connection; }
  1975. #endif
  1976. fd_set fdsr;
  1977. FD_ZERO(&fdsr);
  1978. FD_SET(sock, &fdsr);
  1979. auto fdsw = fdsr;
  1980. auto fdse = fdsr;
  1981. timeval tv;
  1982. tv.tv_sec = static_cast<long>(sec);
  1983. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1984. auto ret = handle_EINTR([&]() {
  1985. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv);
  1986. });
  1987. if (ret == 0) { return Error::ConnectionTimeout; }
  1988. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  1989. int error = 0;
  1990. socklen_t len = sizeof(error);
  1991. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1992. reinterpret_cast<char *>(&error), &len);
  1993. auto successful = res >= 0 && !error;
  1994. return successful ? Error::Success : Error::Connection;
  1995. }
  1996. return Error::Connection;
  1997. #endif
  1998. }
  1999. inline bool is_socket_alive(socket_t sock) {
  2000. const auto val = detail::select_read(sock, 0, 0);
  2001. if (val == 0) {
  2002. return true;
  2003. } else if (val < 0 && errno == EBADF) {
  2004. return false;
  2005. }
  2006. char buf[1];
  2007. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  2008. }
  2009. class SocketStream : public Stream {
  2010. public:
  2011. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2012. time_t write_timeout_sec, time_t write_timeout_usec);
  2013. ~SocketStream() override;
  2014. bool is_readable() const override;
  2015. bool is_writable() const override;
  2016. ssize_t read(char *ptr, size_t size) override;
  2017. ssize_t write(const char *ptr, size_t size) override;
  2018. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2019. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2020. socket_t socket() const override;
  2021. private:
  2022. socket_t sock_;
  2023. time_t read_timeout_sec_;
  2024. time_t read_timeout_usec_;
  2025. time_t write_timeout_sec_;
  2026. time_t write_timeout_usec_;
  2027. std::vector<char> read_buff_;
  2028. size_t read_buff_off_ = 0;
  2029. size_t read_buff_content_size_ = 0;
  2030. static const size_t read_buff_size_ = 1024 * 4;
  2031. };
  2032. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2033. class SSLSocketStream : public Stream {
  2034. public:
  2035. SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
  2036. time_t read_timeout_usec, time_t write_timeout_sec,
  2037. time_t write_timeout_usec);
  2038. ~SSLSocketStream() override;
  2039. bool is_readable() const override;
  2040. bool is_writable() const override;
  2041. ssize_t read(char *ptr, size_t size) override;
  2042. ssize_t write(const char *ptr, size_t size) override;
  2043. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2044. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2045. socket_t socket() const override;
  2046. private:
  2047. socket_t sock_;
  2048. SSL *ssl_;
  2049. time_t read_timeout_sec_;
  2050. time_t read_timeout_usec_;
  2051. time_t write_timeout_sec_;
  2052. time_t write_timeout_usec_;
  2053. };
  2054. #endif
  2055. inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) {
  2056. using namespace std::chrono;
  2057. auto start = steady_clock::now();
  2058. while (true) {
  2059. auto val = select_read(sock, 0, 10000);
  2060. if (val < 0) {
  2061. return false;
  2062. } else if (val == 0) {
  2063. auto current = steady_clock::now();
  2064. auto duration = duration_cast<milliseconds>(current - start);
  2065. auto timeout = keep_alive_timeout_sec * 1000;
  2066. if (duration.count() > timeout) { return false; }
  2067. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2068. } else {
  2069. return true;
  2070. }
  2071. }
  2072. }
  2073. template <typename T>
  2074. inline bool
  2075. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2076. size_t keep_alive_max_count,
  2077. time_t keep_alive_timeout_sec, T callback) {
  2078. assert(keep_alive_max_count > 0);
  2079. auto ret = false;
  2080. auto count = keep_alive_max_count;
  2081. while (svr_sock != INVALID_SOCKET && count > 0 &&
  2082. keep_alive(sock, keep_alive_timeout_sec)) {
  2083. auto close_connection = count == 1;
  2084. auto connection_closed = false;
  2085. ret = callback(close_connection, connection_closed);
  2086. if (!ret || connection_closed) { break; }
  2087. count--;
  2088. }
  2089. return ret;
  2090. }
  2091. template <typename T>
  2092. inline bool
  2093. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2094. size_t keep_alive_max_count,
  2095. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  2096. time_t read_timeout_usec, time_t write_timeout_sec,
  2097. time_t write_timeout_usec, T callback) {
  2098. return process_server_socket_core(
  2099. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  2100. [&](bool close_connection, bool &connection_closed) {
  2101. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2102. write_timeout_sec, write_timeout_usec);
  2103. return callback(strm, close_connection, connection_closed);
  2104. });
  2105. }
  2106. inline bool process_client_socket(socket_t sock, time_t read_timeout_sec,
  2107. time_t read_timeout_usec,
  2108. time_t write_timeout_sec,
  2109. time_t write_timeout_usec,
  2110. std::function<bool(Stream &)> callback) {
  2111. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2112. write_timeout_sec, write_timeout_usec);
  2113. return callback(strm);
  2114. }
  2115. inline int shutdown_socket(socket_t sock) {
  2116. #ifdef _WIN32
  2117. return shutdown(sock, SD_BOTH);
  2118. #else
  2119. return shutdown(sock, SHUT_RDWR);
  2120. #endif
  2121. }
  2122. template <typename BindOrConnect>
  2123. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  2124. int address_family, int socket_flags, bool tcp_nodelay,
  2125. SocketOptions socket_options,
  2126. BindOrConnect bind_or_connect) {
  2127. // Get address info
  2128. const char *node = nullptr;
  2129. struct addrinfo hints;
  2130. struct addrinfo *result;
  2131. memset(&hints, 0, sizeof(struct addrinfo));
  2132. hints.ai_socktype = SOCK_STREAM;
  2133. hints.ai_protocol = 0;
  2134. if (!ip.empty()) {
  2135. node = ip.c_str();
  2136. // Ask getaddrinfo to convert IP in c-string to address
  2137. hints.ai_family = AF_UNSPEC;
  2138. hints.ai_flags = AI_NUMERICHOST;
  2139. } else {
  2140. if (!host.empty()) { node = host.c_str(); }
  2141. hints.ai_family = address_family;
  2142. hints.ai_flags = socket_flags;
  2143. }
  2144. #ifndef _WIN32
  2145. if (hints.ai_family == AF_UNIX) {
  2146. const auto addrlen = host.length();
  2147. if (addrlen > sizeof(sockaddr_un::sun_path)) return INVALID_SOCKET;
  2148. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  2149. if (sock != INVALID_SOCKET) {
  2150. sockaddr_un addr;
  2151. addr.sun_family = AF_UNIX;
  2152. std::copy(host.begin(), host.end(), addr.sun_path);
  2153. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  2154. hints.ai_addrlen = static_cast<socklen_t>(
  2155. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  2156. fcntl(sock, F_SETFD, FD_CLOEXEC);
  2157. if (socket_options) { socket_options(sock); }
  2158. if (!bind_or_connect(sock, hints)) {
  2159. close_socket(sock);
  2160. sock = INVALID_SOCKET;
  2161. }
  2162. }
  2163. return sock;
  2164. }
  2165. #endif
  2166. auto service = std::to_string(port);
  2167. if (getaddrinfo(node, service.c_str(), &hints, &result)) {
  2168. #if defined __linux__ && !defined __ANDROID__
  2169. res_init();
  2170. #endif
  2171. return INVALID_SOCKET;
  2172. }
  2173. for (auto rp = result; rp; rp = rp->ai_next) {
  2174. // Create a socket
  2175. #ifdef _WIN32
  2176. auto sock =
  2177. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  2178. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  2179. /**
  2180. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  2181. * and above the socket creation fails on older Windows Systems.
  2182. *
  2183. * Let's try to create a socket the old way in this case.
  2184. *
  2185. * Reference:
  2186. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  2187. *
  2188. * WSA_FLAG_NO_HANDLE_INHERIT:
  2189. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  2190. * SP1, and later
  2191. *
  2192. */
  2193. if (sock == INVALID_SOCKET) {
  2194. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  2195. }
  2196. #else
  2197. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  2198. #endif
  2199. if (sock == INVALID_SOCKET) { continue; }
  2200. #ifndef _WIN32
  2201. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
  2202. #endif
  2203. if (tcp_nodelay) {
  2204. int yes = 1;
  2205. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&yes),
  2206. sizeof(yes));
  2207. }
  2208. if (socket_options) { socket_options(sock); }
  2209. if (rp->ai_family == AF_INET6) {
  2210. int no = 0;
  2211. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char *>(&no),
  2212. sizeof(no));
  2213. }
  2214. // bind or connect
  2215. if (bind_or_connect(sock, *rp)) {
  2216. freeaddrinfo(result);
  2217. return sock;
  2218. }
  2219. close_socket(sock);
  2220. }
  2221. freeaddrinfo(result);
  2222. return INVALID_SOCKET;
  2223. }
  2224. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  2225. #ifdef _WIN32
  2226. auto flags = nonblocking ? 1UL : 0UL;
  2227. ioctlsocket(sock, FIONBIO, &flags);
  2228. #else
  2229. auto flags = fcntl(sock, F_GETFL, 0);
  2230. fcntl(sock, F_SETFL,
  2231. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  2232. #endif
  2233. }
  2234. inline bool is_connection_error() {
  2235. #ifdef _WIN32
  2236. return WSAGetLastError() != WSAEWOULDBLOCK;
  2237. #else
  2238. return errno != EINPROGRESS;
  2239. #endif
  2240. }
  2241. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  2242. struct addrinfo hints;
  2243. struct addrinfo *result;
  2244. memset(&hints, 0, sizeof(struct addrinfo));
  2245. hints.ai_family = AF_UNSPEC;
  2246. hints.ai_socktype = SOCK_STREAM;
  2247. hints.ai_protocol = 0;
  2248. if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; }
  2249. auto ret = false;
  2250. for (auto rp = result; rp; rp = rp->ai_next) {
  2251. const auto &ai = *rp;
  2252. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  2253. ret = true;
  2254. break;
  2255. }
  2256. }
  2257. freeaddrinfo(result);
  2258. return ret;
  2259. }
  2260. #if !defined _WIN32 && !defined ANDROID && !defined _AIX
  2261. #define USE_IF2IP
  2262. #endif
  2263. #ifdef USE_IF2IP
  2264. inline std::string if2ip(int address_family, const std::string &ifn) {
  2265. struct ifaddrs *ifap;
  2266. getifaddrs(&ifap);
  2267. std::string addr_candidate;
  2268. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  2269. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  2270. (AF_UNSPEC == address_family ||
  2271. ifa->ifa_addr->sa_family == address_family)) {
  2272. if (ifa->ifa_addr->sa_family == AF_INET) {
  2273. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  2274. char buf[INET_ADDRSTRLEN];
  2275. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  2276. freeifaddrs(ifap);
  2277. return std::string(buf, INET_ADDRSTRLEN);
  2278. }
  2279. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  2280. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  2281. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  2282. char buf[INET6_ADDRSTRLEN] = {};
  2283. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  2284. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  2285. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  2286. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  2287. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  2288. } else {
  2289. freeifaddrs(ifap);
  2290. return std::string(buf, INET6_ADDRSTRLEN);
  2291. }
  2292. }
  2293. }
  2294. }
  2295. }
  2296. }
  2297. freeifaddrs(ifap);
  2298. return addr_candidate;
  2299. }
  2300. #endif
  2301. inline socket_t create_client_socket(
  2302. const std::string &host, const std::string &ip, int port,
  2303. int address_family, bool tcp_nodelay, SocketOptions socket_options,
  2304. time_t connection_timeout_sec, time_t connection_timeout_usec,
  2305. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  2306. time_t write_timeout_usec, const std::string &intf, Error &error) {
  2307. auto sock = create_socket(
  2308. host, ip, port, address_family, 0, tcp_nodelay, std::move(socket_options),
  2309. [&](socket_t sock2, struct addrinfo &ai) -> bool {
  2310. if (!intf.empty()) {
  2311. #ifdef USE_IF2IP
  2312. auto ip_from_if = if2ip(address_family, intf);
  2313. if (ip_from_if.empty()) { ip_from_if = intf; }
  2314. if (!bind_ip_address(sock2, ip_from_if.c_str())) {
  2315. error = Error::BindIPAddress;
  2316. return false;
  2317. }
  2318. #endif
  2319. }
  2320. set_nonblocking(sock2, true);
  2321. auto ret =
  2322. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  2323. if (ret < 0) {
  2324. if (is_connection_error()) {
  2325. error = Error::Connection;
  2326. return false;
  2327. }
  2328. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  2329. connection_timeout_usec);
  2330. if (error != Error::Success) { return false; }
  2331. }
  2332. set_nonblocking(sock2, false);
  2333. {
  2334. #ifdef _WIN32
  2335. auto timeout = static_cast<uint32_t>(read_timeout_sec * 1000 +
  2336. read_timeout_usec / 1000);
  2337. setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
  2338. sizeof(timeout));
  2339. #else
  2340. timeval tv;
  2341. tv.tv_sec = static_cast<long>(read_timeout_sec);
  2342. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec);
  2343. setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
  2344. #endif
  2345. }
  2346. {
  2347. #ifdef _WIN32
  2348. auto timeout = static_cast<uint32_t>(write_timeout_sec * 1000 +
  2349. write_timeout_usec / 1000);
  2350. setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
  2351. sizeof(timeout));
  2352. #else
  2353. timeval tv;
  2354. tv.tv_sec = static_cast<long>(write_timeout_sec);
  2355. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec);
  2356. setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
  2357. #endif
  2358. }
  2359. error = Error::Success;
  2360. return true;
  2361. });
  2362. if (sock != INVALID_SOCKET) {
  2363. error = Error::Success;
  2364. } else {
  2365. if (error == Error::Success) { error = Error::Connection; }
  2366. }
  2367. return sock;
  2368. }
  2369. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  2370. socklen_t addr_len, std::string &ip, int &port) {
  2371. if (addr.ss_family == AF_INET) {
  2372. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  2373. } else if (addr.ss_family == AF_INET6) {
  2374. port =
  2375. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  2376. } else {
  2377. return false;
  2378. }
  2379. std::array<char, NI_MAXHOST> ipstr{};
  2380. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  2381. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  2382. 0, NI_NUMERICHOST)) {
  2383. return false;
  2384. }
  2385. ip = ipstr.data();
  2386. return true;
  2387. }
  2388. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  2389. struct sockaddr_storage addr;
  2390. socklen_t addr_len = sizeof(addr);
  2391. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  2392. &addr_len)) {
  2393. get_ip_and_port(addr, addr_len, ip, port);
  2394. }
  2395. }
  2396. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  2397. struct sockaddr_storage addr;
  2398. socklen_t addr_len = sizeof(addr);
  2399. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  2400. &addr_len)) {
  2401. #ifndef _WIN32
  2402. if (addr.ss_family == AF_UNIX) {
  2403. #if defined(__linux__)
  2404. struct ucred ucred;
  2405. socklen_t len = sizeof(ucred);
  2406. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  2407. port = ucred.pid;
  2408. }
  2409. #elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__
  2410. pid_t pid;
  2411. socklen_t len = sizeof(pid);
  2412. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  2413. port = pid;
  2414. }
  2415. #endif
  2416. return;
  2417. }
  2418. #endif
  2419. get_ip_and_port(addr, addr_len, ip, port);
  2420. }
  2421. }
  2422. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  2423. unsigned int h) {
  2424. return (l == 0) ? h
  2425. : str2tag_core(s + 1, l - 1,
  2426. (h * 33) ^ static_cast<unsigned char>(*s));
  2427. }
  2428. inline unsigned int str2tag(const std::string &s) {
  2429. return str2tag_core(s.data(), s.size(), 0);
  2430. }
  2431. namespace udl {
  2432. inline constexpr unsigned int operator"" _t(const char *s, size_t l) {
  2433. return str2tag_core(s, l, 0);
  2434. }
  2435. } // namespace udl
  2436. inline const char *
  2437. find_content_type(const std::string &path,
  2438. const std::map<std::string, std::string> &user_data) {
  2439. auto ext = file_extension(path);
  2440. auto it = user_data.find(ext);
  2441. if (it != user_data.end()) { return it->second.c_str(); }
  2442. using udl::operator""_t;
  2443. switch (str2tag(ext)) {
  2444. default: return nullptr;
  2445. case "css"_t: return "text/css";
  2446. case "csv"_t: return "text/csv";
  2447. case "htm"_t:
  2448. case "html"_t: return "text/html";
  2449. case "js"_t:
  2450. case "mjs"_t: return "text/javascript";
  2451. case "txt"_t: return "text/plain";
  2452. case "vtt"_t: return "text/vtt";
  2453. case "apng"_t: return "image/apng";
  2454. case "avif"_t: return "image/avif";
  2455. case "bmp"_t: return "image/bmp";
  2456. case "gif"_t: return "image/gif";
  2457. case "png"_t: return "image/png";
  2458. case "svg"_t: return "image/svg+xml";
  2459. case "webp"_t: return "image/webp";
  2460. case "ico"_t: return "image/x-icon";
  2461. case "tif"_t: return "image/tiff";
  2462. case "tiff"_t: return "image/tiff";
  2463. case "jpg"_t:
  2464. case "jpeg"_t: return "image/jpeg";
  2465. case "mp4"_t: return "video/mp4";
  2466. case "mpeg"_t: return "video/mpeg";
  2467. case "webm"_t: return "video/webm";
  2468. case "mp3"_t: return "audio/mp3";
  2469. case "mpga"_t: return "audio/mpeg";
  2470. case "weba"_t: return "audio/webm";
  2471. case "wav"_t: return "audio/wave";
  2472. case "otf"_t: return "font/otf";
  2473. case "ttf"_t: return "font/ttf";
  2474. case "woff"_t: return "font/woff";
  2475. case "woff2"_t: return "font/woff2";
  2476. case "7z"_t: return "application/x-7z-compressed";
  2477. case "atom"_t: return "application/atom+xml";
  2478. case "pdf"_t: return "application/pdf";
  2479. case "json"_t: return "application/json";
  2480. case "rss"_t: return "application/rss+xml";
  2481. case "tar"_t: return "application/x-tar";
  2482. case "xht"_t:
  2483. case "xhtml"_t: return "application/xhtml+xml";
  2484. case "xslt"_t: return "application/xslt+xml";
  2485. case "xml"_t: return "application/xml";
  2486. case "gz"_t: return "application/gzip";
  2487. case "zip"_t: return "application/zip";
  2488. case "wasm"_t: return "application/wasm";
  2489. }
  2490. }
  2491. inline const char *status_message(int status) {
  2492. switch (status) {
  2493. case 100: return "Continue";
  2494. case 101: return "Switching Protocol";
  2495. case 102: return "Processing";
  2496. case 103: return "Early Hints";
  2497. case 200: return "OK";
  2498. case 201: return "Created";
  2499. case 202: return "Accepted";
  2500. case 203: return "Non-Authoritative Information";
  2501. case 204: return "No Content";
  2502. case 205: return "Reset Content";
  2503. case 206: return "Partial Content";
  2504. case 207: return "Multi-Status";
  2505. case 208: return "Already Reported";
  2506. case 226: return "IM Used";
  2507. case 300: return "Multiple Choice";
  2508. case 301: return "Moved Permanently";
  2509. case 302: return "Found";
  2510. case 303: return "See Other";
  2511. case 304: return "Not Modified";
  2512. case 305: return "Use Proxy";
  2513. case 306: return "unused";
  2514. case 307: return "Temporary Redirect";
  2515. case 308: return "Permanent Redirect";
  2516. case 400: return "Bad Request";
  2517. case 401: return "Unauthorized";
  2518. case 402: return "Payment Required";
  2519. case 403: return "Forbidden";
  2520. case 404: return "Not Found";
  2521. case 405: return "Method Not Allowed";
  2522. case 406: return "Not Acceptable";
  2523. case 407: return "Proxy Authentication Required";
  2524. case 408: return "Request Timeout";
  2525. case 409: return "Conflict";
  2526. case 410: return "Gone";
  2527. case 411: return "Length Required";
  2528. case 412: return "Precondition Failed";
  2529. case 413: return "Payload Too Large";
  2530. case 414: return "URI Too Long";
  2531. case 415: return "Unsupported Media Type";
  2532. case 416: return "Range Not Satisfiable";
  2533. case 417: return "Expectation Failed";
  2534. case 418: return "I'm a teapot";
  2535. case 421: return "Misdirected Request";
  2536. case 422: return "Unprocessable Entity";
  2537. case 423: return "Locked";
  2538. case 424: return "Failed Dependency";
  2539. case 425: return "Too Early";
  2540. case 426: return "Upgrade Required";
  2541. case 428: return "Precondition Required";
  2542. case 429: return "Too Many Requests";
  2543. case 431: return "Request Header Fields Too Large";
  2544. case 451: return "Unavailable For Legal Reasons";
  2545. case 501: return "Not Implemented";
  2546. case 502: return "Bad Gateway";
  2547. case 503: return "Service Unavailable";
  2548. case 504: return "Gateway Timeout";
  2549. case 505: return "HTTP Version Not Supported";
  2550. case 506: return "Variant Also Negotiates";
  2551. case 507: return "Insufficient Storage";
  2552. case 508: return "Loop Detected";
  2553. case 510: return "Not Extended";
  2554. case 511: return "Network Authentication Required";
  2555. default:
  2556. case 500: return "Internal Server Error";
  2557. }
  2558. }
  2559. inline bool can_compress_content_type(const std::string &content_type) {
  2560. using udl::operator""_t;
  2561. auto tag = str2tag(content_type);
  2562. switch (tag) {
  2563. case "image/svg+xml"_t:
  2564. case "application/javascript"_t:
  2565. case "application/json"_t:
  2566. case "application/xml"_t:
  2567. case "application/protobuf"_t:
  2568. case "application/xhtml+xml"_t: return true;
  2569. default:
  2570. return !content_type.rfind("text/", 0) && tag != "text/event-stream"_t;
  2571. }
  2572. }
  2573. inline EncodingType encoding_type(const Request &req, const Response &res) {
  2574. auto ret =
  2575. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  2576. if (!ret) { return EncodingType::None; }
  2577. const auto &s = req.get_header_value("Accept-Encoding");
  2578. (void)(s);
  2579. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2580. // TODO: 'Accept-Encoding' has br, not br;q=0
  2581. ret = s.find("br") != std::string::npos;
  2582. if (ret) { return EncodingType::Brotli; }
  2583. #endif
  2584. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2585. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  2586. ret = s.find("gzip") != std::string::npos;
  2587. if (ret) { return EncodingType::Gzip; }
  2588. #endif
  2589. return EncodingType::None;
  2590. }
  2591. inline bool nocompressor::compress(const char *data, size_t data_length,
  2592. bool /*last*/, Callback callback) {
  2593. if (!data_length) { return true; }
  2594. return callback(data, data_length);
  2595. }
  2596. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2597. inline gzip_compressor::gzip_compressor() {
  2598. std::memset(&strm_, 0, sizeof(strm_));
  2599. strm_.zalloc = Z_NULL;
  2600. strm_.zfree = Z_NULL;
  2601. strm_.opaque = Z_NULL;
  2602. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  2603. Z_DEFAULT_STRATEGY) == Z_OK;
  2604. }
  2605. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  2606. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  2607. bool last, Callback callback) {
  2608. assert(is_valid_);
  2609. do {
  2610. constexpr size_t max_avail_in =
  2611. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  2612. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  2613. (std::min)(data_length, max_avail_in));
  2614. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  2615. data_length -= strm_.avail_in;
  2616. data += strm_.avail_in;
  2617. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  2618. int ret = Z_OK;
  2619. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  2620. do {
  2621. strm_.avail_out = static_cast<uInt>(buff.size());
  2622. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  2623. ret = deflate(&strm_, flush);
  2624. if (ret == Z_STREAM_ERROR) { return false; }
  2625. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  2626. return false;
  2627. }
  2628. } while (strm_.avail_out == 0);
  2629. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  2630. (flush == Z_NO_FLUSH && ret == Z_OK));
  2631. assert(strm_.avail_in == 0);
  2632. } while (data_length > 0);
  2633. return true;
  2634. }
  2635. inline gzip_decompressor::gzip_decompressor() {
  2636. std::memset(&strm_, 0, sizeof(strm_));
  2637. strm_.zalloc = Z_NULL;
  2638. strm_.zfree = Z_NULL;
  2639. strm_.opaque = Z_NULL;
  2640. // 15 is the value of wbits, which should be at the maximum possible value
  2641. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  2642. // that the stream type should be automatically detected either gzip or
  2643. // deflate.
  2644. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  2645. }
  2646. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  2647. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  2648. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  2649. Callback callback) {
  2650. assert(is_valid_);
  2651. int ret = Z_OK;
  2652. do {
  2653. constexpr size_t max_avail_in =
  2654. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  2655. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  2656. (std::min)(data_length, max_avail_in));
  2657. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  2658. data_length -= strm_.avail_in;
  2659. data += strm_.avail_in;
  2660. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  2661. while (strm_.avail_in > 0) {
  2662. strm_.avail_out = static_cast<uInt>(buff.size());
  2663. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  2664. auto prev_avail_in = strm_.avail_in;
  2665. ret = inflate(&strm_, Z_NO_FLUSH);
  2666. if (prev_avail_in - strm_.avail_in == 0) { return false; }
  2667. assert(ret != Z_STREAM_ERROR);
  2668. switch (ret) {
  2669. case Z_NEED_DICT:
  2670. case Z_DATA_ERROR:
  2671. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  2672. }
  2673. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  2674. return false;
  2675. }
  2676. }
  2677. if (ret != Z_OK && ret != Z_STREAM_END) return false;
  2678. } while (data_length > 0);
  2679. return true;
  2680. }
  2681. #endif
  2682. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2683. inline brotli_compressor::brotli_compressor() {
  2684. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  2685. }
  2686. inline brotli_compressor::~brotli_compressor() {
  2687. BrotliEncoderDestroyInstance(state_);
  2688. }
  2689. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  2690. bool last, Callback callback) {
  2691. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  2692. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  2693. auto available_in = data_length;
  2694. auto next_in = reinterpret_cast<const uint8_t *>(data);
  2695. for (;;) {
  2696. if (last) {
  2697. if (BrotliEncoderIsFinished(state_)) { break; }
  2698. } else {
  2699. if (!available_in) { break; }
  2700. }
  2701. auto available_out = buff.size();
  2702. auto next_out = buff.data();
  2703. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  2704. &available_out, &next_out, nullptr)) {
  2705. return false;
  2706. }
  2707. auto output_bytes = buff.size() - available_out;
  2708. if (output_bytes) {
  2709. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  2710. }
  2711. }
  2712. return true;
  2713. }
  2714. inline brotli_decompressor::brotli_decompressor() {
  2715. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  2716. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  2717. : BROTLI_DECODER_RESULT_ERROR;
  2718. }
  2719. inline brotli_decompressor::~brotli_decompressor() {
  2720. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  2721. }
  2722. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  2723. inline bool brotli_decompressor::decompress(const char *data,
  2724. size_t data_length,
  2725. Callback callback) {
  2726. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  2727. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  2728. return 0;
  2729. }
  2730. const uint8_t *next_in = (const uint8_t *)data;
  2731. size_t avail_in = data_length;
  2732. size_t total_out;
  2733. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  2734. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  2735. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  2736. char *next_out = buff.data();
  2737. size_t avail_out = buff.size();
  2738. decoder_r = BrotliDecoderDecompressStream(
  2739. decoder_s, &avail_in, &next_in, &avail_out,
  2740. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  2741. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  2742. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  2743. }
  2744. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  2745. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  2746. }
  2747. #endif
  2748. inline bool has_header(const Headers &headers, const std::string &key) {
  2749. return headers.find(key) != headers.end();
  2750. }
  2751. inline const char *get_header_value(const Headers &headers,
  2752. const std::string &key, size_t id,
  2753. const char *def) {
  2754. auto rng = headers.equal_range(key);
  2755. auto it = rng.first;
  2756. std::advance(it, static_cast<ssize_t>(id));
  2757. if (it != rng.second) { return it->second.c_str(); }
  2758. return def;
  2759. }
  2760. template <typename T>
  2761. inline bool parse_header(const char *beg, const char *end, T fn) {
  2762. // Skip trailing spaces and tabs.
  2763. while (beg < end && is_space_or_tab(end[-1])) {
  2764. end--;
  2765. }
  2766. auto p = beg;
  2767. while (p < end && *p != ':') {
  2768. p++;
  2769. }
  2770. if (p == end) { return false; }
  2771. auto key_end = p;
  2772. if (*p++ != ':') { return false; }
  2773. while (p < end && is_space_or_tab(*p)) {
  2774. p++;
  2775. }
  2776. if (p < end) {
  2777. fn(std::string(beg, key_end), decode_url(std::string(p, end), false));
  2778. return true;
  2779. }
  2780. return false;
  2781. }
  2782. inline bool read_headers(Stream &strm, Headers &headers) {
  2783. const auto bufsiz = 2048;
  2784. char buf[bufsiz];
  2785. stream_line_reader line_reader(strm, buf, bufsiz);
  2786. for (;;) {
  2787. if (!line_reader.getline()) { return false; }
  2788. // Check if the line ends with CRLF.
  2789. auto line_terminator_len = 2;
  2790. if (line_reader.end_with_crlf()) {
  2791. // Blank line indicates end of headers.
  2792. if (line_reader.size() == 2) { break; }
  2793. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2794. } else {
  2795. // Blank line indicates end of headers.
  2796. if (line_reader.size() == 1) { break; }
  2797. line_terminator_len = 1;
  2798. }
  2799. #else
  2800. } else {
  2801. continue; // Skip invalid line.
  2802. }
  2803. #endif
  2804. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  2805. // Exclude line terminator
  2806. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  2807. parse_header(line_reader.ptr(), end,
  2808. [&](std::string &&key, std::string &&val) {
  2809. headers.emplace(std::move(key), std::move(val));
  2810. });
  2811. }
  2812. return true;
  2813. }
  2814. inline bool read_content_with_length(Stream &strm, uint64_t len,
  2815. Progress progress,
  2816. ContentReceiverWithProgress out) {
  2817. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2818. uint64_t r = 0;
  2819. while (r < len) {
  2820. auto read_len = static_cast<size_t>(len - r);
  2821. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  2822. if (n <= 0) { return false; }
  2823. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  2824. r += static_cast<uint64_t>(n);
  2825. if (progress) {
  2826. if (!progress(r, len)) { return false; }
  2827. }
  2828. }
  2829. return true;
  2830. }
  2831. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  2832. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2833. uint64_t r = 0;
  2834. while (r < len) {
  2835. auto read_len = static_cast<size_t>(len - r);
  2836. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  2837. if (n <= 0) { return; }
  2838. r += static_cast<uint64_t>(n);
  2839. }
  2840. }
  2841. inline bool read_content_without_length(Stream &strm,
  2842. ContentReceiverWithProgress out) {
  2843. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2844. uint64_t r = 0;
  2845. for (;;) {
  2846. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  2847. if (n < 0) {
  2848. return false;
  2849. } else if (n == 0) {
  2850. return true;
  2851. }
  2852. if (!out(buf, static_cast<size_t>(n), r, 0)) { return false; }
  2853. r += static_cast<uint64_t>(n);
  2854. }
  2855. return true;
  2856. }
  2857. inline bool read_content_chunked(Stream &strm,
  2858. ContentReceiverWithProgress out) {
  2859. const auto bufsiz = 16;
  2860. char buf[bufsiz];
  2861. stream_line_reader line_reader(strm, buf, bufsiz);
  2862. if (!line_reader.getline()) { return false; }
  2863. unsigned long chunk_len;
  2864. while (true) {
  2865. char *end_ptr;
  2866. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  2867. if (end_ptr == line_reader.ptr()) { return false; }
  2868. if (chunk_len == ULONG_MAX) { return false; }
  2869. if (chunk_len == 0) { break; }
  2870. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  2871. return false;
  2872. }
  2873. if (!line_reader.getline()) { return false; }
  2874. if (strcmp(line_reader.ptr(), "\r\n")) { break; }
  2875. if (!line_reader.getline()) { return false; }
  2876. }
  2877. if (chunk_len == 0) {
  2878. // Reader terminator after chunks
  2879. if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
  2880. return false;
  2881. }
  2882. return true;
  2883. }
  2884. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  2885. return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
  2886. "chunked");
  2887. }
  2888. template <typename T, typename U>
  2889. bool prepare_content_receiver(T &x, int &status,
  2890. ContentReceiverWithProgress receiver,
  2891. bool decompress, U callback) {
  2892. if (decompress) {
  2893. std::string encoding = x.get_header_value("Content-Encoding");
  2894. std::unique_ptr<decompressor> decompressor;
  2895. if (encoding == "gzip" || encoding == "deflate") {
  2896. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2897. decompressor = detail::make_unique<gzip_decompressor>();
  2898. #else
  2899. status = 415;
  2900. return false;
  2901. #endif
  2902. } else if (encoding.find("br") != std::string::npos) {
  2903. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2904. decompressor = detail::make_unique<brotli_decompressor>();
  2905. #else
  2906. status = 415;
  2907. return false;
  2908. #endif
  2909. }
  2910. if (decompressor) {
  2911. if (decompressor->is_valid()) {
  2912. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  2913. uint64_t off, uint64_t len) {
  2914. return decompressor->decompress(buf, n,
  2915. [&](const char *buf2, size_t n2) {
  2916. return receiver(buf2, n2, off, len);
  2917. });
  2918. };
  2919. return callback(std::move(out));
  2920. } else {
  2921. status = 500;
  2922. return false;
  2923. }
  2924. }
  2925. }
  2926. ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off,
  2927. uint64_t len) {
  2928. return receiver(buf, n, off, len);
  2929. };
  2930. return callback(std::move(out));
  2931. }
  2932. template <typename T>
  2933. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  2934. Progress progress, ContentReceiverWithProgress receiver,
  2935. bool decompress) {
  2936. return prepare_content_receiver(
  2937. x, status, std::move(receiver), decompress,
  2938. [&](const ContentReceiverWithProgress &out) {
  2939. auto ret = true;
  2940. auto exceed_payload_max_length = false;
  2941. if (is_chunked_transfer_encoding(x.headers)) {
  2942. ret = read_content_chunked(strm, out);
  2943. } else if (!has_header(x.headers, "Content-Length")) {
  2944. ret = read_content_without_length(strm, out);
  2945. } else {
  2946. auto len = get_header_value<uint64_t>(x.headers, "Content-Length");
  2947. if (len > payload_max_length) {
  2948. exceed_payload_max_length = true;
  2949. skip_content_with_length(strm, len);
  2950. ret = false;
  2951. } else if (len > 0) {
  2952. ret = read_content_with_length(strm, len, std::move(progress), out);
  2953. }
  2954. }
  2955. if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
  2956. return ret;
  2957. });
  2958. } // namespace detail
  2959. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  2960. ssize_t write_len = 0;
  2961. for (const auto &x : headers) {
  2962. auto len =
  2963. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  2964. if (len < 0) { return len; }
  2965. write_len += len;
  2966. }
  2967. auto len = strm.write("\r\n");
  2968. if (len < 0) { return len; }
  2969. write_len += len;
  2970. return write_len;
  2971. }
  2972. inline bool write_data(Stream &strm, const char *d, size_t l) {
  2973. size_t offset = 0;
  2974. while (offset < l) {
  2975. auto length = strm.write(d + offset, l - offset);
  2976. if (length < 0) { return false; }
  2977. offset += static_cast<size_t>(length);
  2978. }
  2979. return true;
  2980. }
  2981. template <typename T>
  2982. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  2983. size_t offset, size_t length, T is_shutting_down,
  2984. Error &error) {
  2985. size_t end_offset = offset + length;
  2986. auto ok = true;
  2987. DataSink data_sink;
  2988. data_sink.write = [&](const char *d, size_t l) -> bool {
  2989. if (ok) {
  2990. if (strm.is_writable() && write_data(strm, d, l)) {
  2991. offset += l;
  2992. } else {
  2993. ok = false;
  2994. }
  2995. }
  2996. return ok;
  2997. };
  2998. while (offset < end_offset && !is_shutting_down()) {
  2999. if (!strm.is_writable()) {
  3000. error = Error::Write;
  3001. return false;
  3002. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  3003. error = Error::Canceled;
  3004. return false;
  3005. } else if (!ok) {
  3006. error = Error::Write;
  3007. return false;
  3008. }
  3009. }
  3010. error = Error::Success;
  3011. return true;
  3012. }
  3013. template <typename T>
  3014. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  3015. size_t offset, size_t length,
  3016. const T &is_shutting_down) {
  3017. auto error = Error::Success;
  3018. return write_content(strm, content_provider, offset, length, is_shutting_down,
  3019. error);
  3020. }
  3021. template <typename T>
  3022. inline bool
  3023. write_content_without_length(Stream &strm,
  3024. const ContentProvider &content_provider,
  3025. const T &is_shutting_down) {
  3026. size_t offset = 0;
  3027. auto data_available = true;
  3028. auto ok = true;
  3029. DataSink data_sink;
  3030. data_sink.write = [&](const char *d, size_t l) -> bool {
  3031. if (ok) {
  3032. offset += l;
  3033. if (!strm.is_writable() || !write_data(strm, d, l)) { ok = false; }
  3034. }
  3035. return ok;
  3036. };
  3037. data_sink.done = [&](void) { data_available = false; };
  3038. while (data_available && !is_shutting_down()) {
  3039. if (!strm.is_writable()) {
  3040. return false;
  3041. } else if (!content_provider(offset, 0, data_sink)) {
  3042. return false;
  3043. } else if (!ok) {
  3044. return false;
  3045. }
  3046. }
  3047. return true;
  3048. }
  3049. template <typename T, typename U>
  3050. inline bool
  3051. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  3052. const T &is_shutting_down, U &compressor, Error &error) {
  3053. size_t offset = 0;
  3054. auto data_available = true;
  3055. auto ok = true;
  3056. DataSink data_sink;
  3057. data_sink.write = [&](const char *d, size_t l) -> bool {
  3058. if (ok) {
  3059. data_available = l > 0;
  3060. offset += l;
  3061. std::string payload;
  3062. if (compressor.compress(d, l, false,
  3063. [&](const char *data, size_t data_len) {
  3064. payload.append(data, data_len);
  3065. return true;
  3066. })) {
  3067. if (!payload.empty()) {
  3068. // Emit chunked response header and footer for each chunk
  3069. auto chunk =
  3070. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  3071. if (!strm.is_writable() ||
  3072. !write_data(strm, chunk.data(), chunk.size())) {
  3073. ok = false;
  3074. }
  3075. }
  3076. } else {
  3077. ok = false;
  3078. }
  3079. }
  3080. return ok;
  3081. };
  3082. data_sink.done = [&](void) {
  3083. if (!ok) { return; }
  3084. data_available = false;
  3085. std::string payload;
  3086. if (!compressor.compress(nullptr, 0, true,
  3087. [&](const char *data, size_t data_len) {
  3088. payload.append(data, data_len);
  3089. return true;
  3090. })) {
  3091. ok = false;
  3092. return;
  3093. }
  3094. if (!payload.empty()) {
  3095. // Emit chunked response header and footer for each chunk
  3096. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  3097. if (!write_data(strm, chunk.data(), chunk.size())) {
  3098. ok = false;
  3099. return;
  3100. }
  3101. }
  3102. static const std::string done_marker("0\r\n\r\n");
  3103. if (!write_data(strm, done_marker.data(), done_marker.size())) {
  3104. ok = false;
  3105. }
  3106. };
  3107. while (data_available && !is_shutting_down()) {
  3108. if (!strm.is_writable()) {
  3109. error = Error::Write;
  3110. return false;
  3111. } else if (!content_provider(offset, 0, data_sink)) {
  3112. error = Error::Canceled;
  3113. return false;
  3114. } else if (!ok) {
  3115. error = Error::Write;
  3116. return false;
  3117. }
  3118. }
  3119. error = Error::Success;
  3120. return true;
  3121. }
  3122. template <typename T, typename U>
  3123. inline bool write_content_chunked(Stream &strm,
  3124. const ContentProvider &content_provider,
  3125. const T &is_shutting_down, U &compressor) {
  3126. auto error = Error::Success;
  3127. return write_content_chunked(strm, content_provider, is_shutting_down,
  3128. compressor, error);
  3129. }
  3130. template <typename T>
  3131. inline bool redirect(T &cli, Request &req, Response &res,
  3132. const std::string &path, const std::string &location,
  3133. Error &error) {
  3134. Request new_req = req;
  3135. new_req.path = path;
  3136. new_req.redirect_count_ -= 1;
  3137. if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) {
  3138. new_req.method = "GET";
  3139. new_req.body.clear();
  3140. new_req.headers.clear();
  3141. }
  3142. Response new_res;
  3143. auto ret = cli.send(new_req, new_res, error);
  3144. if (ret) {
  3145. req = new_req;
  3146. res = new_res;
  3147. res.location = location;
  3148. }
  3149. return ret;
  3150. }
  3151. inline std::string params_to_query_str(const Params &params) {
  3152. std::string query;
  3153. for (auto it = params.begin(); it != params.end(); ++it) {
  3154. if (it != params.begin()) { query += "&"; }
  3155. query += it->first;
  3156. query += "=";
  3157. query += encode_query_param(it->second);
  3158. }
  3159. return query;
  3160. }
  3161. inline void parse_query_text(const std::string &s, Params &params) {
  3162. std::set<std::string> cache;
  3163. split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) {
  3164. std::string kv(b, e);
  3165. if (cache.find(kv) != cache.end()) { return; }
  3166. cache.insert(kv);
  3167. std::string key;
  3168. std::string val;
  3169. split(b, e, '=', [&](const char *b2, const char *e2) {
  3170. if (key.empty()) {
  3171. key.assign(b2, e2);
  3172. } else {
  3173. val.assign(b2, e2);
  3174. }
  3175. });
  3176. if (!key.empty()) {
  3177. params.emplace(decode_url(key, true), decode_url(val, true));
  3178. }
  3179. });
  3180. }
  3181. inline bool parse_multipart_boundary(const std::string &content_type,
  3182. std::string &boundary) {
  3183. auto pos = content_type.find("boundary=");
  3184. if (pos == std::string::npos) { return false; }
  3185. boundary = content_type.substr(pos + 9);
  3186. if (boundary.length() >= 2 && boundary.front() == '"' &&
  3187. boundary.back() == '"') {
  3188. boundary = boundary.substr(1, boundary.size() - 2);
  3189. }
  3190. return !boundary.empty();
  3191. }
  3192. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  3193. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  3194. #else
  3195. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  3196. #endif
  3197. static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  3198. std::smatch m;
  3199. if (std::regex_match(s, m, re_first_range)) {
  3200. auto pos = static_cast<size_t>(m.position(1));
  3201. auto len = static_cast<size_t>(m.length(1));
  3202. bool all_valid_ranges = true;
  3203. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  3204. if (!all_valid_ranges) return;
  3205. static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
  3206. std::cmatch cm;
  3207. if (std::regex_match(b, e, cm, re_another_range)) {
  3208. ssize_t first = -1;
  3209. if (!cm.str(1).empty()) {
  3210. first = static_cast<ssize_t>(std::stoll(cm.str(1)));
  3211. }
  3212. ssize_t last = -1;
  3213. if (!cm.str(2).empty()) {
  3214. last = static_cast<ssize_t>(std::stoll(cm.str(2)));
  3215. }
  3216. if (first != -1 && last != -1 && first > last) {
  3217. all_valid_ranges = false;
  3218. return;
  3219. }
  3220. ranges.emplace_back(std::make_pair(first, last));
  3221. }
  3222. });
  3223. return all_valid_ranges;
  3224. }
  3225. return false;
  3226. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  3227. }
  3228. #else
  3229. } catch (...) { return false; }
  3230. #endif
  3231. class MultipartFormDataParser {
  3232. public:
  3233. MultipartFormDataParser() = default;
  3234. void set_boundary(std::string &&boundary) {
  3235. boundary_ = boundary;
  3236. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  3237. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  3238. }
  3239. bool is_valid() const { return is_valid_; }
  3240. bool parse(const char *buf, size_t n, const ContentReceiver &content_callback,
  3241. const MultipartContentHeader &header_callback) {
  3242. // TODO: support 'filename*'
  3243. static const std::regex re_content_disposition(
  3244. R"~(^Content-Disposition:\s*form-data;\s*name="(.*?)"(?:;\s*filename="(.*?)")?(?:;\s*filename\*=\S+)?\s*$)~",
  3245. std::regex_constants::icase);
  3246. buf_append(buf, n);
  3247. while (buf_size() > 0) {
  3248. switch (state_) {
  3249. case 0: { // Initial boundary
  3250. buf_erase(buf_find(dash_boundary_crlf_));
  3251. if (dash_boundary_crlf_.size() > buf_size()) { return true; }
  3252. if (!buf_start_with(dash_boundary_crlf_)) { return false; }
  3253. buf_erase(dash_boundary_crlf_.size());
  3254. state_ = 1;
  3255. break;
  3256. }
  3257. case 1: { // New entry
  3258. clear_file_info();
  3259. state_ = 2;
  3260. break;
  3261. }
  3262. case 2: { // Headers
  3263. auto pos = buf_find(crlf_);
  3264. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3265. while (pos < buf_size()) {
  3266. // Empty line
  3267. if (pos == 0) {
  3268. if (!header_callback(file_)) {
  3269. is_valid_ = false;
  3270. return false;
  3271. }
  3272. buf_erase(crlf_.size());
  3273. state_ = 3;
  3274. break;
  3275. }
  3276. static const std::string header_name = "content-type:";
  3277. const auto header = buf_head(pos);
  3278. if (start_with_case_ignore(header, header_name)) {
  3279. file_.content_type = trim_copy(header.substr(header_name.size()));
  3280. } else {
  3281. std::smatch m;
  3282. if (std::regex_match(header, m, re_content_disposition)) {
  3283. file_.name = m[1];
  3284. file_.filename = m[2];
  3285. } else {
  3286. is_valid_ = false;
  3287. return false;
  3288. }
  3289. }
  3290. buf_erase(pos + crlf_.size());
  3291. pos = buf_find(crlf_);
  3292. }
  3293. if (state_ != 3) { return true; }
  3294. break;
  3295. }
  3296. case 3: { // Body
  3297. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  3298. auto pos = buf_find(crlf_dash_boundary_);
  3299. if (pos < buf_size()) {
  3300. if (!content_callback(buf_data(), pos)) {
  3301. is_valid_ = false;
  3302. return false;
  3303. }
  3304. buf_erase(pos + crlf_dash_boundary_.size());
  3305. state_ = 4;
  3306. } else {
  3307. auto len = buf_size() - crlf_dash_boundary_.size();
  3308. if (len > 0) {
  3309. if (!content_callback(buf_data(), len)) {
  3310. is_valid_ = false;
  3311. return false;
  3312. }
  3313. buf_erase(len);
  3314. }
  3315. return true;
  3316. }
  3317. break;
  3318. }
  3319. case 4: { // Boundary
  3320. if (crlf_.size() > buf_size()) { return true; }
  3321. if (buf_start_with(crlf_)) {
  3322. buf_erase(crlf_.size());
  3323. state_ = 1;
  3324. } else {
  3325. if (dash_crlf_.size() > buf_size()) { return true; }
  3326. if (buf_start_with(dash_crlf_)) {
  3327. buf_erase(dash_crlf_.size());
  3328. is_valid_ = true;
  3329. buf_erase(buf_size()); // Remove epilogue
  3330. } else {
  3331. return true;
  3332. }
  3333. }
  3334. break;
  3335. }
  3336. }
  3337. }
  3338. return true;
  3339. }
  3340. private:
  3341. void clear_file_info() {
  3342. file_.name.clear();
  3343. file_.filename.clear();
  3344. file_.content_type.clear();
  3345. }
  3346. bool start_with_case_ignore(const std::string &a,
  3347. const std::string &b) const {
  3348. if (a.size() < b.size()) { return false; }
  3349. for (size_t i = 0; i < b.size(); i++) {
  3350. if (::tolower(a[i]) != ::tolower(b[i])) { return false; }
  3351. }
  3352. return true;
  3353. }
  3354. const std::string dash_ = "--";
  3355. const std::string crlf_ = "\r\n";
  3356. const std::string dash_crlf_ = "--\r\n";
  3357. std::string boundary_;
  3358. std::string dash_boundary_crlf_;
  3359. std::string crlf_dash_boundary_;
  3360. size_t state_ = 0;
  3361. bool is_valid_ = false;
  3362. MultipartFormData file_;
  3363. // Buffer
  3364. bool start_with(const std::string &a, size_t spos, size_t epos,
  3365. const std::string &b) const {
  3366. if (epos - spos < b.size()) { return false; }
  3367. for (size_t i = 0; i < b.size(); i++) {
  3368. if (a[i + spos] != b[i]) { return false; }
  3369. }
  3370. return true;
  3371. }
  3372. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  3373. const char *buf_data() const { return &buf_[buf_spos_]; }
  3374. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  3375. bool buf_start_with(const std::string &s) const {
  3376. return start_with(buf_, buf_spos_, buf_epos_, s);
  3377. }
  3378. size_t buf_find(const std::string &s) const {
  3379. auto c = s.front();
  3380. size_t off = buf_spos_;
  3381. while (off < buf_epos_) {
  3382. auto pos = off;
  3383. while (true) {
  3384. if (pos == buf_epos_) { return buf_size(); }
  3385. if (buf_[pos] == c) { break; }
  3386. pos++;
  3387. }
  3388. auto remaining_size = buf_epos_ - pos;
  3389. if (s.size() > remaining_size) { return buf_size(); }
  3390. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  3391. off = pos + 1;
  3392. }
  3393. return buf_size();
  3394. }
  3395. void buf_append(const char *data, size_t n) {
  3396. auto remaining_size = buf_size();
  3397. if (remaining_size > 0 && buf_spos_ > 0) {
  3398. for (size_t i = 0; i < remaining_size; i++) {
  3399. buf_[i] = buf_[buf_spos_ + i];
  3400. }
  3401. }
  3402. buf_spos_ = 0;
  3403. buf_epos_ = remaining_size;
  3404. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  3405. for (size_t i = 0; i < n; i++) {
  3406. buf_[buf_epos_ + i] = data[i];
  3407. }
  3408. buf_epos_ += n;
  3409. }
  3410. void buf_erase(size_t size) { buf_spos_ += size; }
  3411. std::string buf_;
  3412. size_t buf_spos_ = 0;
  3413. size_t buf_epos_ = 0;
  3414. };
  3415. inline std::string to_lower(const char *beg, const char *end) {
  3416. std::string out;
  3417. auto it = beg;
  3418. while (it != end) {
  3419. out += static_cast<char>(::tolower(*it));
  3420. it++;
  3421. }
  3422. return out;
  3423. }
  3424. inline std::string make_multipart_data_boundary() {
  3425. static const char data[] =
  3426. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  3427. // std::random_device might actually be deterministic on some
  3428. // platforms, but due to lack of support in the c++ standard library,
  3429. // doing better requires either some ugly hacks or breaking portability.
  3430. std::random_device seed_gen;
  3431. // Request 128 bits of entropy for initialization
  3432. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  3433. std::mt19937 engine(seed_sequence);
  3434. std::string result = "--cpp-httplib-multipart-data-";
  3435. for (auto i = 0; i < 16; i++) {
  3436. result += data[engine() % (sizeof(data) - 1)];
  3437. }
  3438. return result;
  3439. }
  3440. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  3441. auto valid = true;
  3442. for (size_t i = 0; i < boundary.size(); i++) {
  3443. auto c = boundary[i];
  3444. if (!std::isalnum(c) && c != '-' && c != '_') {
  3445. valid = false;
  3446. break;
  3447. }
  3448. }
  3449. return valid;
  3450. }
  3451. template <typename T>
  3452. inline std::string
  3453. serialize_multipart_formdata_item_begin(const T &item,
  3454. const std::string &boundary) {
  3455. std::string body = "--" + boundary + "\r\n";
  3456. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3457. if (!item.filename.empty()) {
  3458. body += "; filename=\"" + item.filename + "\"";
  3459. }
  3460. body += "\r\n";
  3461. if (!item.content_type.empty()) {
  3462. body += "Content-Type: " + item.content_type + "\r\n";
  3463. }
  3464. body += "\r\n";
  3465. return body;
  3466. }
  3467. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  3468. inline std::string
  3469. serialize_multipart_formdata_finish(const std::string &boundary) {
  3470. return "--" + boundary + "--\r\n";
  3471. }
  3472. inline std::string
  3473. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  3474. return "multipart/form-data; boundary=" + boundary;
  3475. }
  3476. inline std::string
  3477. serialize_multipart_formdata(const MultipartFormDataItems &items,
  3478. const std::string &boundary, bool finish = true) {
  3479. std::string body;
  3480. for (const auto &item : items) {
  3481. body += serialize_multipart_formdata_item_begin(item, boundary);
  3482. body += item.content + serialize_multipart_formdata_item_end();
  3483. }
  3484. if (finish) body += serialize_multipart_formdata_finish(boundary);
  3485. return body;
  3486. }
  3487. inline std::pair<size_t, size_t>
  3488. get_range_offset_and_length(const Request &req, size_t content_length,
  3489. size_t index) {
  3490. auto r = req.ranges[index];
  3491. if (r.first == -1 && r.second == -1) {
  3492. return std::make_pair(0, content_length);
  3493. }
  3494. auto slen = static_cast<ssize_t>(content_length);
  3495. if (r.first == -1) {
  3496. r.first = (std::max)(static_cast<ssize_t>(0), slen - r.second);
  3497. r.second = slen - 1;
  3498. }
  3499. if (r.second == -1) { r.second = slen - 1; }
  3500. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  3501. }
  3502. inline std::string make_content_range_header_field(size_t offset, size_t length,
  3503. size_t content_length) {
  3504. std::string field = "bytes ";
  3505. field += std::to_string(offset);
  3506. field += "-";
  3507. field += std::to_string(offset + length - 1);
  3508. field += "/";
  3509. field += std::to_string(content_length);
  3510. return field;
  3511. }
  3512. template <typename SToken, typename CToken, typename Content>
  3513. bool process_multipart_ranges_data(const Request &req, Response &res,
  3514. const std::string &boundary,
  3515. const std::string &content_type,
  3516. SToken stoken, CToken ctoken,
  3517. Content content) {
  3518. for (size_t i = 0; i < req.ranges.size(); i++) {
  3519. ctoken("--");
  3520. stoken(boundary);
  3521. ctoken("\r\n");
  3522. if (!content_type.empty()) {
  3523. ctoken("Content-Type: ");
  3524. stoken(content_type);
  3525. ctoken("\r\n");
  3526. }
  3527. auto offsets = get_range_offset_and_length(req, res.body.size(), i);
  3528. auto offset = offsets.first;
  3529. auto length = offsets.second;
  3530. ctoken("Content-Range: ");
  3531. stoken(make_content_range_header_field(offset, length, res.body.size()));
  3532. ctoken("\r\n");
  3533. ctoken("\r\n");
  3534. if (!content(offset, length)) { return false; }
  3535. ctoken("\r\n");
  3536. }
  3537. ctoken("--");
  3538. stoken(boundary);
  3539. ctoken("--\r\n");
  3540. return true;
  3541. }
  3542. inline bool make_multipart_ranges_data(const Request &req, Response &res,
  3543. const std::string &boundary,
  3544. const std::string &content_type,
  3545. std::string &data) {
  3546. return process_multipart_ranges_data(
  3547. req, res, boundary, content_type,
  3548. [&](const std::string &token) { data += token; },
  3549. [&](const std::string &token) { data += token; },
  3550. [&](size_t offset, size_t length) {
  3551. if (offset < res.body.size()) {
  3552. data += res.body.substr(offset, length);
  3553. return true;
  3554. }
  3555. return false;
  3556. });
  3557. }
  3558. inline size_t
  3559. get_multipart_ranges_data_length(const Request &req, Response &res,
  3560. const std::string &boundary,
  3561. const std::string &content_type) {
  3562. size_t data_length = 0;
  3563. process_multipart_ranges_data(
  3564. req, res, boundary, content_type,
  3565. [&](const std::string &token) { data_length += token.size(); },
  3566. [&](const std::string &token) { data_length += token.size(); },
  3567. [&](size_t /*offset*/, size_t length) {
  3568. data_length += length;
  3569. return true;
  3570. });
  3571. return data_length;
  3572. }
  3573. template <typename T>
  3574. inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
  3575. Response &res,
  3576. const std::string &boundary,
  3577. const std::string &content_type,
  3578. const T &is_shutting_down) {
  3579. return process_multipart_ranges_data(
  3580. req, res, boundary, content_type,
  3581. [&](const std::string &token) { strm.write(token); },
  3582. [&](const std::string &token) { strm.write(token); },
  3583. [&](size_t offset, size_t length) {
  3584. return write_content(strm, res.content_provider_, offset, length,
  3585. is_shutting_down);
  3586. });
  3587. }
  3588. inline std::pair<size_t, size_t>
  3589. get_range_offset_and_length(const Request &req, const Response &res,
  3590. size_t index) {
  3591. auto r = req.ranges[index];
  3592. if (r.second == -1) {
  3593. r.second = static_cast<ssize_t>(res.content_length_) - 1;
  3594. }
  3595. return std::make_pair(r.first, r.second - r.first + 1);
  3596. }
  3597. inline bool expect_content(const Request &req) {
  3598. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  3599. req.method == "PRI" || req.method == "DELETE") {
  3600. return true;
  3601. }
  3602. // TODO: check if Content-Length is set
  3603. return false;
  3604. }
  3605. inline bool has_crlf(const std::string &s) {
  3606. auto p = s.c_str();
  3607. while (*p) {
  3608. if (*p == '\r' || *p == '\n') { return true; }
  3609. p++;
  3610. }
  3611. return false;
  3612. }
  3613. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3614. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  3615. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  3616. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  3617. unsigned int hash_length = 0;
  3618. unsigned char hash[EVP_MAX_MD_SIZE];
  3619. EVP_DigestInit_ex(context.get(), algo, nullptr);
  3620. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  3621. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  3622. std::stringstream ss;
  3623. for (auto i = 0u; i < hash_length; ++i) {
  3624. ss << std::hex << std::setw(2) << std::setfill('0')
  3625. << (unsigned int)hash[i];
  3626. }
  3627. return ss.str();
  3628. }
  3629. inline std::string MD5(const std::string &s) {
  3630. return message_digest(s, EVP_md5());
  3631. }
  3632. inline std::string SHA_256(const std::string &s) {
  3633. return message_digest(s, EVP_sha256());
  3634. }
  3635. inline std::string SHA_512(const std::string &s) {
  3636. return message_digest(s, EVP_sha512());
  3637. }
  3638. #endif
  3639. #ifdef _WIN32
  3640. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3641. // NOTE: This code came up with the following stackoverflow post:
  3642. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  3643. inline bool load_system_certs_on_windows(X509_STORE *store) {
  3644. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  3645. if (!hStore) { return false; }
  3646. PCCERT_CONTEXT pContext = NULL;
  3647. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  3648. nullptr) {
  3649. auto encoded_cert =
  3650. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  3651. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  3652. if (x509) {
  3653. X509_STORE_add_cert(store, x509);
  3654. X509_free(x509);
  3655. }
  3656. }
  3657. CertFreeCertificateContext(pContext);
  3658. CertCloseStore(hStore, 0);
  3659. return true;
  3660. }
  3661. #endif
  3662. class WSInit {
  3663. public:
  3664. WSInit() {
  3665. WSADATA wsaData;
  3666. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  3667. }
  3668. ~WSInit() {
  3669. if (is_valid_) WSACleanup();
  3670. }
  3671. bool is_valid_ = false;
  3672. };
  3673. static WSInit wsinit_;
  3674. #endif
  3675. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3676. inline std::pair<std::string, std::string> make_digest_authentication_header(
  3677. const Request &req, const std::map<std::string, std::string> &auth,
  3678. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  3679. const std::string &password, bool is_proxy = false) {
  3680. std::string nc;
  3681. {
  3682. std::stringstream ss;
  3683. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  3684. nc = ss.str();
  3685. }
  3686. std::string qop;
  3687. if (auth.find("qop") != auth.end()) {
  3688. qop = auth.at("qop");
  3689. if (qop.find("auth-int") != std::string::npos) {
  3690. qop = "auth-int";
  3691. } else if (qop.find("auth") != std::string::npos) {
  3692. qop = "auth";
  3693. } else {
  3694. qop.clear();
  3695. }
  3696. }
  3697. std::string algo = "MD5";
  3698. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  3699. std::string response;
  3700. {
  3701. auto H = algo == "SHA-256" ? detail::SHA_256
  3702. : algo == "SHA-512" ? detail::SHA_512
  3703. : detail::MD5;
  3704. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  3705. auto A2 = req.method + ":" + req.path;
  3706. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  3707. if (qop.empty()) {
  3708. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  3709. } else {
  3710. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  3711. ":" + qop + ":" + H(A2));
  3712. }
  3713. }
  3714. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  3715. auto field = "Digest username=\"" + username + "\", realm=\"" +
  3716. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  3717. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  3718. (qop.empty() ? ", response=\""
  3719. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  3720. cnonce + "\", response=\"") +
  3721. response + "\"" +
  3722. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  3723. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3724. return std::make_pair(key, field);
  3725. }
  3726. #endif
  3727. inline bool parse_www_authenticate(const Response &res,
  3728. std::map<std::string, std::string> &auth,
  3729. bool is_proxy) {
  3730. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  3731. if (res.has_header(auth_key)) {
  3732. static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  3733. auto s = res.get_header_value(auth_key);
  3734. auto pos = s.find(' ');
  3735. if (pos != std::string::npos) {
  3736. auto type = s.substr(0, pos);
  3737. if (type == "Basic") {
  3738. return false;
  3739. } else if (type == "Digest") {
  3740. s = s.substr(pos + 1);
  3741. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  3742. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  3743. auto m = *i;
  3744. auto key = s.substr(static_cast<size_t>(m.position(1)),
  3745. static_cast<size_t>(m.length(1)));
  3746. auto val = m.length(2) > 0
  3747. ? s.substr(static_cast<size_t>(m.position(2)),
  3748. static_cast<size_t>(m.length(2)))
  3749. : s.substr(static_cast<size_t>(m.position(3)),
  3750. static_cast<size_t>(m.length(3)));
  3751. auth[key] = val;
  3752. }
  3753. return true;
  3754. }
  3755. }
  3756. }
  3757. return false;
  3758. }
  3759. // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
  3760. inline std::string random_string(size_t length) {
  3761. auto randchar = []() -> char {
  3762. const char charset[] = "0123456789"
  3763. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3764. "abcdefghijklmnopqrstuvwxyz";
  3765. const size_t max_index = (sizeof(charset) - 1);
  3766. return charset[static_cast<size_t>(std::rand()) % max_index];
  3767. };
  3768. std::string str(length, 0);
  3769. std::generate_n(str.begin(), length, randchar);
  3770. return str;
  3771. }
  3772. class ContentProviderAdapter {
  3773. public:
  3774. explicit ContentProviderAdapter(
  3775. ContentProviderWithoutLength &&content_provider)
  3776. : content_provider_(content_provider) {}
  3777. bool operator()(size_t offset, size_t, DataSink &sink) {
  3778. return content_provider_(offset, sink);
  3779. }
  3780. private:
  3781. ContentProviderWithoutLength content_provider_;
  3782. };
  3783. } // namespace detail
  3784. inline std::string hosted_at(const std::string &hostname) {
  3785. std::vector<std::string> addrs;
  3786. hosted_at(hostname, addrs);
  3787. if (addrs.empty()) { return std::string(); }
  3788. return addrs[0];
  3789. }
  3790. inline void hosted_at(const std::string &hostname,
  3791. std::vector<std::string> &addrs) {
  3792. struct addrinfo hints;
  3793. struct addrinfo *result;
  3794. memset(&hints, 0, sizeof(struct addrinfo));
  3795. hints.ai_family = AF_UNSPEC;
  3796. hints.ai_socktype = SOCK_STREAM;
  3797. hints.ai_protocol = 0;
  3798. if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) {
  3799. #if defined __linux__ && !defined __ANDROID__
  3800. res_init();
  3801. #endif
  3802. return;
  3803. }
  3804. for (auto rp = result; rp; rp = rp->ai_next) {
  3805. const auto &addr =
  3806. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  3807. std::string ip;
  3808. int dummy = -1;
  3809. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  3810. dummy)) {
  3811. addrs.push_back(ip);
  3812. }
  3813. }
  3814. freeaddrinfo(result);
  3815. }
  3816. inline std::string append_query_params(const std::string &path,
  3817. const Params &params) {
  3818. std::string path_with_query = path;
  3819. const static std::regex re("[^?]+\\?.*");
  3820. auto delm = std::regex_match(path, re) ? '&' : '?';
  3821. path_with_query += delm + detail::params_to_query_str(params);
  3822. return path_with_query;
  3823. }
  3824. // Header utilities
  3825. inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
  3826. std::string field = "bytes=";
  3827. auto i = 0;
  3828. for (auto r : ranges) {
  3829. if (i != 0) { field += ", "; }
  3830. if (r.first != -1) { field += std::to_string(r.first); }
  3831. field += '-';
  3832. if (r.second != -1) { field += std::to_string(r.second); }
  3833. i++;
  3834. }
  3835. return std::make_pair("Range", std::move(field));
  3836. }
  3837. inline std::pair<std::string, std::string>
  3838. make_basic_authentication_header(const std::string &username,
  3839. const std::string &password, bool is_proxy) {
  3840. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  3841. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3842. return std::make_pair(key, std::move(field));
  3843. }
  3844. inline std::pair<std::string, std::string>
  3845. make_bearer_token_authentication_header(const std::string &token,
  3846. bool is_proxy = false) {
  3847. auto field = "Bearer " + token;
  3848. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3849. return std::make_pair(key, std::move(field));
  3850. }
  3851. // Request implementation
  3852. inline bool Request::has_header(const std::string &key) const {
  3853. return detail::has_header(headers, key);
  3854. }
  3855. inline std::string Request::get_header_value(const std::string &key,
  3856. size_t id) const {
  3857. return detail::get_header_value(headers, key, id, "");
  3858. }
  3859. inline size_t Request::get_header_value_count(const std::string &key) const {
  3860. auto r = headers.equal_range(key);
  3861. return static_cast<size_t>(std::distance(r.first, r.second));
  3862. }
  3863. inline void Request::set_header(const std::string &key,
  3864. const std::string &val) {
  3865. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  3866. headers.emplace(key, val);
  3867. }
  3868. }
  3869. inline bool Request::has_param(const std::string &key) const {
  3870. return params.find(key) != params.end();
  3871. }
  3872. inline std::string Request::get_param_value(const std::string &key,
  3873. size_t id) const {
  3874. auto rng = params.equal_range(key);
  3875. auto it = rng.first;
  3876. std::advance(it, static_cast<ssize_t>(id));
  3877. if (it != rng.second) { return it->second; }
  3878. return std::string();
  3879. }
  3880. inline size_t Request::get_param_value_count(const std::string &key) const {
  3881. auto r = params.equal_range(key);
  3882. return static_cast<size_t>(std::distance(r.first, r.second));
  3883. }
  3884. inline bool Request::is_multipart_form_data() const {
  3885. const auto &content_type = get_header_value("Content-Type");
  3886. return !content_type.rfind("multipart/form-data", 0);
  3887. }
  3888. inline bool Request::has_file(const std::string &key) const {
  3889. return files.find(key) != files.end();
  3890. }
  3891. inline MultipartFormData Request::get_file_value(const std::string &key) const {
  3892. auto it = files.find(key);
  3893. if (it != files.end()) { return it->second; }
  3894. return MultipartFormData();
  3895. }
  3896. // Response implementation
  3897. inline bool Response::has_header(const std::string &key) const {
  3898. return headers.find(key) != headers.end();
  3899. }
  3900. inline std::string Response::get_header_value(const std::string &key,
  3901. size_t id) const {
  3902. return detail::get_header_value(headers, key, id, "");
  3903. }
  3904. inline size_t Response::get_header_value_count(const std::string &key) const {
  3905. auto r = headers.equal_range(key);
  3906. return static_cast<size_t>(std::distance(r.first, r.second));
  3907. }
  3908. inline void Response::set_header(const std::string &key,
  3909. const std::string &val) {
  3910. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  3911. headers.emplace(key, val);
  3912. }
  3913. }
  3914. inline void Response::set_redirect(const std::string &url, int stat) {
  3915. if (!detail::has_crlf(url)) {
  3916. set_header("Location", url);
  3917. if (300 <= stat && stat < 400) {
  3918. this->status = stat;
  3919. } else {
  3920. this->status = 302;
  3921. }
  3922. }
  3923. }
  3924. inline void Response::set_content(const char *s, size_t n,
  3925. const std::string &content_type) {
  3926. body.assign(s, n);
  3927. auto rng = headers.equal_range("Content-Type");
  3928. headers.erase(rng.first, rng.second);
  3929. set_header("Content-Type", content_type);
  3930. }
  3931. inline void Response::set_content(const std::string &s,
  3932. const std::string &content_type) {
  3933. set_content(s.data(), s.size(), content_type);
  3934. }
  3935. inline void Response::set_content_provider(
  3936. size_t in_length, const std::string &content_type, ContentProvider provider,
  3937. ContentProviderResourceReleaser resource_releaser) {
  3938. assert(in_length > 0);
  3939. set_header("Content-Type", content_type);
  3940. content_length_ = in_length;
  3941. content_provider_ = std::move(provider);
  3942. content_provider_resource_releaser_ = resource_releaser;
  3943. is_chunked_content_provider_ = false;
  3944. }
  3945. inline void Response::set_content_provider(
  3946. const std::string &content_type, ContentProviderWithoutLength provider,
  3947. ContentProviderResourceReleaser resource_releaser) {
  3948. set_header("Content-Type", content_type);
  3949. content_length_ = 0;
  3950. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  3951. content_provider_resource_releaser_ = resource_releaser;
  3952. is_chunked_content_provider_ = false;
  3953. }
  3954. inline void Response::set_chunked_content_provider(
  3955. const std::string &content_type, ContentProviderWithoutLength provider,
  3956. ContentProviderResourceReleaser resource_releaser) {
  3957. set_header("Content-Type", content_type);
  3958. content_length_ = 0;
  3959. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  3960. content_provider_resource_releaser_ = resource_releaser;
  3961. is_chunked_content_provider_ = true;
  3962. }
  3963. // Result implementation
  3964. inline bool Result::has_request_header(const std::string &key) const {
  3965. return request_headers_.find(key) != request_headers_.end();
  3966. }
  3967. inline std::string Result::get_request_header_value(const std::string &key,
  3968. size_t id) const {
  3969. return detail::get_header_value(request_headers_, key, id, "");
  3970. }
  3971. inline size_t
  3972. Result::get_request_header_value_count(const std::string &key) const {
  3973. auto r = request_headers_.equal_range(key);
  3974. return static_cast<size_t>(std::distance(r.first, r.second));
  3975. }
  3976. // Stream implementation
  3977. inline ssize_t Stream::write(const char *ptr) {
  3978. return write(ptr, strlen(ptr));
  3979. }
  3980. inline ssize_t Stream::write(const std::string &s) {
  3981. return write(s.data(), s.size());
  3982. }
  3983. namespace detail {
  3984. // Socket stream implementation
  3985. inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
  3986. time_t read_timeout_usec,
  3987. time_t write_timeout_sec,
  3988. time_t write_timeout_usec)
  3989. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  3990. read_timeout_usec_(read_timeout_usec),
  3991. write_timeout_sec_(write_timeout_sec),
  3992. write_timeout_usec_(write_timeout_usec), read_buff_(read_buff_size_, 0) {}
  3993. inline SocketStream::~SocketStream() {}
  3994. inline bool SocketStream::is_readable() const {
  3995. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  3996. }
  3997. inline bool SocketStream::is_writable() const {
  3998. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  3999. is_socket_alive(sock_);
  4000. }
  4001. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  4002. #ifdef _WIN32
  4003. size =
  4004. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  4005. #else
  4006. size = (std::min)(size,
  4007. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  4008. #endif
  4009. if (read_buff_off_ < read_buff_content_size_) {
  4010. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  4011. if (size <= remaining_size) {
  4012. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  4013. read_buff_off_ += size;
  4014. return static_cast<ssize_t>(size);
  4015. } else {
  4016. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  4017. read_buff_off_ += remaining_size;
  4018. return static_cast<ssize_t>(remaining_size);
  4019. }
  4020. }
  4021. if (!is_readable()) { return -1; }
  4022. read_buff_off_ = 0;
  4023. read_buff_content_size_ = 0;
  4024. if (size < read_buff_size_) {
  4025. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  4026. CPPHTTPLIB_RECV_FLAGS);
  4027. if (n <= 0) {
  4028. return n;
  4029. } else if (n <= static_cast<ssize_t>(size)) {
  4030. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  4031. return n;
  4032. } else {
  4033. memcpy(ptr, read_buff_.data(), size);
  4034. read_buff_off_ = size;
  4035. read_buff_content_size_ = static_cast<size_t>(n);
  4036. return static_cast<ssize_t>(size);
  4037. }
  4038. } else {
  4039. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  4040. }
  4041. }
  4042. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  4043. if (!is_writable()) { return -1; }
  4044. #if defined(_WIN32) && !defined(_WIN64)
  4045. size =
  4046. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  4047. #endif
  4048. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  4049. }
  4050. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  4051. int &port) const {
  4052. return detail::get_remote_ip_and_port(sock_, ip, port);
  4053. }
  4054. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  4055. int &port) const {
  4056. return detail::get_local_ip_and_port(sock_, ip, port);
  4057. }
  4058. inline socket_t SocketStream::socket() const { return sock_; }
  4059. // Buffer stream implementation
  4060. inline bool BufferStream::is_readable() const { return true; }
  4061. inline bool BufferStream::is_writable() const { return true; }
  4062. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  4063. #if defined(_MSC_VER) && _MSC_VER < 1910
  4064. auto len_read = buffer._Copy_s(ptr, size, size, position);
  4065. #else
  4066. auto len_read = buffer.copy(ptr, size, position);
  4067. #endif
  4068. position += static_cast<size_t>(len_read);
  4069. return static_cast<ssize_t>(len_read);
  4070. }
  4071. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  4072. buffer.append(ptr, size);
  4073. return static_cast<ssize_t>(size);
  4074. }
  4075. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  4076. int & /*port*/) const {}
  4077. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  4078. int & /*port*/) const {}
  4079. inline socket_t BufferStream::socket() const { return 0; }
  4080. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  4081. } // namespace detail
  4082. // HTTP server implementation
  4083. inline Server::Server()
  4084. : new_task_queue(
  4085. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }),
  4086. svr_sock_(INVALID_SOCKET), is_running_(false) {
  4087. #ifndef _WIN32
  4088. signal(SIGPIPE, SIG_IGN);
  4089. #endif
  4090. }
  4091. inline Server::~Server() {}
  4092. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  4093. get_handlers_.push_back(
  4094. std::make_pair(std::regex(pattern), std::move(handler)));
  4095. return *this;
  4096. }
  4097. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  4098. post_handlers_.push_back(
  4099. std::make_pair(std::regex(pattern), std::move(handler)));
  4100. return *this;
  4101. }
  4102. inline Server &Server::Post(const std::string &pattern,
  4103. HandlerWithContentReader handler) {
  4104. post_handlers_for_content_reader_.push_back(
  4105. std::make_pair(std::regex(pattern), std::move(handler)));
  4106. return *this;
  4107. }
  4108. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  4109. put_handlers_.push_back(
  4110. std::make_pair(std::regex(pattern), std::move(handler)));
  4111. return *this;
  4112. }
  4113. inline Server &Server::Put(const std::string &pattern,
  4114. HandlerWithContentReader handler) {
  4115. put_handlers_for_content_reader_.push_back(
  4116. std::make_pair(std::regex(pattern), std::move(handler)));
  4117. return *this;
  4118. }
  4119. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  4120. patch_handlers_.push_back(
  4121. std::make_pair(std::regex(pattern), std::move(handler)));
  4122. return *this;
  4123. }
  4124. inline Server &Server::Patch(const std::string &pattern,
  4125. HandlerWithContentReader handler) {
  4126. patch_handlers_for_content_reader_.push_back(
  4127. std::make_pair(std::regex(pattern), std::move(handler)));
  4128. return *this;
  4129. }
  4130. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  4131. delete_handlers_.push_back(
  4132. std::make_pair(std::regex(pattern), std::move(handler)));
  4133. return *this;
  4134. }
  4135. inline Server &Server::Delete(const std::string &pattern,
  4136. HandlerWithContentReader handler) {
  4137. delete_handlers_for_content_reader_.push_back(
  4138. std::make_pair(std::regex(pattern), std::move(handler)));
  4139. return *this;
  4140. }
  4141. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  4142. options_handlers_.push_back(
  4143. std::make_pair(std::regex(pattern), std::move(handler)));
  4144. return *this;
  4145. }
  4146. inline bool Server::set_base_dir(const std::string &dir,
  4147. const std::string &mount_point) {
  4148. return set_mount_point(mount_point, dir);
  4149. }
  4150. inline bool Server::set_mount_point(const std::string &mount_point,
  4151. const std::string &dir, Headers headers) {
  4152. if (detail::is_dir(dir)) {
  4153. std::string mnt = !mount_point.empty() ? mount_point : "/";
  4154. if (!mnt.empty() && mnt[0] == '/') {
  4155. base_dirs_.push_back({mnt, dir, std::move(headers)});
  4156. return true;
  4157. }
  4158. }
  4159. return false;
  4160. }
  4161. inline bool Server::remove_mount_point(const std::string &mount_point) {
  4162. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  4163. if (it->mount_point == mount_point) {
  4164. base_dirs_.erase(it);
  4165. return true;
  4166. }
  4167. }
  4168. return false;
  4169. }
  4170. inline Server &
  4171. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  4172. const std::string &mime) {
  4173. file_extension_and_mimetype_map_[ext] = mime;
  4174. return *this;
  4175. }
  4176. inline Server &Server::set_file_request_handler(Handler handler) {
  4177. file_request_handler_ = std::move(handler);
  4178. return *this;
  4179. }
  4180. inline Server &Server::set_error_handler(HandlerWithResponse handler) {
  4181. error_handler_ = std::move(handler);
  4182. return *this;
  4183. }
  4184. inline Server &Server::set_error_handler(Handler handler) {
  4185. error_handler_ = [handler](const Request &req, Response &res) {
  4186. handler(req, res);
  4187. return HandlerResponse::Handled;
  4188. };
  4189. return *this;
  4190. }
  4191. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  4192. exception_handler_ = std::move(handler);
  4193. return *this;
  4194. }
  4195. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  4196. pre_routing_handler_ = std::move(handler);
  4197. return *this;
  4198. }
  4199. inline Server &Server::set_post_routing_handler(Handler handler) {
  4200. post_routing_handler_ = std::move(handler);
  4201. return *this;
  4202. }
  4203. inline Server &Server::set_logger(Logger logger) {
  4204. logger_ = std::move(logger);
  4205. return *this;
  4206. }
  4207. inline Server &
  4208. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  4209. expect_100_continue_handler_ = std::move(handler);
  4210. return *this;
  4211. }
  4212. inline Server &Server::set_address_family(int family) {
  4213. address_family_ = family;
  4214. return *this;
  4215. }
  4216. inline Server &Server::set_tcp_nodelay(bool on) {
  4217. tcp_nodelay_ = on;
  4218. return *this;
  4219. }
  4220. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  4221. socket_options_ = std::move(socket_options);
  4222. return *this;
  4223. }
  4224. inline Server &Server::set_default_headers(Headers headers) {
  4225. default_headers_ = std::move(headers);
  4226. return *this;
  4227. }
  4228. inline Server &Server::set_keep_alive_max_count(size_t count) {
  4229. keep_alive_max_count_ = count;
  4230. return *this;
  4231. }
  4232. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  4233. keep_alive_timeout_sec_ = sec;
  4234. return *this;
  4235. }
  4236. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  4237. read_timeout_sec_ = sec;
  4238. read_timeout_usec_ = usec;
  4239. return *this;
  4240. }
  4241. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  4242. write_timeout_sec_ = sec;
  4243. write_timeout_usec_ = usec;
  4244. return *this;
  4245. }
  4246. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  4247. idle_interval_sec_ = sec;
  4248. idle_interval_usec_ = usec;
  4249. return *this;
  4250. }
  4251. inline Server &Server::set_payload_max_length(size_t length) {
  4252. payload_max_length_ = length;
  4253. return *this;
  4254. }
  4255. inline bool Server::bind_to_port(const std::string &host, int port,
  4256. int socket_flags) {
  4257. if (bind_internal(host, port, socket_flags) < 0) return false;
  4258. return true;
  4259. }
  4260. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  4261. return bind_internal(host, 0, socket_flags);
  4262. }
  4263. inline bool Server::listen_after_bind() { return listen_internal(); }
  4264. inline bool Server::listen(const std::string &host, int port,
  4265. int socket_flags) {
  4266. return bind_to_port(host, port, socket_flags) && listen_internal();
  4267. }
  4268. inline bool Server::is_running() const { return is_running_; }
  4269. inline void Server::stop() {
  4270. if (is_running_) {
  4271. assert(svr_sock_ != INVALID_SOCKET);
  4272. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  4273. detail::shutdown_socket(sock);
  4274. detail::close_socket(sock);
  4275. }
  4276. }
  4277. inline bool Server::parse_request_line(const char *s, Request &req) {
  4278. auto len = strlen(s);
  4279. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  4280. len -= 2;
  4281. {
  4282. size_t count = 0;
  4283. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  4284. switch (count) {
  4285. case 0: req.method = std::string(b, e); break;
  4286. case 1: req.target = std::string(b, e); break;
  4287. case 2: req.version = std::string(b, e); break;
  4288. default: break;
  4289. }
  4290. count++;
  4291. });
  4292. if (count != 3) { return false; }
  4293. }
  4294. static const std::set<std::string> methods{
  4295. "GET", "HEAD", "POST", "PUT", "DELETE",
  4296. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  4297. if (methods.find(req.method) == methods.end()) { return false; }
  4298. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; }
  4299. {
  4300. // Skip URL fragment
  4301. for (size_t i = 0; i < req.target.size(); i++) {
  4302. if (req.target[i] == '#') {
  4303. req.target.erase(i);
  4304. break;
  4305. }
  4306. }
  4307. size_t count = 0;
  4308. detail::split(req.target.data(), req.target.data() + req.target.size(), '?',
  4309. [&](const char *b, const char *e) {
  4310. switch (count) {
  4311. case 0:
  4312. req.path = detail::decode_url(std::string(b, e), false);
  4313. break;
  4314. case 1: {
  4315. if (e - b > 0) {
  4316. detail::parse_query_text(std::string(b, e), req.params);
  4317. }
  4318. break;
  4319. }
  4320. default: break;
  4321. }
  4322. count++;
  4323. });
  4324. if (count > 2) { return false; }
  4325. }
  4326. return true;
  4327. }
  4328. inline bool Server::write_response(Stream &strm, bool close_connection,
  4329. const Request &req, Response &res) {
  4330. return write_response_core(strm, close_connection, req, res, false);
  4331. }
  4332. inline bool Server::write_response_with_content(Stream &strm,
  4333. bool close_connection,
  4334. const Request &req,
  4335. Response &res) {
  4336. return write_response_core(strm, close_connection, req, res, true);
  4337. }
  4338. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  4339. const Request &req, Response &res,
  4340. bool need_apply_ranges) {
  4341. assert(res.status != -1);
  4342. if (400 <= res.status && error_handler_ &&
  4343. error_handler_(req, res) == HandlerResponse::Handled) {
  4344. need_apply_ranges = true;
  4345. }
  4346. std::string content_type;
  4347. std::string boundary;
  4348. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  4349. // Prepare additional headers
  4350. if (close_connection || req.get_header_value("Connection") == "close") {
  4351. res.set_header("Connection", "close");
  4352. } else {
  4353. std::stringstream ss;
  4354. ss << "timeout=" << keep_alive_timeout_sec_
  4355. << ", max=" << keep_alive_max_count_;
  4356. res.set_header("Keep-Alive", ss.str());
  4357. }
  4358. if (!res.has_header("Content-Type") &&
  4359. (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) {
  4360. res.set_header("Content-Type", "text/plain");
  4361. }
  4362. if (!res.has_header("Content-Length") && res.body.empty() &&
  4363. !res.content_length_ && !res.content_provider_) {
  4364. res.set_header("Content-Length", "0");
  4365. }
  4366. if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
  4367. res.set_header("Accept-Ranges", "bytes");
  4368. }
  4369. if (post_routing_handler_) { post_routing_handler_(req, res); }
  4370. // Response line and headers
  4371. {
  4372. detail::BufferStream bstrm;
  4373. if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  4374. detail::status_message(res.status))) {
  4375. return false;
  4376. }
  4377. if (!detail::write_headers(bstrm, res.headers)) { return false; }
  4378. // Flush buffer
  4379. auto &data = bstrm.get_buffer();
  4380. detail::write_data(strm, data.data(), data.size());
  4381. }
  4382. // Body
  4383. auto ret = true;
  4384. if (req.method != "HEAD") {
  4385. if (!res.body.empty()) {
  4386. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  4387. ret = false;
  4388. }
  4389. } else if (res.content_provider_) {
  4390. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  4391. res.content_provider_success_ = true;
  4392. } else {
  4393. res.content_provider_success_ = false;
  4394. ret = false;
  4395. }
  4396. }
  4397. }
  4398. // Log
  4399. if (logger_) { logger_(req, res); }
  4400. return ret;
  4401. }
  4402. inline bool
  4403. Server::write_content_with_provider(Stream &strm, const Request &req,
  4404. Response &res, const std::string &boundary,
  4405. const std::string &content_type) {
  4406. auto is_shutting_down = [this]() {
  4407. return this->svr_sock_ == INVALID_SOCKET;
  4408. };
  4409. if (res.content_length_ > 0) {
  4410. if (req.ranges.empty()) {
  4411. return detail::write_content(strm, res.content_provider_, 0,
  4412. res.content_length_, is_shutting_down);
  4413. } else if (req.ranges.size() == 1) {
  4414. auto offsets =
  4415. detail::get_range_offset_and_length(req, res.content_length_, 0);
  4416. auto offset = offsets.first;
  4417. auto length = offsets.second;
  4418. return detail::write_content(strm, res.content_provider_, offset, length,
  4419. is_shutting_down);
  4420. } else {
  4421. return detail::write_multipart_ranges_data(
  4422. strm, req, res, boundary, content_type, is_shutting_down);
  4423. }
  4424. } else {
  4425. if (res.is_chunked_content_provider_) {
  4426. auto type = detail::encoding_type(req, res);
  4427. std::unique_ptr<detail::compressor> compressor;
  4428. if (type == detail::EncodingType::Gzip) {
  4429. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4430. compressor = detail::make_unique<detail::gzip_compressor>();
  4431. #endif
  4432. } else if (type == detail::EncodingType::Brotli) {
  4433. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4434. compressor = detail::make_unique<detail::brotli_compressor>();
  4435. #endif
  4436. } else {
  4437. compressor = detail::make_unique<detail::nocompressor>();
  4438. }
  4439. assert(compressor != nullptr);
  4440. return detail::write_content_chunked(strm, res.content_provider_,
  4441. is_shutting_down, *compressor);
  4442. } else {
  4443. return detail::write_content_without_length(strm, res.content_provider_,
  4444. is_shutting_down);
  4445. }
  4446. }
  4447. }
  4448. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  4449. MultipartFormDataMap::iterator cur;
  4450. auto file_count = 0;
  4451. if (read_content_core(
  4452. strm, req, res,
  4453. // Regular
  4454. [&](const char *buf, size_t n) {
  4455. if (req.body.size() + n > req.body.max_size()) { return false; }
  4456. req.body.append(buf, n);
  4457. return true;
  4458. },
  4459. // Multipart
  4460. [&](const MultipartFormData &file) {
  4461. if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  4462. return false;
  4463. }
  4464. cur = req.files.emplace(file.name, file);
  4465. return true;
  4466. },
  4467. [&](const char *buf, size_t n) {
  4468. auto &content = cur->second.content;
  4469. if (content.size() + n > content.max_size()) { return false; }
  4470. content.append(buf, n);
  4471. return true;
  4472. })) {
  4473. const auto &content_type = req.get_header_value("Content-Type");
  4474. if (!content_type.find("application/x-www-form-urlencoded")) {
  4475. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  4476. res.status = 413; // NOTE: should be 414?
  4477. return false;
  4478. }
  4479. detail::parse_query_text(req.body, req.params);
  4480. }
  4481. return true;
  4482. }
  4483. return false;
  4484. }
  4485. inline bool Server::read_content_with_content_receiver(
  4486. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  4487. MultipartContentHeader multipart_header,
  4488. ContentReceiver multipart_receiver) {
  4489. return read_content_core(strm, req, res, std::move(receiver),
  4490. std::move(multipart_header),
  4491. std::move(multipart_receiver));
  4492. }
  4493. inline bool Server::read_content_core(Stream &strm, Request &req, Response &res,
  4494. ContentReceiver receiver,
  4495. MultipartContentHeader mulitpart_header,
  4496. ContentReceiver multipart_receiver) {
  4497. detail::MultipartFormDataParser multipart_form_data_parser;
  4498. ContentReceiverWithProgress out;
  4499. if (req.is_multipart_form_data()) {
  4500. const auto &content_type = req.get_header_value("Content-Type");
  4501. std::string boundary;
  4502. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  4503. res.status = 400;
  4504. return false;
  4505. }
  4506. multipart_form_data_parser.set_boundary(std::move(boundary));
  4507. out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {
  4508. /* For debug
  4509. size_t pos = 0;
  4510. while (pos < n) {
  4511. auto read_size = (std::min)<size_t>(1, n - pos);
  4512. auto ret = multipart_form_data_parser.parse(
  4513. buf + pos, read_size, multipart_receiver, mulitpart_header);
  4514. if (!ret) { return false; }
  4515. pos += read_size;
  4516. }
  4517. return true;
  4518. */
  4519. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  4520. mulitpart_header);
  4521. };
  4522. } else {
  4523. out = [receiver](const char *buf, size_t n, uint64_t /*off*/,
  4524. uint64_t /*len*/) { return receiver(buf, n); };
  4525. }
  4526. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  4527. return true;
  4528. }
  4529. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  4530. out, true)) {
  4531. return false;
  4532. }
  4533. if (req.is_multipart_form_data()) {
  4534. if (!multipart_form_data_parser.is_valid()) {
  4535. res.status = 400;
  4536. return false;
  4537. }
  4538. }
  4539. return true;
  4540. }
  4541. inline bool Server::handle_file_request(const Request &req, Response &res,
  4542. bool head) {
  4543. for (const auto &entry : base_dirs_) {
  4544. // Prefix match
  4545. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  4546. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  4547. if (detail::is_valid_path(sub_path)) {
  4548. auto path = entry.base_dir + sub_path;
  4549. if (path.back() == '/') { path += "index.html"; }
  4550. if (detail::is_file(path)) {
  4551. detail::read_file(path, res.body);
  4552. auto type =
  4553. detail::find_content_type(path, file_extension_and_mimetype_map_);
  4554. if (type) { res.set_header("Content-Type", type); }
  4555. for (const auto &kv : entry.headers) {
  4556. res.set_header(kv.first.c_str(), kv.second);
  4557. }
  4558. res.status = req.has_header("Range") ? 206 : 200;
  4559. if (!head && file_request_handler_) {
  4560. file_request_handler_(req, res);
  4561. }
  4562. return true;
  4563. }
  4564. }
  4565. }
  4566. }
  4567. return false;
  4568. }
  4569. inline socket_t
  4570. Server::create_server_socket(const std::string &host, int port,
  4571. int socket_flags,
  4572. SocketOptions socket_options) const {
  4573. return detail::create_socket(
  4574. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  4575. std::move(socket_options),
  4576. [](socket_t sock, struct addrinfo &ai) -> bool {
  4577. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4578. return false;
  4579. }
  4580. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; }
  4581. return true;
  4582. });
  4583. }
  4584. inline int Server::bind_internal(const std::string &host, int port,
  4585. int socket_flags) {
  4586. if (!is_valid()) { return -1; }
  4587. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  4588. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  4589. if (port == 0) {
  4590. struct sockaddr_storage addr;
  4591. socklen_t addr_len = sizeof(addr);
  4592. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  4593. &addr_len) == -1) {
  4594. return -1;
  4595. }
  4596. if (addr.ss_family == AF_INET) {
  4597. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  4598. } else if (addr.ss_family == AF_INET6) {
  4599. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  4600. } else {
  4601. return -1;
  4602. }
  4603. } else {
  4604. return port;
  4605. }
  4606. }
  4607. inline bool Server::listen_internal() {
  4608. auto ret = true;
  4609. is_running_ = true;
  4610. {
  4611. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  4612. while (svr_sock_ != INVALID_SOCKET) {
  4613. #ifndef _WIN32
  4614. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  4615. #endif
  4616. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  4617. idle_interval_usec_);
  4618. if (val == 0) { // Timeout
  4619. task_queue->on_idle();
  4620. continue;
  4621. }
  4622. #ifndef _WIN32
  4623. }
  4624. #endif
  4625. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  4626. if (sock == INVALID_SOCKET) {
  4627. if (errno == EMFILE) {
  4628. // The per-process limit of open file descriptors has been reached.
  4629. // Try to accept new connections after a short sleep.
  4630. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4631. continue;
  4632. } else if (errno == EINTR || errno == EAGAIN) {
  4633. continue;
  4634. }
  4635. if (svr_sock_ != INVALID_SOCKET) {
  4636. detail::close_socket(svr_sock_);
  4637. ret = false;
  4638. } else {
  4639. ; // The server socket was closed by user.
  4640. }
  4641. break;
  4642. }
  4643. {
  4644. #ifdef _WIN32
  4645. auto timeout = static_cast<uint32_t>(read_timeout_sec_ * 1000 +
  4646. read_timeout_usec_ / 1000);
  4647. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
  4648. sizeof(timeout));
  4649. #else
  4650. timeval tv;
  4651. tv.tv_sec = static_cast<long>(read_timeout_sec_);
  4652. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec_);
  4653. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
  4654. #endif
  4655. }
  4656. {
  4657. #ifdef _WIN32
  4658. auto timeout = static_cast<uint32_t>(write_timeout_sec_ * 1000 +
  4659. write_timeout_usec_ / 1000);
  4660. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
  4661. sizeof(timeout));
  4662. #else
  4663. timeval tv;
  4664. tv.tv_sec = static_cast<long>(write_timeout_sec_);
  4665. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec_);
  4666. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
  4667. #endif
  4668. }
  4669. #if __cplusplus > 201703L
  4670. task_queue->enqueue([=, this]() { process_and_close_socket(sock); });
  4671. #else
  4672. task_queue->enqueue([=]() { process_and_close_socket(sock); });
  4673. #endif
  4674. }
  4675. task_queue->shutdown();
  4676. }
  4677. is_running_ = false;
  4678. return ret;
  4679. }
  4680. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  4681. if (pre_routing_handler_ &&
  4682. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  4683. return true;
  4684. }
  4685. // File handler
  4686. bool is_head_request = req.method == "HEAD";
  4687. if ((req.method == "GET" || is_head_request) &&
  4688. handle_file_request(req, res, is_head_request)) {
  4689. return true;
  4690. }
  4691. if (detail::expect_content(req)) {
  4692. // Content reader handler
  4693. {
  4694. ContentReader reader(
  4695. [&](ContentReceiver receiver) {
  4696. return read_content_with_content_receiver(
  4697. strm, req, res, std::move(receiver), nullptr, nullptr);
  4698. },
  4699. [&](MultipartContentHeader header, ContentReceiver receiver) {
  4700. return read_content_with_content_receiver(strm, req, res, nullptr,
  4701. std::move(header),
  4702. std::move(receiver));
  4703. });
  4704. if (req.method == "POST") {
  4705. if (dispatch_request_for_content_reader(
  4706. req, res, std::move(reader),
  4707. post_handlers_for_content_reader_)) {
  4708. return true;
  4709. }
  4710. } else if (req.method == "PUT") {
  4711. if (dispatch_request_for_content_reader(
  4712. req, res, std::move(reader),
  4713. put_handlers_for_content_reader_)) {
  4714. return true;
  4715. }
  4716. } else if (req.method == "PATCH") {
  4717. if (dispatch_request_for_content_reader(
  4718. req, res, std::move(reader),
  4719. patch_handlers_for_content_reader_)) {
  4720. return true;
  4721. }
  4722. } else if (req.method == "DELETE") {
  4723. if (dispatch_request_for_content_reader(
  4724. req, res, std::move(reader),
  4725. delete_handlers_for_content_reader_)) {
  4726. return true;
  4727. }
  4728. }
  4729. }
  4730. // Read content into `req.body`
  4731. if (!read_content(strm, req, res)) { return false; }
  4732. }
  4733. // Regular handler
  4734. if (req.method == "GET" || req.method == "HEAD") {
  4735. return dispatch_request(req, res, get_handlers_);
  4736. } else if (req.method == "POST") {
  4737. return dispatch_request(req, res, post_handlers_);
  4738. } else if (req.method == "PUT") {
  4739. return dispatch_request(req, res, put_handlers_);
  4740. } else if (req.method == "DELETE") {
  4741. return dispatch_request(req, res, delete_handlers_);
  4742. } else if (req.method == "OPTIONS") {
  4743. return dispatch_request(req, res, options_handlers_);
  4744. } else if (req.method == "PATCH") {
  4745. return dispatch_request(req, res, patch_handlers_);
  4746. }
  4747. res.status = 400;
  4748. return false;
  4749. }
  4750. inline bool Server::dispatch_request(Request &req, Response &res,
  4751. const Handlers &handlers) {
  4752. for (const auto &x : handlers) {
  4753. const auto &pattern = x.first;
  4754. const auto &handler = x.second;
  4755. if (std::regex_match(req.path, req.matches, pattern)) {
  4756. handler(req, res);
  4757. return true;
  4758. }
  4759. }
  4760. return false;
  4761. }
  4762. inline void Server::apply_ranges(const Request &req, Response &res,
  4763. std::string &content_type,
  4764. std::string &boundary) {
  4765. if (req.ranges.size() > 1) {
  4766. boundary = detail::make_multipart_data_boundary();
  4767. auto it = res.headers.find("Content-Type");
  4768. if (it != res.headers.end()) {
  4769. content_type = it->second;
  4770. res.headers.erase(it);
  4771. }
  4772. res.headers.emplace("Content-Type",
  4773. "multipart/byteranges; boundary=" + boundary);
  4774. }
  4775. auto type = detail::encoding_type(req, res);
  4776. if (res.body.empty()) {
  4777. if (res.content_length_ > 0) {
  4778. size_t length = 0;
  4779. if (req.ranges.empty()) {
  4780. length = res.content_length_;
  4781. } else if (req.ranges.size() == 1) {
  4782. auto offsets =
  4783. detail::get_range_offset_and_length(req, res.content_length_, 0);
  4784. auto offset = offsets.first;
  4785. length = offsets.second;
  4786. auto content_range = detail::make_content_range_header_field(
  4787. offset, length, res.content_length_);
  4788. res.set_header("Content-Range", content_range);
  4789. } else {
  4790. length = detail::get_multipart_ranges_data_length(req, res, boundary,
  4791. content_type);
  4792. }
  4793. res.set_header("Content-Length", std::to_string(length));
  4794. } else {
  4795. if (res.content_provider_) {
  4796. if (res.is_chunked_content_provider_) {
  4797. res.set_header("Transfer-Encoding", "chunked");
  4798. if (type == detail::EncodingType::Gzip) {
  4799. res.set_header("Content-Encoding", "gzip");
  4800. } else if (type == detail::EncodingType::Brotli) {
  4801. res.set_header("Content-Encoding", "br");
  4802. }
  4803. }
  4804. }
  4805. }
  4806. } else {
  4807. if (req.ranges.empty()) {
  4808. ;
  4809. } else if (req.ranges.size() == 1) {
  4810. auto offsets =
  4811. detail::get_range_offset_and_length(req, res.body.size(), 0);
  4812. auto offset = offsets.first;
  4813. auto length = offsets.second;
  4814. auto content_range = detail::make_content_range_header_field(
  4815. offset, length, res.body.size());
  4816. res.set_header("Content-Range", content_range);
  4817. if (offset < res.body.size()) {
  4818. res.body = res.body.substr(offset, length);
  4819. } else {
  4820. res.body.clear();
  4821. res.status = 416;
  4822. }
  4823. } else {
  4824. std::string data;
  4825. if (detail::make_multipart_ranges_data(req, res, boundary, content_type,
  4826. data)) {
  4827. res.body.swap(data);
  4828. } else {
  4829. res.body.clear();
  4830. res.status = 416;
  4831. }
  4832. }
  4833. if (type != detail::EncodingType::None) {
  4834. std::unique_ptr<detail::compressor> compressor;
  4835. std::string content_encoding;
  4836. if (type == detail::EncodingType::Gzip) {
  4837. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4838. compressor = detail::make_unique<detail::gzip_compressor>();
  4839. content_encoding = "gzip";
  4840. #endif
  4841. } else if (type == detail::EncodingType::Brotli) {
  4842. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4843. compressor = detail::make_unique<detail::brotli_compressor>();
  4844. content_encoding = "br";
  4845. #endif
  4846. }
  4847. if (compressor) {
  4848. std::string compressed;
  4849. if (compressor->compress(res.body.data(), res.body.size(), true,
  4850. [&](const char *data, size_t data_len) {
  4851. compressed.append(data, data_len);
  4852. return true;
  4853. })) {
  4854. res.body.swap(compressed);
  4855. res.set_header("Content-Encoding", content_encoding);
  4856. }
  4857. }
  4858. }
  4859. auto length = std::to_string(res.body.size());
  4860. res.set_header("Content-Length", length);
  4861. }
  4862. }
  4863. inline bool Server::dispatch_request_for_content_reader(
  4864. Request &req, Response &res, ContentReader content_reader,
  4865. const HandlersForContentReader &handlers) {
  4866. for (const auto &x : handlers) {
  4867. const auto &pattern = x.first;
  4868. const auto &handler = x.second;
  4869. if (std::regex_match(req.path, req.matches, pattern)) {
  4870. handler(req, res, content_reader);
  4871. return true;
  4872. }
  4873. }
  4874. return false;
  4875. }
  4876. inline bool
  4877. Server::process_request(Stream &strm, bool close_connection,
  4878. bool &connection_closed,
  4879. const std::function<void(Request &)> &setup_request) {
  4880. std::array<char, 2048> buf{};
  4881. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  4882. // Connection has been closed on client
  4883. if (!line_reader.getline()) { return false; }
  4884. Request req;
  4885. Response res;
  4886. res.version = "HTTP/1.1";
  4887. for (const auto &header : default_headers_) {
  4888. if (res.headers.find(header.first) == res.headers.end()) {
  4889. res.headers.insert(header);
  4890. }
  4891. }
  4892. #ifdef _WIN32
  4893. // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL).
  4894. #else
  4895. #ifndef CPPHTTPLIB_USE_POLL
  4896. // Socket file descriptor exceeded FD_SETSIZE...
  4897. if (strm.socket() >= FD_SETSIZE) {
  4898. Headers dummy;
  4899. detail::read_headers(strm, dummy);
  4900. res.status = 500;
  4901. return write_response(strm, close_connection, req, res);
  4902. }
  4903. #endif
  4904. #endif
  4905. // Check if the request URI doesn't exceed the limit
  4906. if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  4907. Headers dummy;
  4908. detail::read_headers(strm, dummy);
  4909. res.status = 414;
  4910. return write_response(strm, close_connection, req, res);
  4911. }
  4912. // Request line and headers
  4913. if (!parse_request_line(line_reader.ptr(), req) ||
  4914. !detail::read_headers(strm, req.headers)) {
  4915. res.status = 400;
  4916. return write_response(strm, close_connection, req, res);
  4917. }
  4918. if (req.get_header_value("Connection") == "close") {
  4919. connection_closed = true;
  4920. }
  4921. if (req.version == "HTTP/1.0" &&
  4922. req.get_header_value("Connection") != "Keep-Alive") {
  4923. connection_closed = true;
  4924. }
  4925. strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);
  4926. req.set_header("REMOTE_ADDR", req.remote_addr);
  4927. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  4928. strm.get_local_ip_and_port(req.local_addr, req.local_port);
  4929. req.set_header("LOCAL_ADDR", req.local_addr);
  4930. req.set_header("LOCAL_PORT", std::to_string(req.local_port));
  4931. if (req.has_header("Range")) {
  4932. const auto &range_header_value = req.get_header_value("Range");
  4933. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  4934. res.status = 416;
  4935. return write_response(strm, close_connection, req, res);
  4936. }
  4937. }
  4938. if (setup_request) { setup_request(req); }
  4939. if (req.get_header_value("Expect") == "100-continue") {
  4940. auto status = 100;
  4941. if (expect_100_continue_handler_) {
  4942. status = expect_100_continue_handler_(req, res);
  4943. }
  4944. switch (status) {
  4945. case 100:
  4946. case 417:
  4947. strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
  4948. detail::status_message(status));
  4949. break;
  4950. default: return write_response(strm, close_connection, req, res);
  4951. }
  4952. }
  4953. // Rounting
  4954. bool routed = false;
  4955. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4956. routed = routing(req, res, strm);
  4957. #else
  4958. try {
  4959. routed = routing(req, res, strm);
  4960. } catch (std::exception &e) {
  4961. if (exception_handler_) {
  4962. auto ep = std::current_exception();
  4963. exception_handler_(req, res, ep);
  4964. routed = true;
  4965. } else {
  4966. res.status = 500;
  4967. std::string val;
  4968. auto s = e.what();
  4969. for (size_t i = 0; s[i]; i++) {
  4970. switch (s[i]) {
  4971. case '\r': val += "\\r"; break;
  4972. case '\n': val += "\\n"; break;
  4973. default: val += s[i]; break;
  4974. }
  4975. }
  4976. res.set_header("EXCEPTION_WHAT", val);
  4977. }
  4978. } catch (...) {
  4979. if (exception_handler_) {
  4980. auto ep = std::current_exception();
  4981. exception_handler_(req, res, ep);
  4982. routed = true;
  4983. } else {
  4984. res.status = 500;
  4985. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  4986. }
  4987. }
  4988. #endif
  4989. if (routed) {
  4990. if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
  4991. return write_response_with_content(strm, close_connection, req, res);
  4992. } else {
  4993. if (res.status == -1) { res.status = 404; }
  4994. return write_response(strm, close_connection, req, res);
  4995. }
  4996. }
  4997. inline bool Server::is_valid() const { return true; }
  4998. inline bool Server::process_and_close_socket(socket_t sock) {
  4999. auto ret = detail::process_server_socket(
  5000. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  5001. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  5002. write_timeout_usec_,
  5003. [this](Stream &strm, bool close_connection, bool &connection_closed) {
  5004. return process_request(strm, close_connection, connection_closed,
  5005. nullptr);
  5006. });
  5007. detail::shutdown_socket(sock);
  5008. detail::close_socket(sock);
  5009. return ret;
  5010. }
  5011. // HTTP client implementation
  5012. inline ClientImpl::ClientImpl(const std::string &host)
  5013. : ClientImpl(host, 80, std::string(), std::string()) {}
  5014. inline ClientImpl::ClientImpl(const std::string &host, int port)
  5015. : ClientImpl(host, port, std::string(), std::string()) {}
  5016. inline ClientImpl::ClientImpl(const std::string &host, int port,
  5017. const std::string &client_cert_path,
  5018. const std::string &client_key_path)
  5019. : host_(host), port_(port),
  5020. host_and_port_(adjust_host_string(host) + ":" + std::to_string(port)),
  5021. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  5022. inline ClientImpl::~ClientImpl() {
  5023. std::lock_guard<std::mutex> guard(socket_mutex_);
  5024. shutdown_socket(socket_);
  5025. close_socket(socket_);
  5026. }
  5027. inline bool ClientImpl::is_valid() const { return true; }
  5028. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  5029. client_cert_path_ = rhs.client_cert_path_;
  5030. client_key_path_ = rhs.client_key_path_;
  5031. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  5032. read_timeout_sec_ = rhs.read_timeout_sec_;
  5033. read_timeout_usec_ = rhs.read_timeout_usec_;
  5034. write_timeout_sec_ = rhs.write_timeout_sec_;
  5035. write_timeout_usec_ = rhs.write_timeout_usec_;
  5036. basic_auth_username_ = rhs.basic_auth_username_;
  5037. basic_auth_password_ = rhs.basic_auth_password_;
  5038. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  5039. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5040. digest_auth_username_ = rhs.digest_auth_username_;
  5041. digest_auth_password_ = rhs.digest_auth_password_;
  5042. #endif
  5043. keep_alive_ = rhs.keep_alive_;
  5044. follow_location_ = rhs.follow_location_;
  5045. url_encode_ = rhs.url_encode_;
  5046. address_family_ = rhs.address_family_;
  5047. tcp_nodelay_ = rhs.tcp_nodelay_;
  5048. socket_options_ = rhs.socket_options_;
  5049. compress_ = rhs.compress_;
  5050. decompress_ = rhs.decompress_;
  5051. interface_ = rhs.interface_;
  5052. proxy_host_ = rhs.proxy_host_;
  5053. proxy_port_ = rhs.proxy_port_;
  5054. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  5055. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  5056. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  5057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5058. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  5059. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  5060. #endif
  5061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5062. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  5063. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  5064. ca_cert_store_ = rhs.ca_cert_store_;
  5065. #endif
  5066. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5067. server_certificate_verification_ = rhs.server_certificate_verification_;
  5068. #endif
  5069. logger_ = rhs.logger_;
  5070. }
  5071. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  5072. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5073. return detail::create_client_socket(
  5074. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  5075. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  5076. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  5077. write_timeout_usec_, interface_, error);
  5078. }
  5079. // Check is custom IP specified for host_
  5080. std::string ip;
  5081. auto it = addr_map_.find(host_);
  5082. if (it != addr_map_.end()) ip = it->second;
  5083. return detail::create_client_socket(
  5084. host_, ip, port_, address_family_, tcp_nodelay_, socket_options_,
  5085. connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_,
  5086. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_,
  5087. error);
  5088. }
  5089. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  5090. Error &error) {
  5091. auto sock = create_client_socket(error);
  5092. if (sock == INVALID_SOCKET) { return false; }
  5093. socket.sock = sock;
  5094. return true;
  5095. }
  5096. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  5097. bool /*shutdown_gracefully*/) {
  5098. // If there are any requests in flight from threads other than us, then it's
  5099. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  5100. assert(socket_requests_in_flight_ == 0 ||
  5101. socket_requests_are_from_thread_ == std::this_thread::get_id());
  5102. }
  5103. inline void ClientImpl::shutdown_socket(Socket &socket) {
  5104. if (socket.sock == INVALID_SOCKET) { return; }
  5105. detail::shutdown_socket(socket.sock);
  5106. }
  5107. inline void ClientImpl::close_socket(Socket &socket) {
  5108. // If there are requests in flight in another thread, usually closing
  5109. // the socket will be fine and they will simply receive an error when
  5110. // using the closed socket, but it is still a bug since rarely the OS
  5111. // may reassign the socket id to be used for a new socket, and then
  5112. // suddenly they will be operating on a live socket that is different
  5113. // than the one they intended!
  5114. assert(socket_requests_in_flight_ == 0 ||
  5115. socket_requests_are_from_thread_ == std::this_thread::get_id());
  5116. // It is also a bug if this happens while SSL is still active
  5117. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5118. assert(socket.ssl == nullptr);
  5119. #endif
  5120. if (socket.sock == INVALID_SOCKET) { return; }
  5121. detail::close_socket(socket.sock);
  5122. socket.sock = INVALID_SOCKET;
  5123. }
  5124. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  5125. Response &res) {
  5126. std::array<char, 2048> buf{};
  5127. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  5128. if (!line_reader.getline()) { return false; }
  5129. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5130. const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  5131. #else
  5132. const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  5133. #endif
  5134. std::cmatch m;
  5135. if (!std::regex_match(line_reader.ptr(), m, re)) {
  5136. return req.method == "CONNECT";
  5137. }
  5138. res.version = std::string(m[1]);
  5139. res.status = std::stoi(std::string(m[2]));
  5140. res.reason = std::string(m[3]);
  5141. // Ignore '100 Continue'
  5142. while (res.status == 100) {
  5143. if (!line_reader.getline()) { return false; } // CRLF
  5144. if (!line_reader.getline()) { return false; } // next response line
  5145. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  5146. res.version = std::string(m[1]);
  5147. res.status = std::stoi(std::string(m[2]));
  5148. res.reason = std::string(m[3]);
  5149. }
  5150. return true;
  5151. }
  5152. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  5153. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  5154. {
  5155. std::lock_guard<std::mutex> guard(socket_mutex_);
  5156. // Set this to false immediately - if it ever gets set to true by the end of
  5157. // the request, we know another thread instructed us to close the socket.
  5158. socket_should_be_closed_when_request_is_done_ = false;
  5159. auto is_alive = false;
  5160. if (socket_.is_open()) {
  5161. is_alive = detail::is_socket_alive(socket_.sock);
  5162. if (!is_alive) {
  5163. // Attempt to avoid sigpipe by shutting down nongracefully if it seems
  5164. // like the other side has already closed the connection Also, there
  5165. // cannot be any requests in flight from other threads since we locked
  5166. // request_mutex_, so safe to close everything immediately
  5167. const bool shutdown_gracefully = false;
  5168. shutdown_ssl(socket_, shutdown_gracefully);
  5169. shutdown_socket(socket_);
  5170. close_socket(socket_);
  5171. }
  5172. }
  5173. if (!is_alive) {
  5174. if (!create_and_connect_socket(socket_, error)) { return false; }
  5175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5176. // TODO: refactoring
  5177. if (is_ssl()) {
  5178. auto &scli = static_cast<SSLClient &>(*this);
  5179. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5180. bool success = false;
  5181. if (!scli.connect_with_proxy(socket_, res, success, error)) {
  5182. return success;
  5183. }
  5184. }
  5185. if (!scli.initialize_ssl(socket_, error)) { return false; }
  5186. }
  5187. #endif
  5188. }
  5189. // Mark the current socket as being in use so that it cannot be closed by
  5190. // anyone else while this request is ongoing, even though we will be
  5191. // releasing the mutex.
  5192. if (socket_requests_in_flight_ > 1) {
  5193. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  5194. }
  5195. socket_requests_in_flight_ += 1;
  5196. socket_requests_are_from_thread_ = std::this_thread::get_id();
  5197. }
  5198. for (const auto &header : default_headers_) {
  5199. if (req.headers.find(header.first) == req.headers.end()) {
  5200. req.headers.insert(header);
  5201. }
  5202. }
  5203. auto close_connection = !keep_alive_;
  5204. auto ret = process_socket(socket_, [&](Stream &strm) {
  5205. return handle_request(strm, req, res, close_connection, error);
  5206. });
  5207. // Briefly lock mutex in order to mark that a request is no longer ongoing
  5208. {
  5209. std::lock_guard<std::mutex> guard(socket_mutex_);
  5210. socket_requests_in_flight_ -= 1;
  5211. if (socket_requests_in_flight_ <= 0) {
  5212. assert(socket_requests_in_flight_ == 0);
  5213. socket_requests_are_from_thread_ = std::thread::id();
  5214. }
  5215. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  5216. !ret) {
  5217. shutdown_ssl(socket_, true);
  5218. shutdown_socket(socket_);
  5219. close_socket(socket_);
  5220. }
  5221. }
  5222. if (!ret) {
  5223. if (error == Error::Success) { error = Error::Unknown; }
  5224. }
  5225. return ret;
  5226. }
  5227. inline Result ClientImpl::send(const Request &req) {
  5228. auto req2 = req;
  5229. return send_(std::move(req2));
  5230. }
  5231. inline Result ClientImpl::send_(Request &&req) {
  5232. auto res = detail::make_unique<Response>();
  5233. auto error = Error::Success;
  5234. auto ret = send(req, *res, error);
  5235. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  5236. }
  5237. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  5238. Response &res, bool close_connection,
  5239. Error &error) {
  5240. if (req.path.empty()) {
  5241. error = Error::Connection;
  5242. return false;
  5243. }
  5244. auto req_save = req;
  5245. bool ret;
  5246. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  5247. auto req2 = req;
  5248. req2.path = "http://" + host_and_port_ + req.path;
  5249. ret = process_request(strm, req2, res, close_connection, error);
  5250. req = req2;
  5251. req.path = req_save.path;
  5252. } else {
  5253. ret = process_request(strm, req, res, close_connection, error);
  5254. }
  5255. if (!ret) { return false; }
  5256. if (300 < res.status && res.status < 400 && follow_location_) {
  5257. req = req_save;
  5258. ret = redirect(req, res, error);
  5259. }
  5260. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5261. if ((res.status == 401 || res.status == 407) &&
  5262. req.authorization_count_ < 5) {
  5263. auto is_proxy = res.status == 407;
  5264. const auto &username =
  5265. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  5266. const auto &password =
  5267. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  5268. if (!username.empty() && !password.empty()) {
  5269. std::map<std::string, std::string> auth;
  5270. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  5271. Request new_req = req;
  5272. new_req.authorization_count_ += 1;
  5273. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  5274. : "Authorization");
  5275. new_req.headers.insert(detail::make_digest_authentication_header(
  5276. req, auth, new_req.authorization_count_, detail::random_string(10),
  5277. username, password, is_proxy));
  5278. Response new_res;
  5279. ret = send(new_req, new_res, error);
  5280. if (ret) { res = new_res; }
  5281. }
  5282. }
  5283. }
  5284. #endif
  5285. return ret;
  5286. }
  5287. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  5288. if (req.redirect_count_ == 0) {
  5289. error = Error::ExceedRedirectCount;
  5290. return false;
  5291. }
  5292. auto location = detail::decode_url(res.get_header_value("location"), true);
  5293. if (location.empty()) { return false; }
  5294. const static std::regex re(
  5295. R"((?:(https?):)?(?://(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
  5296. std::smatch m;
  5297. if (!std::regex_match(location, m, re)) { return false; }
  5298. auto scheme = is_ssl() ? "https" : "http";
  5299. auto next_scheme = m[1].str();
  5300. auto next_host = m[2].str();
  5301. if (next_host.empty()) { next_host = m[3].str(); }
  5302. auto port_str = m[4].str();
  5303. auto next_path = m[5].str();
  5304. auto next_port = port_;
  5305. if (!port_str.empty()) {
  5306. next_port = std::stoi(port_str);
  5307. } else if (!next_scheme.empty()) {
  5308. next_port = next_scheme == "https" ? 443 : 80;
  5309. }
  5310. if (next_scheme.empty()) { next_scheme = scheme; }
  5311. if (next_host.empty()) { next_host = host_; }
  5312. if (next_path.empty()) { next_path = "/"; }
  5313. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  5314. return detail::redirect(*this, req, res, next_path, location, error);
  5315. } else {
  5316. if (next_scheme == "https") {
  5317. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5318. SSLClient cli(next_host.c_str(), next_port);
  5319. cli.copy_settings(*this);
  5320. if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); }
  5321. return detail::redirect(cli, req, res, next_path, location, error);
  5322. #else
  5323. return false;
  5324. #endif
  5325. } else {
  5326. ClientImpl cli(next_host.c_str(), next_port);
  5327. cli.copy_settings(*this);
  5328. return detail::redirect(cli, req, res, next_path, location, error);
  5329. }
  5330. }
  5331. }
  5332. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  5333. const Request &req,
  5334. Error &error) {
  5335. auto is_shutting_down = []() { return false; };
  5336. if (req.is_chunked_content_provider_) {
  5337. // TODO: Brotli suport
  5338. std::unique_ptr<detail::compressor> compressor;
  5339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5340. if (compress_) {
  5341. compressor = detail::make_unique<detail::gzip_compressor>();
  5342. } else
  5343. #endif
  5344. {
  5345. compressor = detail::make_unique<detail::nocompressor>();
  5346. }
  5347. return detail::write_content_chunked(strm, req.content_provider_,
  5348. is_shutting_down, *compressor, error);
  5349. } else {
  5350. return detail::write_content(strm, req.content_provider_, 0,
  5351. req.content_length_, is_shutting_down, error);
  5352. }
  5353. }
  5354. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  5355. bool close_connection, Error &error) {
  5356. // Prepare additional headers
  5357. if (close_connection) {
  5358. if (!req.has_header("Connection")) {
  5359. req.headers.emplace("Connection", "close");
  5360. }
  5361. }
  5362. if (!req.has_header("Host")) {
  5363. if (is_ssl()) {
  5364. if (port_ == 443) {
  5365. req.headers.emplace("Host", host_);
  5366. } else {
  5367. req.headers.emplace("Host", host_and_port_);
  5368. }
  5369. } else {
  5370. if (port_ == 80) {
  5371. req.headers.emplace("Host", host_);
  5372. } else {
  5373. req.headers.emplace("Host", host_and_port_);
  5374. }
  5375. }
  5376. }
  5377. if (!req.has_header("Accept")) { req.headers.emplace("Accept", "*/*"); }
  5378. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  5379. if (!req.has_header("User-Agent")) {
  5380. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  5381. req.headers.emplace("User-Agent", agent);
  5382. }
  5383. #endif
  5384. if (req.body.empty()) {
  5385. if (req.content_provider_) {
  5386. if (!req.is_chunked_content_provider_) {
  5387. if (!req.has_header("Content-Length")) {
  5388. auto length = std::to_string(req.content_length_);
  5389. req.headers.emplace("Content-Length", length);
  5390. }
  5391. }
  5392. } else {
  5393. if (req.method == "POST" || req.method == "PUT" ||
  5394. req.method == "PATCH") {
  5395. req.headers.emplace("Content-Length", "0");
  5396. }
  5397. }
  5398. } else {
  5399. if (!req.has_header("Content-Type")) {
  5400. req.headers.emplace("Content-Type", "text/plain");
  5401. }
  5402. if (!req.has_header("Content-Length")) {
  5403. auto length = std::to_string(req.body.size());
  5404. req.headers.emplace("Content-Length", length);
  5405. }
  5406. }
  5407. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  5408. if (!req.has_header("Authorization")) {
  5409. req.headers.insert(make_basic_authentication_header(
  5410. basic_auth_username_, basic_auth_password_, false));
  5411. }
  5412. }
  5413. if (!proxy_basic_auth_username_.empty() &&
  5414. !proxy_basic_auth_password_.empty()) {
  5415. if (!req.has_header("Proxy-Authorization")) {
  5416. req.headers.insert(make_basic_authentication_header(
  5417. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  5418. }
  5419. }
  5420. if (!bearer_token_auth_token_.empty()) {
  5421. if (!req.has_header("Authorization")) {
  5422. req.headers.insert(make_bearer_token_authentication_header(
  5423. bearer_token_auth_token_, false));
  5424. }
  5425. }
  5426. if (!proxy_bearer_token_auth_token_.empty()) {
  5427. if (!req.has_header("Proxy-Authorization")) {
  5428. req.headers.insert(make_bearer_token_authentication_header(
  5429. proxy_bearer_token_auth_token_, true));
  5430. }
  5431. }
  5432. // Request line and headers
  5433. {
  5434. detail::BufferStream bstrm;
  5435. const auto &path = url_encode_ ? detail::encode_url(req.path) : req.path;
  5436. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  5437. detail::write_headers(bstrm, req.headers);
  5438. // Flush buffer
  5439. auto &data = bstrm.get_buffer();
  5440. if (!detail::write_data(strm, data.data(), data.size())) {
  5441. error = Error::Write;
  5442. return false;
  5443. }
  5444. }
  5445. // Body
  5446. if (req.body.empty()) {
  5447. return write_content_with_provider(strm, req, error);
  5448. }
  5449. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  5450. error = Error::Write;
  5451. return false;
  5452. }
  5453. return true;
  5454. }
  5455. inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
  5456. Request &req, const char *body, size_t content_length,
  5457. ContentProvider content_provider,
  5458. ContentProviderWithoutLength content_provider_without_length,
  5459. const std::string &content_type, Error &error) {
  5460. if (!content_type.empty()) {
  5461. req.headers.emplace("Content-Type", content_type);
  5462. }
  5463. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5464. if (compress_) { req.headers.emplace("Content-Encoding", "gzip"); }
  5465. #endif
  5466. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5467. if (compress_ && !content_provider_without_length) {
  5468. // TODO: Brotli support
  5469. detail::gzip_compressor compressor;
  5470. if (content_provider) {
  5471. auto ok = true;
  5472. size_t offset = 0;
  5473. DataSink data_sink;
  5474. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  5475. if (ok) {
  5476. auto last = offset + data_len == content_length;
  5477. auto ret = compressor.compress(
  5478. data, data_len, last,
  5479. [&](const char *compressed_data, size_t compressed_data_len) {
  5480. req.body.append(compressed_data, compressed_data_len);
  5481. return true;
  5482. });
  5483. if (ret) {
  5484. offset += data_len;
  5485. } else {
  5486. ok = false;
  5487. }
  5488. }
  5489. return ok;
  5490. };
  5491. while (ok && offset < content_length) {
  5492. if (!content_provider(offset, content_length - offset, data_sink)) {
  5493. error = Error::Canceled;
  5494. return nullptr;
  5495. }
  5496. }
  5497. } else {
  5498. if (!compressor.compress(body, content_length, true,
  5499. [&](const char *data, size_t data_len) {
  5500. req.body.append(data, data_len);
  5501. return true;
  5502. })) {
  5503. error = Error::Compression;
  5504. return nullptr;
  5505. }
  5506. }
  5507. } else
  5508. #endif
  5509. {
  5510. if (content_provider) {
  5511. req.content_length_ = content_length;
  5512. req.content_provider_ = std::move(content_provider);
  5513. req.is_chunked_content_provider_ = false;
  5514. } else if (content_provider_without_length) {
  5515. req.content_length_ = 0;
  5516. req.content_provider_ = detail::ContentProviderAdapter(
  5517. std::move(content_provider_without_length));
  5518. req.is_chunked_content_provider_ = true;
  5519. req.headers.emplace("Transfer-Encoding", "chunked");
  5520. } else {
  5521. req.body.assign(body, content_length);
  5522. ;
  5523. }
  5524. }
  5525. auto res = detail::make_unique<Response>();
  5526. return send(req, *res, error) ? std::move(res) : nullptr;
  5527. }
  5528. inline Result ClientImpl::send_with_content_provider(
  5529. const std::string &method, const std::string &path, const Headers &headers,
  5530. const char *body, size_t content_length, ContentProvider content_provider,
  5531. ContentProviderWithoutLength content_provider_without_length,
  5532. const std::string &content_type) {
  5533. Request req;
  5534. req.method = method;
  5535. req.headers = headers;
  5536. req.path = path;
  5537. auto error = Error::Success;
  5538. auto res = send_with_content_provider(
  5539. req, body, content_length, std::move(content_provider),
  5540. std::move(content_provider_without_length), content_type, error);
  5541. return Result{std::move(res), error, std::move(req.headers)};
  5542. }
  5543. inline std::string
  5544. ClientImpl::adjust_host_string(const std::string &host) const {
  5545. if (host.find(':') != std::string::npos) { return "[" + host + "]"; }
  5546. return host;
  5547. }
  5548. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  5549. Response &res, bool close_connection,
  5550. Error &error) {
  5551. // Send request
  5552. if (!write_request(strm, req, close_connection, error)) { return false; }
  5553. // Receive response and headers
  5554. if (!read_response_line(strm, req, res) ||
  5555. !detail::read_headers(strm, res.headers)) {
  5556. error = Error::Read;
  5557. return false;
  5558. }
  5559. // Body
  5560. if ((res.status != 204) && req.method != "HEAD" && req.method != "CONNECT") {
  5561. auto redirect = 300 < res.status && res.status < 400 && follow_location_;
  5562. if (req.response_handler && !redirect) {
  5563. if (!req.response_handler(res)) {
  5564. error = Error::Canceled;
  5565. return false;
  5566. }
  5567. }
  5568. auto out =
  5569. req.content_receiver
  5570. ? static_cast<ContentReceiverWithProgress>(
  5571. [&](const char *buf, size_t n, uint64_t off, uint64_t len) {
  5572. if (redirect) { return true; }
  5573. auto ret = req.content_receiver(buf, n, off, len);
  5574. if (!ret) { error = Error::Canceled; }
  5575. return ret;
  5576. })
  5577. : static_cast<ContentReceiverWithProgress>(
  5578. [&](const char *buf, size_t n, uint64_t /*off*/,
  5579. uint64_t /*len*/) {
  5580. if (res.body.size() + n > res.body.max_size()) {
  5581. return false;
  5582. }
  5583. res.body.append(buf, n);
  5584. return true;
  5585. });
  5586. auto progress = [&](uint64_t current, uint64_t total) {
  5587. if (!req.progress || redirect) { return true; }
  5588. auto ret = req.progress(current, total);
  5589. if (!ret) { error = Error::Canceled; }
  5590. return ret;
  5591. };
  5592. int dummy_status;
  5593. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  5594. dummy_status, std::move(progress), std::move(out),
  5595. decompress_)) {
  5596. if (error != Error::Canceled) { error = Error::Read; }
  5597. return false;
  5598. }
  5599. }
  5600. if (res.get_header_value("Connection") == "close" ||
  5601. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  5602. // TODO this requires a not-entirely-obvious chain of calls to be correct
  5603. // for this to be safe. Maybe a code refactor (such as moving this out to
  5604. // the send function and getting rid of the recursiveness of the mutex)
  5605. // could make this more obvious.
  5606. // This is safe to call because process_request is only called by
  5607. // handle_request which is only called by send, which locks the request
  5608. // mutex during the process. It would be a bug to call it from a different
  5609. // thread since it's a thread-safety issue to do these things to the socket
  5610. // if another thread is using the socket.
  5611. std::lock_guard<std::mutex> guard(socket_mutex_);
  5612. shutdown_ssl(socket_, true);
  5613. shutdown_socket(socket_);
  5614. close_socket(socket_);
  5615. }
  5616. // Log
  5617. if (logger_) { logger_(req, res); }
  5618. return true;
  5619. }
  5620. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  5621. const std::string &boundary, const MultipartFormDataItems &items,
  5622. const MultipartFormDataProviderItems &provider_items) {
  5623. size_t cur_item = 0, cur_start = 0;
  5624. // cur_item and cur_start are copied to within the std::function and maintain
  5625. // state between successive calls
  5626. return [&, cur_item, cur_start](size_t offset,
  5627. DataSink &sink) mutable -> bool {
  5628. if (!offset && items.size()) {
  5629. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  5630. return true;
  5631. } else if (cur_item < provider_items.size()) {
  5632. if (!cur_start) {
  5633. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  5634. provider_items[cur_item], boundary);
  5635. offset += begin.size();
  5636. cur_start = offset;
  5637. sink.os << begin;
  5638. }
  5639. DataSink cur_sink;
  5640. bool has_data = true;
  5641. cur_sink.write = sink.write;
  5642. cur_sink.done = [&]() { has_data = false; };
  5643. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink))
  5644. return false;
  5645. if (!has_data) {
  5646. sink.os << detail::serialize_multipart_formdata_item_end();
  5647. cur_item++;
  5648. cur_start = 0;
  5649. }
  5650. return true;
  5651. } else {
  5652. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  5653. sink.done();
  5654. return true;
  5655. }
  5656. };
  5657. }
  5658. inline bool
  5659. ClientImpl::process_socket(const Socket &socket,
  5660. std::function<bool(Stream &strm)> callback) {
  5661. return detail::process_client_socket(
  5662. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  5663. write_timeout_usec_, std::move(callback));
  5664. }
  5665. inline bool ClientImpl::is_ssl() const { return false; }
  5666. inline Result ClientImpl::Get(const std::string &path) {
  5667. return Get(path, Headers(), Progress());
  5668. }
  5669. inline Result ClientImpl::Get(const std::string &path, Progress progress) {
  5670. return Get(path, Headers(), std::move(progress));
  5671. }
  5672. inline Result ClientImpl::Get(const std::string &path, const Headers &headers) {
  5673. return Get(path, headers, Progress());
  5674. }
  5675. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5676. Progress progress) {
  5677. Request req;
  5678. req.method = "GET";
  5679. req.path = path;
  5680. req.headers = headers;
  5681. req.progress = std::move(progress);
  5682. return send_(std::move(req));
  5683. }
  5684. inline Result ClientImpl::Get(const std::string &path,
  5685. ContentReceiver content_receiver) {
  5686. return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr);
  5687. }
  5688. inline Result ClientImpl::Get(const std::string &path,
  5689. ContentReceiver content_receiver,
  5690. Progress progress) {
  5691. return Get(path, Headers(), nullptr, std::move(content_receiver),
  5692. std::move(progress));
  5693. }
  5694. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5695. ContentReceiver content_receiver) {
  5696. return Get(path, headers, nullptr, std::move(content_receiver), nullptr);
  5697. }
  5698. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5699. ContentReceiver content_receiver,
  5700. Progress progress) {
  5701. return Get(path, headers, nullptr, std::move(content_receiver),
  5702. std::move(progress));
  5703. }
  5704. inline Result ClientImpl::Get(const std::string &path,
  5705. ResponseHandler response_handler,
  5706. ContentReceiver content_receiver) {
  5707. return Get(path, Headers(), std::move(response_handler),
  5708. std::move(content_receiver), nullptr);
  5709. }
  5710. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5711. ResponseHandler response_handler,
  5712. ContentReceiver content_receiver) {
  5713. return Get(path, headers, std::move(response_handler),
  5714. std::move(content_receiver), nullptr);
  5715. }
  5716. inline Result ClientImpl::Get(const std::string &path,
  5717. ResponseHandler response_handler,
  5718. ContentReceiver content_receiver,
  5719. Progress progress) {
  5720. return Get(path, Headers(), std::move(response_handler),
  5721. std::move(content_receiver), std::move(progress));
  5722. }
  5723. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5724. ResponseHandler response_handler,
  5725. ContentReceiver content_receiver,
  5726. Progress progress) {
  5727. Request req;
  5728. req.method = "GET";
  5729. req.path = path;
  5730. req.headers = headers;
  5731. req.response_handler = std::move(response_handler);
  5732. req.content_receiver =
  5733. [content_receiver](const char *data, size_t data_length,
  5734. uint64_t /*offset*/, uint64_t /*total_length*/) {
  5735. return content_receiver(data, data_length);
  5736. };
  5737. req.progress = std::move(progress);
  5738. return send_(std::move(req));
  5739. }
  5740. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  5741. const Headers &headers, Progress progress) {
  5742. if (params.empty()) { return Get(path, headers); }
  5743. std::string path_with_query = append_query_params(path, params);
  5744. return Get(path_with_query.c_str(), headers, progress);
  5745. }
  5746. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  5747. const Headers &headers,
  5748. ContentReceiver content_receiver,
  5749. Progress progress) {
  5750. return Get(path, params, headers, nullptr, content_receiver, progress);
  5751. }
  5752. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  5753. const Headers &headers,
  5754. ResponseHandler response_handler,
  5755. ContentReceiver content_receiver,
  5756. Progress progress) {
  5757. if (params.empty()) {
  5758. return Get(path, headers, response_handler, content_receiver, progress);
  5759. }
  5760. std::string path_with_query = append_query_params(path, params);
  5761. return Get(path_with_query.c_str(), headers, response_handler,
  5762. content_receiver, progress);
  5763. }
  5764. inline Result ClientImpl::Head(const std::string &path) {
  5765. return Head(path, Headers());
  5766. }
  5767. inline Result ClientImpl::Head(const std::string &path,
  5768. const Headers &headers) {
  5769. Request req;
  5770. req.method = "HEAD";
  5771. req.headers = headers;
  5772. req.path = path;
  5773. return send_(std::move(req));
  5774. }
  5775. inline Result ClientImpl::Post(const std::string &path) {
  5776. return Post(path, std::string(), std::string());
  5777. }
  5778. inline Result ClientImpl::Post(const std::string &path,
  5779. const Headers &headers) {
  5780. return Post(path, headers, nullptr, 0, std::string());
  5781. }
  5782. inline Result ClientImpl::Post(const std::string &path, const char *body,
  5783. size_t content_length,
  5784. const std::string &content_type) {
  5785. return Post(path, Headers(), body, content_length, content_type);
  5786. }
  5787. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  5788. const char *body, size_t content_length,
  5789. const std::string &content_type) {
  5790. return send_with_content_provider("POST", path, headers, body, content_length,
  5791. nullptr, nullptr, content_type);
  5792. }
  5793. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  5794. const std::string &content_type) {
  5795. return Post(path, Headers(), body, content_type);
  5796. }
  5797. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  5798. const std::string &body,
  5799. const std::string &content_type) {
  5800. return send_with_content_provider("POST", path, headers, body.data(),
  5801. body.size(), nullptr, nullptr,
  5802. content_type);
  5803. }
  5804. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  5805. return Post(path, Headers(), params);
  5806. }
  5807. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  5808. ContentProvider content_provider,
  5809. const std::string &content_type) {
  5810. return Post(path, Headers(), content_length, std::move(content_provider),
  5811. content_type);
  5812. }
  5813. inline Result ClientImpl::Post(const std::string &path,
  5814. ContentProviderWithoutLength content_provider,
  5815. const std::string &content_type) {
  5816. return Post(path, Headers(), std::move(content_provider), content_type);
  5817. }
  5818. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  5819. size_t content_length,
  5820. ContentProvider content_provider,
  5821. const std::string &content_type) {
  5822. return send_with_content_provider("POST", path, headers, nullptr,
  5823. content_length, std::move(content_provider),
  5824. nullptr, content_type);
  5825. }
  5826. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  5827. ContentProviderWithoutLength content_provider,
  5828. const std::string &content_type) {
  5829. return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
  5830. std::move(content_provider), content_type);
  5831. }
  5832. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  5833. const Params &params) {
  5834. auto query = detail::params_to_query_str(params);
  5835. return Post(path, headers, query, "application/x-www-form-urlencoded");
  5836. }
  5837. inline Result ClientImpl::Post(const std::string &path,
  5838. const MultipartFormDataItems &items) {
  5839. return Post(path, Headers(), items);
  5840. }
  5841. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  5842. const MultipartFormDataItems &items) {
  5843. const auto &boundary = detail::make_multipart_data_boundary();
  5844. const auto &content_type =
  5845. detail::serialize_multipart_formdata_get_content_type(boundary);
  5846. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  5847. return Post(path, headers, body, content_type.c_str());
  5848. }
  5849. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  5850. const MultipartFormDataItems &items,
  5851. const std::string &boundary) {
  5852. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  5853. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  5854. }
  5855. const auto &content_type =
  5856. detail::serialize_multipart_formdata_get_content_type(boundary);
  5857. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  5858. return Post(path, headers, body, content_type.c_str());
  5859. }
  5860. inline Result
  5861. ClientImpl::Post(const std::string &path, const Headers &headers,
  5862. const MultipartFormDataItems &items,
  5863. const MultipartFormDataProviderItems &provider_items) {
  5864. const auto &boundary = detail::make_multipart_data_boundary();
  5865. const auto &content_type =
  5866. detail::serialize_multipart_formdata_get_content_type(boundary);
  5867. return send_with_content_provider(
  5868. "POST", path, headers, nullptr, 0, nullptr,
  5869. get_multipart_content_provider(boundary, items, provider_items),
  5870. content_type);
  5871. }
  5872. inline Result ClientImpl::Put(const std::string &path) {
  5873. return Put(path, std::string(), std::string());
  5874. }
  5875. inline Result ClientImpl::Put(const std::string &path, const char *body,
  5876. size_t content_length,
  5877. const std::string &content_type) {
  5878. return Put(path, Headers(), body, content_length, content_type);
  5879. }
  5880. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  5881. const char *body, size_t content_length,
  5882. const std::string &content_type) {
  5883. return send_with_content_provider("PUT", path, headers, body, content_length,
  5884. nullptr, nullptr, content_type);
  5885. }
  5886. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  5887. const std::string &content_type) {
  5888. return Put(path, Headers(), body, content_type);
  5889. }
  5890. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  5891. const std::string &body,
  5892. const std::string &content_type) {
  5893. return send_with_content_provider("PUT", path, headers, body.data(),
  5894. body.size(), nullptr, nullptr,
  5895. content_type);
  5896. }
  5897. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  5898. ContentProvider content_provider,
  5899. const std::string &content_type) {
  5900. return Put(path, Headers(), content_length, std::move(content_provider),
  5901. content_type);
  5902. }
  5903. inline Result ClientImpl::Put(const std::string &path,
  5904. ContentProviderWithoutLength content_provider,
  5905. const std::string &content_type) {
  5906. return Put(path, Headers(), std::move(content_provider), content_type);
  5907. }
  5908. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  5909. size_t content_length,
  5910. ContentProvider content_provider,
  5911. const std::string &content_type) {
  5912. return send_with_content_provider("PUT", path, headers, nullptr,
  5913. content_length, std::move(content_provider),
  5914. nullptr, content_type);
  5915. }
  5916. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  5917. ContentProviderWithoutLength content_provider,
  5918. const std::string &content_type) {
  5919. return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
  5920. std::move(content_provider), content_type);
  5921. }
  5922. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  5923. return Put(path, Headers(), params);
  5924. }
  5925. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  5926. const Params &params) {
  5927. auto query = detail::params_to_query_str(params);
  5928. return Put(path, headers, query, "application/x-www-form-urlencoded");
  5929. }
  5930. inline Result ClientImpl::Put(const std::string &path,
  5931. const MultipartFormDataItems &items) {
  5932. return Put(path, Headers(), items);
  5933. }
  5934. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  5935. const MultipartFormDataItems &items) {
  5936. const auto &boundary = detail::make_multipart_data_boundary();
  5937. const auto &content_type =
  5938. detail::serialize_multipart_formdata_get_content_type(boundary);
  5939. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  5940. return Put(path, headers, body, content_type);
  5941. }
  5942. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  5943. const MultipartFormDataItems &items,
  5944. const std::string &boundary) {
  5945. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  5946. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  5947. }
  5948. const auto &content_type =
  5949. detail::serialize_multipart_formdata_get_content_type(boundary);
  5950. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  5951. return Put(path, headers, body, content_type);
  5952. }
  5953. inline Result
  5954. ClientImpl::Put(const std::string &path, const Headers &headers,
  5955. const MultipartFormDataItems &items,
  5956. const MultipartFormDataProviderItems &provider_items) {
  5957. const auto &boundary = detail::make_multipart_data_boundary();
  5958. const auto &content_type =
  5959. detail::serialize_multipart_formdata_get_content_type(boundary);
  5960. return send_with_content_provider(
  5961. "PUT", path, headers, nullptr, 0, nullptr,
  5962. get_multipart_content_provider(boundary, items, provider_items),
  5963. content_type);
  5964. }
  5965. inline Result ClientImpl::Patch(const std::string &path) {
  5966. return Patch(path, std::string(), std::string());
  5967. }
  5968. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  5969. size_t content_length,
  5970. const std::string &content_type) {
  5971. return Patch(path, Headers(), body, content_length, content_type);
  5972. }
  5973. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  5974. const char *body, size_t content_length,
  5975. const std::string &content_type) {
  5976. return send_with_content_provider("PATCH", path, headers, body,
  5977. content_length, nullptr, nullptr,
  5978. content_type);
  5979. }
  5980. inline Result ClientImpl::Patch(const std::string &path,
  5981. const std::string &body,
  5982. const std::string &content_type) {
  5983. return Patch(path, Headers(), body, content_type);
  5984. }
  5985. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  5986. const std::string &body,
  5987. const std::string &content_type) {
  5988. return send_with_content_provider("PATCH", path, headers, body.data(),
  5989. body.size(), nullptr, nullptr,
  5990. content_type);
  5991. }
  5992. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  5993. ContentProvider content_provider,
  5994. const std::string &content_type) {
  5995. return Patch(path, Headers(), content_length, std::move(content_provider),
  5996. content_type);
  5997. }
  5998. inline Result ClientImpl::Patch(const std::string &path,
  5999. ContentProviderWithoutLength content_provider,
  6000. const std::string &content_type) {
  6001. return Patch(path, Headers(), std::move(content_provider), content_type);
  6002. }
  6003. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6004. size_t content_length,
  6005. ContentProvider content_provider,
  6006. const std::string &content_type) {
  6007. return send_with_content_provider("PATCH", path, headers, nullptr,
  6008. content_length, std::move(content_provider),
  6009. nullptr, content_type);
  6010. }
  6011. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6012. ContentProviderWithoutLength content_provider,
  6013. const std::string &content_type) {
  6014. return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
  6015. std::move(content_provider), content_type);
  6016. }
  6017. inline Result ClientImpl::Delete(const std::string &path) {
  6018. return Delete(path, Headers(), std::string(), std::string());
  6019. }
  6020. inline Result ClientImpl::Delete(const std::string &path,
  6021. const Headers &headers) {
  6022. return Delete(path, headers, std::string(), std::string());
  6023. }
  6024. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  6025. size_t content_length,
  6026. const std::string &content_type) {
  6027. return Delete(path, Headers(), body, content_length, content_type);
  6028. }
  6029. inline Result ClientImpl::Delete(const std::string &path,
  6030. const Headers &headers, const char *body,
  6031. size_t content_length,
  6032. const std::string &content_type) {
  6033. Request req;
  6034. req.method = "DELETE";
  6035. req.headers = headers;
  6036. req.path = path;
  6037. if (!content_type.empty()) {
  6038. req.headers.emplace("Content-Type", content_type);
  6039. }
  6040. req.body.assign(body, content_length);
  6041. return send_(std::move(req));
  6042. }
  6043. inline Result ClientImpl::Delete(const std::string &path,
  6044. const std::string &body,
  6045. const std::string &content_type) {
  6046. return Delete(path, Headers(), body.data(), body.size(), content_type);
  6047. }
  6048. inline Result ClientImpl::Delete(const std::string &path,
  6049. const Headers &headers,
  6050. const std::string &body,
  6051. const std::string &content_type) {
  6052. return Delete(path, headers, body.data(), body.size(), content_type);
  6053. }
  6054. inline Result ClientImpl::Options(const std::string &path) {
  6055. return Options(path, Headers());
  6056. }
  6057. inline Result ClientImpl::Options(const std::string &path,
  6058. const Headers &headers) {
  6059. Request req;
  6060. req.method = "OPTIONS";
  6061. req.headers = headers;
  6062. req.path = path;
  6063. return send_(std::move(req));
  6064. }
  6065. inline size_t ClientImpl::is_socket_open() const {
  6066. std::lock_guard<std::mutex> guard(socket_mutex_);
  6067. return socket_.is_open();
  6068. }
  6069. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  6070. inline void ClientImpl::stop() {
  6071. std::lock_guard<std::mutex> guard(socket_mutex_);
  6072. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  6073. // do is to shutdown_socket, so that threads using this socket suddenly
  6074. // discover they can't read/write any more and error out. Everything else
  6075. // (closing the socket, shutting ssl down) is unsafe because these actions are
  6076. // not thread-safe.
  6077. if (socket_requests_in_flight_ > 0) {
  6078. shutdown_socket(socket_);
  6079. // Aside from that, we set a flag for the socket to be closed when we're
  6080. // done.
  6081. socket_should_be_closed_when_request_is_done_ = true;
  6082. return;
  6083. }
  6084. // Otherwise, sitll holding the mutex, we can shut everything down ourselves
  6085. shutdown_ssl(socket_, true);
  6086. shutdown_socket(socket_);
  6087. close_socket(socket_);
  6088. }
  6089. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  6090. connection_timeout_sec_ = sec;
  6091. connection_timeout_usec_ = usec;
  6092. }
  6093. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  6094. read_timeout_sec_ = sec;
  6095. read_timeout_usec_ = usec;
  6096. }
  6097. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  6098. write_timeout_sec_ = sec;
  6099. write_timeout_usec_ = usec;
  6100. }
  6101. inline void ClientImpl::set_basic_auth(const std::string &username,
  6102. const std::string &password) {
  6103. basic_auth_username_ = username;
  6104. basic_auth_password_ = password;
  6105. }
  6106. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  6107. bearer_token_auth_token_ = token;
  6108. }
  6109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6110. inline void ClientImpl::set_digest_auth(const std::string &username,
  6111. const std::string &password) {
  6112. digest_auth_username_ = username;
  6113. digest_auth_password_ = password;
  6114. }
  6115. #endif
  6116. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  6117. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  6118. inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; }
  6119. inline void
  6120. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  6121. addr_map_ = std::move(addr_map);
  6122. }
  6123. inline void ClientImpl::set_default_headers(Headers headers) {
  6124. default_headers_ = std::move(headers);
  6125. }
  6126. inline void ClientImpl::set_address_family(int family) {
  6127. address_family_ = family;
  6128. }
  6129. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  6130. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  6131. socket_options_ = std::move(socket_options);
  6132. }
  6133. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  6134. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  6135. inline void ClientImpl::set_interface(const std::string &intf) {
  6136. interface_ = intf;
  6137. }
  6138. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  6139. proxy_host_ = host;
  6140. proxy_port_ = port;
  6141. }
  6142. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  6143. const std::string &password) {
  6144. proxy_basic_auth_username_ = username;
  6145. proxy_basic_auth_password_ = password;
  6146. }
  6147. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  6148. proxy_bearer_token_auth_token_ = token;
  6149. }
  6150. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6151. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  6152. const std::string &password) {
  6153. proxy_digest_auth_username_ = username;
  6154. proxy_digest_auth_password_ = password;
  6155. }
  6156. #endif
  6157. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6158. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  6159. const std::string &ca_cert_dir_path) {
  6160. ca_cert_file_path_ = ca_cert_file_path;
  6161. ca_cert_dir_path_ = ca_cert_dir_path;
  6162. }
  6163. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  6164. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  6165. ca_cert_store_ = ca_cert_store;
  6166. }
  6167. }
  6168. #endif
  6169. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6170. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  6171. server_certificate_verification_ = enabled;
  6172. }
  6173. #endif
  6174. inline void ClientImpl::set_logger(Logger logger) {
  6175. logger_ = std::move(logger);
  6176. }
  6177. /*
  6178. * SSL Implementation
  6179. */
  6180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6181. namespace detail {
  6182. template <typename U, typename V>
  6183. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  6184. U SSL_connect_or_accept, V setup) {
  6185. SSL *ssl = nullptr;
  6186. {
  6187. std::lock_guard<std::mutex> guard(ctx_mutex);
  6188. ssl = SSL_new(ctx);
  6189. }
  6190. if (ssl) {
  6191. set_nonblocking(sock, true);
  6192. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  6193. BIO_set_nbio(bio, 1);
  6194. SSL_set_bio(ssl, bio, bio);
  6195. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  6196. SSL_shutdown(ssl);
  6197. {
  6198. std::lock_guard<std::mutex> guard(ctx_mutex);
  6199. SSL_free(ssl);
  6200. }
  6201. set_nonblocking(sock, false);
  6202. return nullptr;
  6203. }
  6204. BIO_set_nbio(bio, 0);
  6205. set_nonblocking(sock, false);
  6206. }
  6207. return ssl;
  6208. }
  6209. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,
  6210. bool shutdown_gracefully) {
  6211. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  6212. // the remote has closed the network connection
  6213. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  6214. // best-efforts.
  6215. if (shutdown_gracefully) { SSL_shutdown(ssl); }
  6216. std::lock_guard<std::mutex> guard(ctx_mutex);
  6217. SSL_free(ssl);
  6218. }
  6219. template <typename U>
  6220. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  6221. U ssl_connect_or_accept,
  6222. time_t timeout_sec,
  6223. time_t timeout_usec) {
  6224. int res = 0;
  6225. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  6226. auto err = SSL_get_error(ssl, res);
  6227. switch (err) {
  6228. case SSL_ERROR_WANT_READ:
  6229. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  6230. break;
  6231. case SSL_ERROR_WANT_WRITE:
  6232. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  6233. break;
  6234. default: break;
  6235. }
  6236. return false;
  6237. }
  6238. return true;
  6239. }
  6240. template <typename T>
  6241. inline bool process_server_socket_ssl(
  6242. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  6243. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  6244. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  6245. time_t write_timeout_usec, T callback) {
  6246. return process_server_socket_core(
  6247. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  6248. [&](bool close_connection, bool &connection_closed) {
  6249. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  6250. write_timeout_sec, write_timeout_usec);
  6251. return callback(strm, close_connection, connection_closed);
  6252. });
  6253. }
  6254. template <typename T>
  6255. inline bool
  6256. process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec,
  6257. time_t read_timeout_usec, time_t write_timeout_sec,
  6258. time_t write_timeout_usec, T callback) {
  6259. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  6260. write_timeout_sec, write_timeout_usec);
  6261. return callback(strm);
  6262. }
  6263. class SSLInit {
  6264. public:
  6265. SSLInit() {
  6266. OPENSSL_init_ssl(
  6267. OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  6268. }
  6269. };
  6270. // SSL socket stream implementation
  6271. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
  6272. time_t read_timeout_sec,
  6273. time_t read_timeout_usec,
  6274. time_t write_timeout_sec,
  6275. time_t write_timeout_usec)
  6276. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  6277. read_timeout_usec_(read_timeout_usec),
  6278. write_timeout_sec_(write_timeout_sec),
  6279. write_timeout_usec_(write_timeout_usec) {
  6280. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  6281. }
  6282. inline SSLSocketStream::~SSLSocketStream() {}
  6283. inline bool SSLSocketStream::is_readable() const {
  6284. return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  6285. }
  6286. inline bool SSLSocketStream::is_writable() const {
  6287. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  6288. is_socket_alive(sock_);
  6289. }
  6290. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  6291. if (SSL_pending(ssl_) > 0) {
  6292. return SSL_read(ssl_, ptr, static_cast<int>(size));
  6293. } else if (is_readable()) {
  6294. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  6295. if (ret < 0) {
  6296. auto err = SSL_get_error(ssl_, ret);
  6297. int n = 1000;
  6298. #ifdef _WIN32
  6299. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  6300. (err == SSL_ERROR_SYSCALL &&
  6301. WSAGetLastError() == WSAETIMEDOUT))) {
  6302. #else
  6303. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  6304. #endif
  6305. if (SSL_pending(ssl_) > 0) {
  6306. return SSL_read(ssl_, ptr, static_cast<int>(size));
  6307. } else if (is_readable()) {
  6308. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  6309. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  6310. if (ret >= 0) { return ret; }
  6311. err = SSL_get_error(ssl_, ret);
  6312. } else {
  6313. return -1;
  6314. }
  6315. }
  6316. }
  6317. return ret;
  6318. }
  6319. return -1;
  6320. }
  6321. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  6322. if (is_writable()) {
  6323. auto handle_size = static_cast<int>(
  6324. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  6325. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  6326. if (ret < 0) {
  6327. auto err = SSL_get_error(ssl_, ret);
  6328. int n = 1000;
  6329. #ifdef _WIN32
  6330. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  6331. (err == SSL_ERROR_SYSCALL &&
  6332. WSAGetLastError() == WSAETIMEDOUT))) {
  6333. #else
  6334. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  6335. #endif
  6336. if (is_writable()) {
  6337. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  6338. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  6339. if (ret >= 0) { return ret; }
  6340. err = SSL_get_error(ssl_, ret);
  6341. } else {
  6342. return -1;
  6343. }
  6344. }
  6345. }
  6346. return ret;
  6347. }
  6348. return -1;
  6349. }
  6350. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  6351. int &port) const {
  6352. detail::get_remote_ip_and_port(sock_, ip, port);
  6353. }
  6354. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  6355. int &port) const {
  6356. detail::get_local_ip_and_port(sock_, ip, port);
  6357. }
  6358. inline socket_t SSLSocketStream::socket() const { return sock_; }
  6359. static SSLInit sslinit_;
  6360. } // namespace detail
  6361. // SSL HTTP server implementation
  6362. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  6363. const char *client_ca_cert_file_path,
  6364. const char *client_ca_cert_dir_path,
  6365. const char *private_key_password) {
  6366. ctx_ = SSL_CTX_new(TLS_server_method());
  6367. if (ctx_) {
  6368. SSL_CTX_set_options(ctx_,
  6369. SSL_OP_NO_COMPRESSION |
  6370. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6371. SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION);
  6372. // add default password callback before opening encrypted private key
  6373. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  6374. SSL_CTX_set_default_passwd_cb_userdata(ctx_,
  6375. (char *)private_key_password);
  6376. }
  6377. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  6378. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  6379. 1) {
  6380. SSL_CTX_free(ctx_);
  6381. ctx_ = nullptr;
  6382. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  6383. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  6384. client_ca_cert_dir_path);
  6385. SSL_CTX_set_verify(
  6386. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  6387. }
  6388. }
  6389. }
  6390. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  6391. X509_STORE *client_ca_cert_store) {
  6392. ctx_ = SSL_CTX_new(TLS_server_method());
  6393. if (ctx_) {
  6394. SSL_CTX_set_options(ctx_,
  6395. SSL_OP_NO_COMPRESSION |
  6396. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6397. SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION);
  6398. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  6399. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  6400. SSL_CTX_free(ctx_);
  6401. ctx_ = nullptr;
  6402. } else if (client_ca_cert_store) {
  6403. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  6404. SSL_CTX_set_verify(
  6405. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  6406. }
  6407. }
  6408. }
  6409. inline SSLServer::SSLServer(
  6410. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  6411. ctx_ = SSL_CTX_new(TLS_method());
  6412. if (ctx_) {
  6413. if (!setup_ssl_ctx_callback(*ctx_)) {
  6414. SSL_CTX_free(ctx_);
  6415. ctx_ = nullptr;
  6416. }
  6417. }
  6418. }
  6419. inline SSLServer::~SSLServer() {
  6420. if (ctx_) { SSL_CTX_free(ctx_); }
  6421. }
  6422. inline bool SSLServer::is_valid() const { return ctx_; }
  6423. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  6424. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  6425. auto ssl = detail::ssl_new(
  6426. sock, ctx_, ctx_mutex_,
  6427. [&](SSL *ssl2) {
  6428. return detail::ssl_connect_or_accept_nonblocking(
  6429. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_);
  6430. },
  6431. [](SSL * /*ssl2*/) { return true; });
  6432. bool ret = false;
  6433. if (ssl) {
  6434. ret = detail::process_server_socket_ssl(
  6435. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  6436. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6437. write_timeout_usec_,
  6438. [this, ssl](Stream &strm, bool close_connection,
  6439. bool &connection_closed) {
  6440. return process_request(strm, close_connection, connection_closed,
  6441. [&](Request &req) { req.ssl = ssl; });
  6442. });
  6443. // Shutdown gracefully if the result seemed successful, non-gracefully if
  6444. // the connection appeared to be closed.
  6445. const bool shutdown_gracefully = ret;
  6446. detail::ssl_delete(ctx_mutex_, ssl, shutdown_gracefully);
  6447. }
  6448. detail::shutdown_socket(sock);
  6449. detail::close_socket(sock);
  6450. return ret;
  6451. }
  6452. // SSL HTTP client implementation
  6453. inline SSLClient::SSLClient(const std::string &host)
  6454. : SSLClient(host, 443, std::string(), std::string()) {}
  6455. inline SSLClient::SSLClient(const std::string &host, int port)
  6456. : SSLClient(host, port, std::string(), std::string()) {}
  6457. inline SSLClient::SSLClient(const std::string &host, int port,
  6458. const std::string &client_cert_path,
  6459. const std::string &client_key_path)
  6460. : ClientImpl(host, port, client_cert_path, client_key_path) {
  6461. ctx_ = SSL_CTX_new(TLS_client_method());
  6462. detail::split(&host_[0], &host_[host_.size()], '.',
  6463. [&](const char *b, const char *e) {
  6464. host_components_.emplace_back(std::string(b, e));
  6465. });
  6466. if (!client_cert_path.empty() && !client_key_path.empty()) {
  6467. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  6468. SSL_FILETYPE_PEM) != 1 ||
  6469. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  6470. SSL_FILETYPE_PEM) != 1) {
  6471. SSL_CTX_free(ctx_);
  6472. ctx_ = nullptr;
  6473. }
  6474. }
  6475. }
  6476. inline SSLClient::SSLClient(const std::string &host, int port,
  6477. X509 *client_cert, EVP_PKEY *client_key)
  6478. : ClientImpl(host, port) {
  6479. ctx_ = SSL_CTX_new(TLS_client_method());
  6480. detail::split(&host_[0], &host_[host_.size()], '.',
  6481. [&](const char *b, const char *e) {
  6482. host_components_.emplace_back(std::string(b, e));
  6483. });
  6484. if (client_cert != nullptr && client_key != nullptr) {
  6485. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  6486. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  6487. SSL_CTX_free(ctx_);
  6488. ctx_ = nullptr;
  6489. }
  6490. }
  6491. }
  6492. inline SSLClient::~SSLClient() {
  6493. if (ctx_) { SSL_CTX_free(ctx_); }
  6494. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  6495. // base function rather than the derived function once we get to the
  6496. // base class destructor, and won't free the SSL (causing a leak).
  6497. shutdown_ssl_impl(socket_, true);
  6498. }
  6499. inline bool SSLClient::is_valid() const { return ctx_; }
  6500. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  6501. if (ca_cert_store) {
  6502. if (ctx_) {
  6503. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  6504. // Free memory allocated for old cert and use new store `ca_cert_store`
  6505. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  6506. }
  6507. } else {
  6508. X509_STORE_free(ca_cert_store);
  6509. }
  6510. }
  6511. }
  6512. inline long SSLClient::get_openssl_verify_result() const {
  6513. return verify_result_;
  6514. }
  6515. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  6516. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  6517. return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
  6518. }
  6519. // Assumes that socket_mutex_ is locked and that there are no requests in flight
  6520. inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res,
  6521. bool &success, Error &error) {
  6522. success = true;
  6523. Response res2;
  6524. if (!detail::process_client_socket(
  6525. socket.sock, read_timeout_sec_, read_timeout_usec_,
  6526. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  6527. Request req2;
  6528. req2.method = "CONNECT";
  6529. req2.path = host_and_port_;
  6530. return process_request(strm, req2, res2, false, error);
  6531. })) {
  6532. // Thread-safe to close everything because we are assuming there are no
  6533. // requests in flight
  6534. shutdown_ssl(socket, true);
  6535. shutdown_socket(socket);
  6536. close_socket(socket);
  6537. success = false;
  6538. return false;
  6539. }
  6540. if (res2.status == 407) {
  6541. if (!proxy_digest_auth_username_.empty() &&
  6542. !proxy_digest_auth_password_.empty()) {
  6543. std::map<std::string, std::string> auth;
  6544. if (detail::parse_www_authenticate(res2, auth, true)) {
  6545. Response res3;
  6546. if (!detail::process_client_socket(
  6547. socket.sock, read_timeout_sec_, read_timeout_usec_,
  6548. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  6549. Request req3;
  6550. req3.method = "CONNECT";
  6551. req3.path = host_and_port_;
  6552. req3.headers.insert(detail::make_digest_authentication_header(
  6553. req3, auth, 1, detail::random_string(10),
  6554. proxy_digest_auth_username_, proxy_digest_auth_password_,
  6555. true));
  6556. return process_request(strm, req3, res3, false, error);
  6557. })) {
  6558. // Thread-safe to close everything because we are assuming there are
  6559. // no requests in flight
  6560. shutdown_ssl(socket, true);
  6561. shutdown_socket(socket);
  6562. close_socket(socket);
  6563. success = false;
  6564. return false;
  6565. }
  6566. }
  6567. } else {
  6568. res = res2;
  6569. return false;
  6570. }
  6571. }
  6572. return true;
  6573. }
  6574. inline bool SSLClient::load_certs() {
  6575. bool ret = true;
  6576. std::call_once(initialize_cert_, [&]() {
  6577. std::lock_guard<std::mutex> guard(ctx_mutex_);
  6578. if (!ca_cert_file_path_.empty()) {
  6579. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  6580. nullptr)) {
  6581. ret = false;
  6582. }
  6583. } else if (!ca_cert_dir_path_.empty()) {
  6584. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  6585. ca_cert_dir_path_.c_str())) {
  6586. ret = false;
  6587. }
  6588. } else {
  6589. #ifdef _WIN32
  6590. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  6591. #else
  6592. SSL_CTX_set_default_verify_paths(ctx_);
  6593. #endif
  6594. }
  6595. });
  6596. return ret;
  6597. }
  6598. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  6599. auto ssl = detail::ssl_new(
  6600. socket.sock, ctx_, ctx_mutex_,
  6601. [&](SSL *ssl2) {
  6602. if (server_certificate_verification_) {
  6603. if (!load_certs()) {
  6604. error = Error::SSLLoadingCerts;
  6605. return false;
  6606. }
  6607. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  6608. }
  6609. if (!detail::ssl_connect_or_accept_nonblocking(
  6610. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  6611. connection_timeout_usec_)) {
  6612. error = Error::SSLConnection;
  6613. return false;
  6614. }
  6615. if (server_certificate_verification_) {
  6616. verify_result_ = SSL_get_verify_result(ssl2);
  6617. if (verify_result_ != X509_V_OK) {
  6618. error = Error::SSLServerVerification;
  6619. return false;
  6620. }
  6621. auto server_cert = SSL_get1_peer_certificate(ssl2);
  6622. if (server_cert == nullptr) {
  6623. error = Error::SSLServerVerification;
  6624. return false;
  6625. }
  6626. if (!verify_host(server_cert)) {
  6627. X509_free(server_cert);
  6628. error = Error::SSLServerVerification;
  6629. return false;
  6630. }
  6631. X509_free(server_cert);
  6632. }
  6633. return true;
  6634. },
  6635. [&](SSL *ssl2) {
  6636. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  6637. return true;
  6638. });
  6639. if (ssl) {
  6640. socket.ssl = ssl;
  6641. return true;
  6642. }
  6643. shutdown_socket(socket);
  6644. close_socket(socket);
  6645. return false;
  6646. }
  6647. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  6648. shutdown_ssl_impl(socket, shutdown_gracefully);
  6649. }
  6650. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  6651. bool shutdown_gracefully) {
  6652. if (socket.sock == INVALID_SOCKET) {
  6653. assert(socket.ssl == nullptr);
  6654. return;
  6655. }
  6656. if (socket.ssl) {
  6657. detail::ssl_delete(ctx_mutex_, socket.ssl, shutdown_gracefully);
  6658. socket.ssl = nullptr;
  6659. }
  6660. assert(socket.ssl == nullptr);
  6661. }
  6662. inline bool
  6663. SSLClient::process_socket(const Socket &socket,
  6664. std::function<bool(Stream &strm)> callback) {
  6665. assert(socket.ssl);
  6666. return detail::process_client_socket_ssl(
  6667. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  6668. write_timeout_sec_, write_timeout_usec_, std::move(callback));
  6669. }
  6670. inline bool SSLClient::is_ssl() const { return true; }
  6671. inline bool SSLClient::verify_host(X509 *server_cert) const {
  6672. /* Quote from RFC2818 section 3.1 "Server Identity"
  6673. If a subjectAltName extension of type dNSName is present, that MUST
  6674. be used as the identity. Otherwise, the (most specific) Common Name
  6675. field in the Subject field of the certificate MUST be used. Although
  6676. the use of the Common Name is existing practice, it is deprecated and
  6677. Certification Authorities are encouraged to use the dNSName instead.
  6678. Matching is performed using the matching rules specified by
  6679. [RFC2459]. If more than one identity of a given type is present in
  6680. the certificate (e.g., more than one dNSName name, a match in any one
  6681. of the set is considered acceptable.) Names may contain the wildcard
  6682. character * which is considered to match any single domain name
  6683. component or component fragment. E.g., *.a.com matches foo.a.com but
  6684. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  6685. In some cases, the URI is specified as an IP address rather than a
  6686. hostname. In this case, the iPAddress subjectAltName must be present
  6687. in the certificate and must exactly match the IP in the URI.
  6688. */
  6689. return verify_host_with_subject_alt_name(server_cert) ||
  6690. verify_host_with_common_name(server_cert);
  6691. }
  6692. inline bool
  6693. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  6694. auto ret = false;
  6695. auto type = GEN_DNS;
  6696. struct in6_addr addr6;
  6697. struct in_addr addr;
  6698. size_t addr_len = 0;
  6699. #ifndef __MINGW32__
  6700. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  6701. type = GEN_IPADD;
  6702. addr_len = sizeof(struct in6_addr);
  6703. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  6704. type = GEN_IPADD;
  6705. addr_len = sizeof(struct in_addr);
  6706. }
  6707. #endif
  6708. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  6709. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  6710. if (alt_names) {
  6711. auto dsn_matched = false;
  6712. auto ip_mached = false;
  6713. auto count = sk_GENERAL_NAME_num(alt_names);
  6714. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  6715. auto val = sk_GENERAL_NAME_value(alt_names, i);
  6716. if (val->type == type) {
  6717. auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
  6718. auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
  6719. switch (type) {
  6720. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  6721. case GEN_IPADD:
  6722. if (!memcmp(&addr6, name, addr_len) ||
  6723. !memcmp(&addr, name, addr_len)) {
  6724. ip_mached = true;
  6725. }
  6726. break;
  6727. }
  6728. }
  6729. }
  6730. if (dsn_matched || ip_mached) { ret = true; }
  6731. }
  6732. GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
  6733. return ret;
  6734. }
  6735. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  6736. const auto subject_name = X509_get_subject_name(server_cert);
  6737. if (subject_name != nullptr) {
  6738. char name[BUFSIZ];
  6739. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6740. name, sizeof(name));
  6741. if (name_len != -1) {
  6742. return check_host_name(name, static_cast<size_t>(name_len));
  6743. }
  6744. }
  6745. return false;
  6746. }
  6747. inline bool SSLClient::check_host_name(const char *pattern,
  6748. size_t pattern_len) const {
  6749. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  6750. // Wildcard match
  6751. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  6752. std::vector<std::string> pattern_components;
  6753. detail::split(&pattern[0], &pattern[pattern_len], '.',
  6754. [&](const char *b, const char *e) {
  6755. pattern_components.emplace_back(std::string(b, e));
  6756. });
  6757. if (host_components_.size() != pattern_components.size()) { return false; }
  6758. auto itr = pattern_components.begin();
  6759. for (const auto &h : host_components_) {
  6760. auto &p = *itr;
  6761. if (p != h && p != "*") {
  6762. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  6763. !p.compare(0, p.size() - 1, h));
  6764. if (!partial_match) { return false; }
  6765. }
  6766. ++itr;
  6767. }
  6768. return true;
  6769. }
  6770. #endif
  6771. // Universal client implementation
  6772. inline Client::Client(const std::string &scheme_host_port)
  6773. : Client(scheme_host_port, std::string(), std::string()) {}
  6774. inline Client::Client(const std::string &scheme_host_port,
  6775. const std::string &client_cert_path,
  6776. const std::string &client_key_path) {
  6777. const static std::regex re(
  6778. R"((?:([a-z]+):\/\/)?(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  6779. std::smatch m;
  6780. if (std::regex_match(scheme_host_port, m, re)) {
  6781. auto scheme = m[1].str();
  6782. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6783. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  6784. #else
  6785. if (!scheme.empty() && scheme != "http") {
  6786. #endif
  6787. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6788. std::string msg = "'" + scheme + "' scheme is not supported.";
  6789. throw std::invalid_argument(msg);
  6790. #endif
  6791. return;
  6792. }
  6793. auto is_ssl = scheme == "https";
  6794. auto host = m[2].str();
  6795. if (host.empty()) { host = m[3].str(); }
  6796. auto port_str = m[4].str();
  6797. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  6798. if (is_ssl) {
  6799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6800. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  6801. client_key_path);
  6802. is_ssl_ = is_ssl;
  6803. #endif
  6804. } else {
  6805. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  6806. client_key_path);
  6807. }
  6808. } else {
  6809. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  6810. client_cert_path, client_key_path);
  6811. }
  6812. }
  6813. inline Client::Client(const std::string &host, int port)
  6814. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  6815. inline Client::Client(const std::string &host, int port,
  6816. const std::string &client_cert_path,
  6817. const std::string &client_key_path)
  6818. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  6819. client_key_path)) {}
  6820. inline Client::~Client() {}
  6821. inline bool Client::is_valid() const {
  6822. return cli_ != nullptr && cli_->is_valid();
  6823. }
  6824. inline Result Client::Get(const std::string &path) { return cli_->Get(path); }
  6825. inline Result Client::Get(const std::string &path, const Headers &headers) {
  6826. return cli_->Get(path, headers);
  6827. }
  6828. inline Result Client::Get(const std::string &path, Progress progress) {
  6829. return cli_->Get(path, std::move(progress));
  6830. }
  6831. inline Result Client::Get(const std::string &path, const Headers &headers,
  6832. Progress progress) {
  6833. return cli_->Get(path, headers, std::move(progress));
  6834. }
  6835. inline Result Client::Get(const std::string &path,
  6836. ContentReceiver content_receiver) {
  6837. return cli_->Get(path, std::move(content_receiver));
  6838. }
  6839. inline Result Client::Get(const std::string &path, const Headers &headers,
  6840. ContentReceiver content_receiver) {
  6841. return cli_->Get(path, headers, std::move(content_receiver));
  6842. }
  6843. inline Result Client::Get(const std::string &path,
  6844. ContentReceiver content_receiver, Progress progress) {
  6845. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  6846. }
  6847. inline Result Client::Get(const std::string &path, const Headers &headers,
  6848. ContentReceiver content_receiver, Progress progress) {
  6849. return cli_->Get(path, headers, std::move(content_receiver),
  6850. std::move(progress));
  6851. }
  6852. inline Result Client::Get(const std::string &path,
  6853. ResponseHandler response_handler,
  6854. ContentReceiver content_receiver) {
  6855. return cli_->Get(path, std::move(response_handler),
  6856. std::move(content_receiver));
  6857. }
  6858. inline Result Client::Get(const std::string &path, const Headers &headers,
  6859. ResponseHandler response_handler,
  6860. ContentReceiver content_receiver) {
  6861. return cli_->Get(path, headers, std::move(response_handler),
  6862. std::move(content_receiver));
  6863. }
  6864. inline Result Client::Get(const std::string &path,
  6865. ResponseHandler response_handler,
  6866. ContentReceiver content_receiver, Progress progress) {
  6867. return cli_->Get(path, std::move(response_handler),
  6868. std::move(content_receiver), std::move(progress));
  6869. }
  6870. inline Result Client::Get(const std::string &path, const Headers &headers,
  6871. ResponseHandler response_handler,
  6872. ContentReceiver content_receiver, Progress progress) {
  6873. return cli_->Get(path, headers, std::move(response_handler),
  6874. std::move(content_receiver), std::move(progress));
  6875. }
  6876. inline Result Client::Get(const std::string &path, const Params &params,
  6877. const Headers &headers, Progress progress) {
  6878. return cli_->Get(path, params, headers, progress);
  6879. }
  6880. inline Result Client::Get(const std::string &path, const Params &params,
  6881. const Headers &headers,
  6882. ContentReceiver content_receiver, Progress progress) {
  6883. return cli_->Get(path, params, headers, content_receiver, progress);
  6884. }
  6885. inline Result Client::Get(const std::string &path, const Params &params,
  6886. const Headers &headers,
  6887. ResponseHandler response_handler,
  6888. ContentReceiver content_receiver, Progress progress) {
  6889. return cli_->Get(path, params, headers, response_handler, content_receiver,
  6890. progress);
  6891. }
  6892. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  6893. inline Result Client::Head(const std::string &path, const Headers &headers) {
  6894. return cli_->Head(path, headers);
  6895. }
  6896. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  6897. inline Result Client::Post(const std::string &path, const Headers &headers) {
  6898. return cli_->Post(path, headers);
  6899. }
  6900. inline Result Client::Post(const std::string &path, const char *body,
  6901. size_t content_length,
  6902. const std::string &content_type) {
  6903. return cli_->Post(path, body, content_length, content_type);
  6904. }
  6905. inline Result Client::Post(const std::string &path, const Headers &headers,
  6906. const char *body, size_t content_length,
  6907. const std::string &content_type) {
  6908. return cli_->Post(path, headers, body, content_length, content_type);
  6909. }
  6910. inline Result Client::Post(const std::string &path, const std::string &body,
  6911. const std::string &content_type) {
  6912. return cli_->Post(path, body, content_type);
  6913. }
  6914. inline Result Client::Post(const std::string &path, const Headers &headers,
  6915. const std::string &body,
  6916. const std::string &content_type) {
  6917. return cli_->Post(path, headers, body, content_type);
  6918. }
  6919. inline Result Client::Post(const std::string &path, size_t content_length,
  6920. ContentProvider content_provider,
  6921. const std::string &content_type) {
  6922. return cli_->Post(path, content_length, std::move(content_provider),
  6923. content_type);
  6924. }
  6925. inline Result Client::Post(const std::string &path,
  6926. ContentProviderWithoutLength content_provider,
  6927. const std::string &content_type) {
  6928. return cli_->Post(path, std::move(content_provider), content_type);
  6929. }
  6930. inline Result Client::Post(const std::string &path, const Headers &headers,
  6931. size_t content_length,
  6932. ContentProvider content_provider,
  6933. const std::string &content_type) {
  6934. return cli_->Post(path, headers, content_length, std::move(content_provider),
  6935. content_type);
  6936. }
  6937. inline Result Client::Post(const std::string &path, const Headers &headers,
  6938. ContentProviderWithoutLength content_provider,
  6939. const std::string &content_type) {
  6940. return cli_->Post(path, headers, std::move(content_provider), content_type);
  6941. }
  6942. inline Result Client::Post(const std::string &path, const Params &params) {
  6943. return cli_->Post(path, params);
  6944. }
  6945. inline Result Client::Post(const std::string &path, const Headers &headers,
  6946. const Params &params) {
  6947. return cli_->Post(path, headers, params);
  6948. }
  6949. inline Result Client::Post(const std::string &path,
  6950. const MultipartFormDataItems &items) {
  6951. return cli_->Post(path, items);
  6952. }
  6953. inline Result Client::Post(const std::string &path, const Headers &headers,
  6954. const MultipartFormDataItems &items) {
  6955. return cli_->Post(path, headers, items);
  6956. }
  6957. inline Result Client::Post(const std::string &path, const Headers &headers,
  6958. const MultipartFormDataItems &items,
  6959. const std::string &boundary) {
  6960. return cli_->Post(path, headers, items, boundary);
  6961. }
  6962. inline Result
  6963. Client::Post(const std::string &path, const Headers &headers,
  6964. const MultipartFormDataItems &items,
  6965. const MultipartFormDataProviderItems &provider_items) {
  6966. return cli_->Post(path, headers, items, provider_items);
  6967. }
  6968. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  6969. inline Result Client::Put(const std::string &path, const char *body,
  6970. size_t content_length,
  6971. const std::string &content_type) {
  6972. return cli_->Put(path, body, content_length, content_type);
  6973. }
  6974. inline Result Client::Put(const std::string &path, const Headers &headers,
  6975. const char *body, size_t content_length,
  6976. const std::string &content_type) {
  6977. return cli_->Put(path, headers, body, content_length, content_type);
  6978. }
  6979. inline Result Client::Put(const std::string &path, const std::string &body,
  6980. const std::string &content_type) {
  6981. return cli_->Put(path, body, content_type);
  6982. }
  6983. inline Result Client::Put(const std::string &path, const Headers &headers,
  6984. const std::string &body,
  6985. const std::string &content_type) {
  6986. return cli_->Put(path, headers, body, content_type);
  6987. }
  6988. inline Result Client::Put(const std::string &path, size_t content_length,
  6989. ContentProvider content_provider,
  6990. const std::string &content_type) {
  6991. return cli_->Put(path, content_length, std::move(content_provider),
  6992. content_type);
  6993. }
  6994. inline Result Client::Put(const std::string &path,
  6995. ContentProviderWithoutLength content_provider,
  6996. const std::string &content_type) {
  6997. return cli_->Put(path, std::move(content_provider), content_type);
  6998. }
  6999. inline Result Client::Put(const std::string &path, const Headers &headers,
  7000. size_t content_length,
  7001. ContentProvider content_provider,
  7002. const std::string &content_type) {
  7003. return cli_->Put(path, headers, content_length, std::move(content_provider),
  7004. content_type);
  7005. }
  7006. inline Result Client::Put(const std::string &path, const Headers &headers,
  7007. ContentProviderWithoutLength content_provider,
  7008. const std::string &content_type) {
  7009. return cli_->Put(path, headers, std::move(content_provider), content_type);
  7010. }
  7011. inline Result Client::Put(const std::string &path, const Params &params) {
  7012. return cli_->Put(path, params);
  7013. }
  7014. inline Result Client::Put(const std::string &path, const Headers &headers,
  7015. const Params &params) {
  7016. return cli_->Put(path, headers, params);
  7017. }
  7018. inline Result Client::Put(const std::string &path,
  7019. const MultipartFormDataItems &items) {
  7020. return cli_->Put(path, items);
  7021. }
  7022. inline Result Client::Put(const std::string &path, const Headers &headers,
  7023. const MultipartFormDataItems &items) {
  7024. return cli_->Put(path, headers, items);
  7025. }
  7026. inline Result Client::Put(const std::string &path, const Headers &headers,
  7027. const MultipartFormDataItems &items,
  7028. const std::string &boundary) {
  7029. return cli_->Put(path, headers, items, boundary);
  7030. }
  7031. inline Result
  7032. Client::Put(const std::string &path, const Headers &headers,
  7033. const MultipartFormDataItems &items,
  7034. const MultipartFormDataProviderItems &provider_items) {
  7035. return cli_->Put(path, headers, items, provider_items);
  7036. }
  7037. inline Result Client::Patch(const std::string &path) {
  7038. return cli_->Patch(path);
  7039. }
  7040. inline Result Client::Patch(const std::string &path, const char *body,
  7041. size_t content_length,
  7042. const std::string &content_type) {
  7043. return cli_->Patch(path, body, content_length, content_type);
  7044. }
  7045. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7046. const char *body, size_t content_length,
  7047. const std::string &content_type) {
  7048. return cli_->Patch(path, headers, body, content_length, content_type);
  7049. }
  7050. inline Result Client::Patch(const std::string &path, const std::string &body,
  7051. const std::string &content_type) {
  7052. return cli_->Patch(path, body, content_type);
  7053. }
  7054. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7055. const std::string &body,
  7056. const std::string &content_type) {
  7057. return cli_->Patch(path, headers, body, content_type);
  7058. }
  7059. inline Result Client::Patch(const std::string &path, size_t content_length,
  7060. ContentProvider content_provider,
  7061. const std::string &content_type) {
  7062. return cli_->Patch(path, content_length, std::move(content_provider),
  7063. content_type);
  7064. }
  7065. inline Result Client::Patch(const std::string &path,
  7066. ContentProviderWithoutLength content_provider,
  7067. const std::string &content_type) {
  7068. return cli_->Patch(path, std::move(content_provider), content_type);
  7069. }
  7070. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7071. size_t content_length,
  7072. ContentProvider content_provider,
  7073. const std::string &content_type) {
  7074. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  7075. content_type);
  7076. }
  7077. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7078. ContentProviderWithoutLength content_provider,
  7079. const std::string &content_type) {
  7080. return cli_->Patch(path, headers, std::move(content_provider), content_type);
  7081. }
  7082. inline Result Client::Delete(const std::string &path) {
  7083. return cli_->Delete(path);
  7084. }
  7085. inline Result Client::Delete(const std::string &path, const Headers &headers) {
  7086. return cli_->Delete(path, headers);
  7087. }
  7088. inline Result Client::Delete(const std::string &path, const char *body,
  7089. size_t content_length,
  7090. const std::string &content_type) {
  7091. return cli_->Delete(path, body, content_length, content_type);
  7092. }
  7093. inline Result Client::Delete(const std::string &path, const Headers &headers,
  7094. const char *body, size_t content_length,
  7095. const std::string &content_type) {
  7096. return cli_->Delete(path, headers, body, content_length, content_type);
  7097. }
  7098. inline Result Client::Delete(const std::string &path, const std::string &body,
  7099. const std::string &content_type) {
  7100. return cli_->Delete(path, body, content_type);
  7101. }
  7102. inline Result Client::Delete(const std::string &path, const Headers &headers,
  7103. const std::string &body,
  7104. const std::string &content_type) {
  7105. return cli_->Delete(path, headers, body, content_type);
  7106. }
  7107. inline Result Client::Options(const std::string &path) {
  7108. return cli_->Options(path);
  7109. }
  7110. inline Result Client::Options(const std::string &path, const Headers &headers) {
  7111. return cli_->Options(path, headers);
  7112. }
  7113. inline bool Client::send(Request &req, Response &res, Error &error) {
  7114. return cli_->send(req, res, error);
  7115. }
  7116. inline Result Client::send(const Request &req) { return cli_->send(req); }
  7117. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  7118. inline socket_t Client::socket() const { return cli_->socket(); }
  7119. inline void Client::stop() { cli_->stop(); }
  7120. inline void
  7121. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  7122. cli_->set_hostname_addr_map(std::move(addr_map));
  7123. }
  7124. inline void Client::set_default_headers(Headers headers) {
  7125. cli_->set_default_headers(std::move(headers));
  7126. }
  7127. inline void Client::set_address_family(int family) {
  7128. cli_->set_address_family(family);
  7129. }
  7130. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  7131. inline void Client::set_socket_options(SocketOptions socket_options) {
  7132. cli_->set_socket_options(std::move(socket_options));
  7133. }
  7134. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  7135. cli_->set_connection_timeout(sec, usec);
  7136. }
  7137. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  7138. cli_->set_read_timeout(sec, usec);
  7139. }
  7140. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  7141. cli_->set_write_timeout(sec, usec);
  7142. }
  7143. inline void Client::set_basic_auth(const std::string &username,
  7144. const std::string &password) {
  7145. cli_->set_basic_auth(username, password);
  7146. }
  7147. inline void Client::set_bearer_token_auth(const std::string &token) {
  7148. cli_->set_bearer_token_auth(token);
  7149. }
  7150. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7151. inline void Client::set_digest_auth(const std::string &username,
  7152. const std::string &password) {
  7153. cli_->set_digest_auth(username, password);
  7154. }
  7155. #endif
  7156. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  7157. inline void Client::set_follow_location(bool on) {
  7158. cli_->set_follow_location(on);
  7159. }
  7160. inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); }
  7161. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  7162. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  7163. inline void Client::set_interface(const std::string &intf) {
  7164. cli_->set_interface(intf);
  7165. }
  7166. inline void Client::set_proxy(const std::string &host, int port) {
  7167. cli_->set_proxy(host, port);
  7168. }
  7169. inline void Client::set_proxy_basic_auth(const std::string &username,
  7170. const std::string &password) {
  7171. cli_->set_proxy_basic_auth(username, password);
  7172. }
  7173. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  7174. cli_->set_proxy_bearer_token_auth(token);
  7175. }
  7176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7177. inline void Client::set_proxy_digest_auth(const std::string &username,
  7178. const std::string &password) {
  7179. cli_->set_proxy_digest_auth(username, password);
  7180. }
  7181. #endif
  7182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7183. inline void Client::enable_server_certificate_verification(bool enabled) {
  7184. cli_->enable_server_certificate_verification(enabled);
  7185. }
  7186. #endif
  7187. inline void Client::set_logger(Logger logger) { cli_->set_logger(logger); }
  7188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7189. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  7190. const std::string &ca_cert_dir_path) {
  7191. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  7192. }
  7193. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  7194. if (is_ssl_) {
  7195. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  7196. } else {
  7197. cli_->set_ca_cert_store(ca_cert_store);
  7198. }
  7199. }
  7200. inline long Client::get_openssl_verify_result() const {
  7201. if (is_ssl_) {
  7202. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  7203. }
  7204. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  7205. }
  7206. inline SSL_CTX *Client::ssl_context() const {
  7207. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  7208. return nullptr;
  7209. }
  7210. #endif
  7211. // ----------------------------------------------------------------------------
  7212. } // namespace httplib
  7213. #if defined(_WIN32) && defined(CPPHTTPLIB_USE_POLL)
  7214. #undef poll
  7215. #endif
  7216. #endif // CPPHTTPLIB_HTTPLIB_H