1
0

httplib.cpp 298 KB

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