httplib.h 471 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.30.1"
  10. #define CPPHTTPLIB_VERSION_NUM "0x001E01"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  81. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  82. #endif
  83. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  84. #ifdef _WIN32
  85. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  86. #else
  87. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  88. #endif
  89. #endif
  90. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  91. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  92. #endif
  93. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  94. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  95. #endif
  96. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  97. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  98. #endif
  99. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  100. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  101. #endif
  102. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  103. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  104. #endif
  105. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  106. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  107. #endif
  108. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  109. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  110. #endif
  111. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  112. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  113. #endif
  114. #ifndef CPPHTTPLIB_TCP_NODELAY
  115. #define CPPHTTPLIB_TCP_NODELAY false
  116. #endif
  117. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  118. #define CPPHTTPLIB_IPV6_V6ONLY false
  119. #endif
  120. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  121. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  124. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  125. #endif
  126. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  127. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  131. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  132. ? std::thread::hardware_concurrency() - 1 \
  133. : 0))
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. /*
  148. * Headers
  149. */
  150. #ifdef _WIN32
  151. #ifndef _CRT_SECURE_NO_WARNINGS
  152. #define _CRT_SECURE_NO_WARNINGS
  153. #endif //_CRT_SECURE_NO_WARNINGS
  154. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  155. #define _CRT_NONSTDC_NO_DEPRECATE
  156. #endif //_CRT_NONSTDC_NO_DEPRECATE
  157. #if defined(_MSC_VER)
  158. #if _MSC_VER < 1900
  159. #error Sorry, Visual Studio versions prior to 2015 are not supported
  160. #endif
  161. #pragma comment(lib, "ws2_32.lib")
  162. #ifndef _SSIZE_T_DEFINED
  163. using ssize_t = __int64;
  164. #define _SSIZE_T_DEFINED
  165. #endif
  166. #endif // _MSC_VER
  167. #ifndef S_ISREG
  168. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  169. #endif // S_ISREG
  170. #ifndef S_ISDIR
  171. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  172. #endif // S_ISDIR
  173. #ifndef NOMINMAX
  174. #define NOMINMAX
  175. #endif // NOMINMAX
  176. #include <io.h>
  177. #include <winsock2.h>
  178. #include <ws2tcpip.h>
  179. #if defined(__has_include)
  180. #if __has_include(<afunix.h>)
  181. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  182. #include <afunix.h>
  183. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  184. #endif
  185. #endif
  186. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  187. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  188. #endif
  189. using nfds_t = unsigned long;
  190. using socket_t = SOCKET;
  191. using socklen_t = int;
  192. #else // not _WIN32
  193. #include <arpa/inet.h>
  194. #if !defined(_AIX) && !defined(__MVS__)
  195. #include <ifaddrs.h>
  196. #endif
  197. #ifdef __MVS__
  198. #include <strings.h>
  199. #ifndef NI_MAXHOST
  200. #define NI_MAXHOST 1025
  201. #endif
  202. #endif
  203. #include <net/if.h>
  204. #include <netdb.h>
  205. #include <netinet/in.h>
  206. #ifdef __linux__
  207. #include <resolv.h>
  208. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  209. #endif
  210. #include <csignal>
  211. #include <netinet/tcp.h>
  212. #include <poll.h>
  213. #include <pthread.h>
  214. #include <sys/mman.h>
  215. #include <sys/socket.h>
  216. #include <sys/un.h>
  217. #include <unistd.h>
  218. using socket_t = int;
  219. #ifndef INVALID_SOCKET
  220. #define INVALID_SOCKET (-1)
  221. #endif
  222. #endif //_WIN32
  223. #if defined(__APPLE__)
  224. #include <TargetConditionals.h>
  225. #endif
  226. #include <algorithm>
  227. #include <array>
  228. #include <atomic>
  229. #include <cassert>
  230. #include <cctype>
  231. #include <chrono>
  232. #include <climits>
  233. #include <condition_variable>
  234. #include <cstring>
  235. #include <errno.h>
  236. #include <exception>
  237. #include <fcntl.h>
  238. #include <functional>
  239. #include <iomanip>
  240. #include <iostream>
  241. #include <list>
  242. #include <map>
  243. #include <memory>
  244. #include <mutex>
  245. #include <random>
  246. #include <regex>
  247. #include <set>
  248. #include <sstream>
  249. #include <string>
  250. #include <sys/stat.h>
  251. #include <thread>
  252. #include <unordered_map>
  253. #include <unordered_set>
  254. #include <utility>
  255. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  256. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  257. #if TARGET_OS_MAC
  258. #include <CFNetwork/CFHost.h>
  259. #include <CoreFoundation/CoreFoundation.h>
  260. #endif
  261. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  262. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  263. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  264. #ifdef _WIN32
  265. #include <wincrypt.h>
  266. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  267. // used
  268. #undef X509_NAME
  269. #undef X509_CERT_PAIR
  270. #undef X509_EXTENSIONS
  271. #undef PKCS7_SIGNER_INFO
  272. #ifdef _MSC_VER
  273. #pragma comment(lib, "crypt32.lib")
  274. #endif
  275. #endif // _WIN32
  276. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  277. #if TARGET_OS_MAC
  278. #include <Security/Security.h>
  279. #endif
  280. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  281. #include <openssl/err.h>
  282. #include <openssl/evp.h>
  283. #include <openssl/ssl.h>
  284. #include <openssl/x509v3.h>
  285. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  286. #include <openssl/applink.c>
  287. #endif
  288. #include <iostream>
  289. #include <sstream>
  290. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  291. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  292. #error Please use OpenSSL or a current version of BoringSSL
  293. #endif
  294. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  295. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  296. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  297. #endif
  298. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  299. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  300. #include <zlib.h>
  301. #endif
  302. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  303. #include <brotli/decode.h>
  304. #include <brotli/encode.h>
  305. #endif
  306. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  307. #include <zstd.h>
  308. #endif
  309. /*
  310. * Declaration
  311. */
  312. namespace httplib {
  313. namespace detail {
  314. /*
  315. * Backport std::make_unique from C++14.
  316. *
  317. * NOTE: This code came up with the following stackoverflow post:
  318. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  319. *
  320. */
  321. template <class T, class... Args>
  322. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  323. make_unique(Args &&...args) {
  324. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  325. }
  326. template <class T>
  327. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  328. make_unique(std::size_t n) {
  329. typedef typename std::remove_extent<T>::type RT;
  330. return std::unique_ptr<T>(new RT[n]);
  331. }
  332. namespace case_ignore {
  333. inline unsigned char to_lower(int c) {
  334. const static unsigned char table[256] = {
  335. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  336. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  337. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  338. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  339. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  340. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  341. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  342. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  343. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  344. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  345. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  346. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  347. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  348. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  349. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  350. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  351. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  352. 255,
  353. };
  354. return table[(unsigned char)(char)c];
  355. }
  356. inline bool equal(const std::string &a, const std::string &b) {
  357. return a.size() == b.size() &&
  358. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  359. return to_lower(ca) == to_lower(cb);
  360. });
  361. }
  362. struct equal_to {
  363. bool operator()(const std::string &a, const std::string &b) const {
  364. return equal(a, b);
  365. }
  366. };
  367. struct hash {
  368. size_t operator()(const std::string &key) const {
  369. return hash_core(key.data(), key.size(), 0);
  370. }
  371. size_t hash_core(const char *s, size_t l, size_t h) const {
  372. return (l == 0) ? h
  373. : hash_core(s + 1, l - 1,
  374. // Unsets the 6 high bits of h, therefore no
  375. // overflow happens
  376. (((std::numeric_limits<size_t>::max)() >> 6) &
  377. h * 33) ^
  378. static_cast<unsigned char>(to_lower(*s)));
  379. }
  380. };
  381. template <typename T>
  382. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  383. detail::case_ignore::equal_to>;
  384. } // namespace case_ignore
  385. // This is based on
  386. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  387. struct scope_exit {
  388. explicit scope_exit(std::function<void(void)> &&f)
  389. : exit_function(std::move(f)), execute_on_destruction{true} {}
  390. scope_exit(scope_exit &&rhs) noexcept
  391. : exit_function(std::move(rhs.exit_function)),
  392. execute_on_destruction{rhs.execute_on_destruction} {
  393. rhs.release();
  394. }
  395. ~scope_exit() {
  396. if (execute_on_destruction) { this->exit_function(); }
  397. }
  398. void release() { this->execute_on_destruction = false; }
  399. private:
  400. scope_exit(const scope_exit &) = delete;
  401. void operator=(const scope_exit &) = delete;
  402. scope_exit &operator=(scope_exit &&) = delete;
  403. std::function<void(void)> exit_function;
  404. bool execute_on_destruction;
  405. };
  406. } // namespace detail
  407. enum SSLVerifierResponse {
  408. // no decision has been made, use the built-in certificate verifier
  409. NoDecisionMade,
  410. // connection certificate is verified and accepted
  411. CertificateAccepted,
  412. // connection certificate was processed but is rejected
  413. CertificateRejected
  414. };
  415. enum StatusCode {
  416. // Information responses
  417. Continue_100 = 100,
  418. SwitchingProtocol_101 = 101,
  419. Processing_102 = 102,
  420. EarlyHints_103 = 103,
  421. // Successful responses
  422. OK_200 = 200,
  423. Created_201 = 201,
  424. Accepted_202 = 202,
  425. NonAuthoritativeInformation_203 = 203,
  426. NoContent_204 = 204,
  427. ResetContent_205 = 205,
  428. PartialContent_206 = 206,
  429. MultiStatus_207 = 207,
  430. AlreadyReported_208 = 208,
  431. IMUsed_226 = 226,
  432. // Redirection messages
  433. MultipleChoices_300 = 300,
  434. MovedPermanently_301 = 301,
  435. Found_302 = 302,
  436. SeeOther_303 = 303,
  437. NotModified_304 = 304,
  438. UseProxy_305 = 305,
  439. unused_306 = 306,
  440. TemporaryRedirect_307 = 307,
  441. PermanentRedirect_308 = 308,
  442. // Client error responses
  443. BadRequest_400 = 400,
  444. Unauthorized_401 = 401,
  445. PaymentRequired_402 = 402,
  446. Forbidden_403 = 403,
  447. NotFound_404 = 404,
  448. MethodNotAllowed_405 = 405,
  449. NotAcceptable_406 = 406,
  450. ProxyAuthenticationRequired_407 = 407,
  451. RequestTimeout_408 = 408,
  452. Conflict_409 = 409,
  453. Gone_410 = 410,
  454. LengthRequired_411 = 411,
  455. PreconditionFailed_412 = 412,
  456. PayloadTooLarge_413 = 413,
  457. UriTooLong_414 = 414,
  458. UnsupportedMediaType_415 = 415,
  459. RangeNotSatisfiable_416 = 416,
  460. ExpectationFailed_417 = 417,
  461. ImATeapot_418 = 418,
  462. MisdirectedRequest_421 = 421,
  463. UnprocessableContent_422 = 422,
  464. Locked_423 = 423,
  465. FailedDependency_424 = 424,
  466. TooEarly_425 = 425,
  467. UpgradeRequired_426 = 426,
  468. PreconditionRequired_428 = 428,
  469. TooManyRequests_429 = 429,
  470. RequestHeaderFieldsTooLarge_431 = 431,
  471. UnavailableForLegalReasons_451 = 451,
  472. // Server error responses
  473. InternalServerError_500 = 500,
  474. NotImplemented_501 = 501,
  475. BadGateway_502 = 502,
  476. ServiceUnavailable_503 = 503,
  477. GatewayTimeout_504 = 504,
  478. HttpVersionNotSupported_505 = 505,
  479. VariantAlsoNegotiates_506 = 506,
  480. InsufficientStorage_507 = 507,
  481. LoopDetected_508 = 508,
  482. NotExtended_510 = 510,
  483. NetworkAuthenticationRequired_511 = 511,
  484. };
  485. using Headers =
  486. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  487. detail::case_ignore::equal_to>;
  488. using Params = std::multimap<std::string, std::string>;
  489. using Match = std::smatch;
  490. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  491. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  492. struct Response;
  493. using ResponseHandler = std::function<bool(const Response &response)>;
  494. struct FormData {
  495. std::string name;
  496. std::string content;
  497. std::string filename;
  498. std::string content_type;
  499. Headers headers;
  500. };
  501. struct FormField {
  502. std::string name;
  503. std::string content;
  504. Headers headers;
  505. };
  506. using FormFields = std::multimap<std::string, FormField>;
  507. using FormFiles = std::multimap<std::string, FormData>;
  508. struct MultipartFormData {
  509. FormFields fields; // Text fields from multipart
  510. FormFiles files; // Files from multipart
  511. // Text field access
  512. std::string get_field(const std::string &key, size_t id = 0) const;
  513. std::vector<std::string> get_fields(const std::string &key) const;
  514. bool has_field(const std::string &key) const;
  515. size_t get_field_count(const std::string &key) const;
  516. // File access
  517. FormData get_file(const std::string &key, size_t id = 0) const;
  518. std::vector<FormData> get_files(const std::string &key) const;
  519. bool has_file(const std::string &key) const;
  520. size_t get_file_count(const std::string &key) const;
  521. };
  522. struct UploadFormData {
  523. std::string name;
  524. std::string content;
  525. std::string filename;
  526. std::string content_type;
  527. };
  528. using UploadFormDataItems = std::vector<UploadFormData>;
  529. class DataSink {
  530. public:
  531. DataSink() : os(&sb_), sb_(*this) {}
  532. DataSink(const DataSink &) = delete;
  533. DataSink &operator=(const DataSink &) = delete;
  534. DataSink(DataSink &&) = delete;
  535. DataSink &operator=(DataSink &&) = delete;
  536. std::function<bool(const char *data, size_t data_len)> write;
  537. std::function<bool()> is_writable;
  538. std::function<void()> done;
  539. std::function<void(const Headers &trailer)> done_with_trailer;
  540. std::ostream os;
  541. private:
  542. class data_sink_streambuf final : public std::streambuf {
  543. public:
  544. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  545. protected:
  546. std::streamsize xsputn(const char *s, std::streamsize n) override {
  547. sink_.write(s, static_cast<size_t>(n));
  548. return n;
  549. }
  550. private:
  551. DataSink &sink_;
  552. };
  553. data_sink_streambuf sb_;
  554. };
  555. using ContentProvider =
  556. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  557. using ContentProviderWithoutLength =
  558. std::function<bool(size_t offset, DataSink &sink)>;
  559. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  560. struct FormDataProvider {
  561. std::string name;
  562. ContentProviderWithoutLength provider;
  563. std::string filename;
  564. std::string content_type;
  565. };
  566. using FormDataProviderItems = std::vector<FormDataProvider>;
  567. using ContentReceiverWithProgress = std::function<bool(
  568. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  569. using ContentReceiver =
  570. std::function<bool(const char *data, size_t data_length)>;
  571. using FormDataHeader = std::function<bool(const FormData &file)>;
  572. class ContentReader {
  573. public:
  574. using Reader = std::function<bool(ContentReceiver receiver)>;
  575. using FormDataReader =
  576. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  577. ContentReader(Reader reader, FormDataReader multipart_reader)
  578. : reader_(std::move(reader)),
  579. formdata_reader_(std::move(multipart_reader)) {}
  580. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  581. return formdata_reader_(std::move(header), std::move(receiver));
  582. }
  583. bool operator()(ContentReceiver receiver) const {
  584. return reader_(std::move(receiver));
  585. }
  586. Reader reader_;
  587. FormDataReader formdata_reader_;
  588. };
  589. using Range = std::pair<ssize_t, ssize_t>;
  590. using Ranges = std::vector<Range>;
  591. struct Request {
  592. std::string method;
  593. std::string path;
  594. std::string matched_route;
  595. Params params;
  596. Headers headers;
  597. Headers trailers;
  598. std::string body;
  599. std::string remote_addr;
  600. int remote_port = -1;
  601. std::string local_addr;
  602. int local_port = -1;
  603. // for server
  604. std::string version;
  605. std::string target;
  606. MultipartFormData form;
  607. Ranges ranges;
  608. Match matches;
  609. std::unordered_map<std::string, std::string> path_params;
  610. std::function<bool()> is_connection_closed = []() { return true; };
  611. // for client
  612. std::vector<std::string> accept_content_types;
  613. ResponseHandler response_handler;
  614. ContentReceiverWithProgress content_receiver;
  615. DownloadProgress download_progress;
  616. UploadProgress upload_progress;
  617. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  618. const SSL *ssl = nullptr;
  619. #endif
  620. bool has_header(const std::string &key) const;
  621. std::string get_header_value(const std::string &key, const char *def = "",
  622. size_t id = 0) const;
  623. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  624. size_t id = 0) const;
  625. size_t get_header_value_count(const std::string &key) const;
  626. void set_header(const std::string &key, const std::string &val);
  627. bool has_trailer(const std::string &key) const;
  628. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  629. size_t get_trailer_value_count(const std::string &key) const;
  630. bool has_param(const std::string &key) const;
  631. std::string get_param_value(const std::string &key, size_t id = 0) const;
  632. size_t get_param_value_count(const std::string &key) const;
  633. bool is_multipart_form_data() const;
  634. // private members...
  635. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  636. size_t content_length_ = 0;
  637. ContentProvider content_provider_;
  638. bool is_chunked_content_provider_ = false;
  639. size_t authorization_count_ = 0;
  640. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  641. (std::chrono::steady_clock::time_point::min)();
  642. };
  643. struct Response {
  644. std::string version;
  645. int status = -1;
  646. std::string reason;
  647. Headers headers;
  648. Headers trailers;
  649. std::string body;
  650. std::string location; // Redirect location
  651. bool has_header(const std::string &key) const;
  652. std::string get_header_value(const std::string &key, const char *def = "",
  653. size_t id = 0) const;
  654. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  655. size_t id = 0) const;
  656. size_t get_header_value_count(const std::string &key) const;
  657. void set_header(const std::string &key, const std::string &val);
  658. bool has_trailer(const std::string &key) const;
  659. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  660. size_t get_trailer_value_count(const std::string &key) const;
  661. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  662. void set_content(const char *s, size_t n, const std::string &content_type);
  663. void set_content(const std::string &s, const std::string &content_type);
  664. void set_content(std::string &&s, const std::string &content_type);
  665. void set_content_provider(
  666. size_t length, const std::string &content_type, ContentProvider provider,
  667. ContentProviderResourceReleaser resource_releaser = nullptr);
  668. void set_content_provider(
  669. const std::string &content_type, ContentProviderWithoutLength provider,
  670. ContentProviderResourceReleaser resource_releaser = nullptr);
  671. void set_chunked_content_provider(
  672. const std::string &content_type, ContentProviderWithoutLength provider,
  673. ContentProviderResourceReleaser resource_releaser = nullptr);
  674. void set_file_content(const std::string &path,
  675. const std::string &content_type);
  676. void set_file_content(const std::string &path);
  677. Response() = default;
  678. Response(const Response &) = default;
  679. Response &operator=(const Response &) = default;
  680. Response(Response &&) = default;
  681. Response &operator=(Response &&) = default;
  682. ~Response() {
  683. if (content_provider_resource_releaser_) {
  684. content_provider_resource_releaser_(content_provider_success_);
  685. }
  686. }
  687. // private members...
  688. size_t content_length_ = 0;
  689. ContentProvider content_provider_;
  690. ContentProviderResourceReleaser content_provider_resource_releaser_;
  691. bool is_chunked_content_provider_ = false;
  692. bool content_provider_success_ = false;
  693. std::string file_content_path_;
  694. std::string file_content_content_type_;
  695. };
  696. enum class Error {
  697. Success = 0,
  698. Unknown,
  699. Connection,
  700. BindIPAddress,
  701. Read,
  702. Write,
  703. ExceedRedirectCount,
  704. Canceled,
  705. SSLConnection,
  706. SSLLoadingCerts,
  707. SSLServerVerification,
  708. SSLServerHostnameVerification,
  709. UnsupportedMultipartBoundaryChars,
  710. Compression,
  711. ConnectionTimeout,
  712. ProxyConnection,
  713. ConnectionClosed,
  714. Timeout,
  715. ResourceExhaustion,
  716. TooManyFormDataFiles,
  717. ExceedMaxPayloadSize,
  718. ExceedUriMaxLength,
  719. ExceedMaxSocketDescriptorCount,
  720. InvalidRequestLine,
  721. InvalidHTTPMethod,
  722. InvalidHTTPVersion,
  723. InvalidHeaders,
  724. MultipartParsing,
  725. OpenFile,
  726. Listen,
  727. GetSockName,
  728. UnsupportedAddressFamily,
  729. HTTPParsing,
  730. InvalidRangeHeader,
  731. // For internal use only
  732. SSLPeerCouldBeClosed_,
  733. };
  734. std::string to_string(Error error);
  735. std::ostream &operator<<(std::ostream &os, const Error &obj);
  736. class Stream {
  737. public:
  738. virtual ~Stream() = default;
  739. virtual bool is_readable() const = 0;
  740. virtual bool wait_readable() const = 0;
  741. virtual bool wait_writable() const = 0;
  742. virtual ssize_t read(char *ptr, size_t size) = 0;
  743. virtual ssize_t write(const char *ptr, size_t size) = 0;
  744. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  745. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  746. virtual socket_t socket() const = 0;
  747. virtual time_t duration() const = 0;
  748. ssize_t write(const char *ptr);
  749. ssize_t write(const std::string &s);
  750. Error get_error() const { return error_; }
  751. protected:
  752. Error error_ = Error::Success;
  753. };
  754. class TaskQueue {
  755. public:
  756. TaskQueue() = default;
  757. virtual ~TaskQueue() = default;
  758. virtual bool enqueue(std::function<void()> fn) = 0;
  759. virtual void shutdown() = 0;
  760. virtual void on_idle() {}
  761. };
  762. class ThreadPool final : public TaskQueue {
  763. public:
  764. explicit ThreadPool(size_t n, size_t mqr = 0)
  765. : shutdown_(false), max_queued_requests_(mqr) {
  766. threads_.reserve(n);
  767. while (n) {
  768. threads_.emplace_back(worker(*this));
  769. n--;
  770. }
  771. }
  772. ThreadPool(const ThreadPool &) = delete;
  773. ~ThreadPool() override = default;
  774. bool enqueue(std::function<void()> fn) override {
  775. {
  776. std::unique_lock<std::mutex> lock(mutex_);
  777. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  778. return false;
  779. }
  780. jobs_.push_back(std::move(fn));
  781. }
  782. cond_.notify_one();
  783. return true;
  784. }
  785. void shutdown() override {
  786. // Stop all worker threads...
  787. {
  788. std::unique_lock<std::mutex> lock(mutex_);
  789. shutdown_ = true;
  790. }
  791. cond_.notify_all();
  792. // Join...
  793. for (auto &t : threads_) {
  794. t.join();
  795. }
  796. }
  797. private:
  798. struct worker {
  799. explicit worker(ThreadPool &pool) : pool_(pool) {}
  800. void operator()() {
  801. for (;;) {
  802. std::function<void()> fn;
  803. {
  804. std::unique_lock<std::mutex> lock(pool_.mutex_);
  805. pool_.cond_.wait(
  806. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  807. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  808. fn = pool_.jobs_.front();
  809. pool_.jobs_.pop_front();
  810. }
  811. assert(true == static_cast<bool>(fn));
  812. fn();
  813. }
  814. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  815. !defined(LIBRESSL_VERSION_NUMBER)
  816. OPENSSL_thread_stop();
  817. #endif
  818. }
  819. ThreadPool &pool_;
  820. };
  821. friend struct worker;
  822. std::vector<std::thread> threads_;
  823. std::list<std::function<void()>> jobs_;
  824. bool shutdown_;
  825. size_t max_queued_requests_ = 0;
  826. std::condition_variable cond_;
  827. std::mutex mutex_;
  828. };
  829. using Logger = std::function<void(const Request &, const Response &)>;
  830. // Forward declaration for Error type
  831. enum class Error;
  832. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  833. using SocketOptions = std::function<void(socket_t sock)>;
  834. void default_socket_options(socket_t sock);
  835. const char *status_message(int status);
  836. std::string to_string(Error error);
  837. std::ostream &operator<<(std::ostream &os, const Error &obj);
  838. std::string get_bearer_token_auth(const Request &req);
  839. namespace detail {
  840. class MatcherBase {
  841. public:
  842. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  843. virtual ~MatcherBase() = default;
  844. const std::string &pattern() const { return pattern_; }
  845. // Match request path and populate its matches and
  846. virtual bool match(Request &request) const = 0;
  847. private:
  848. std::string pattern_;
  849. };
  850. /**
  851. * Captures parameters in request path and stores them in Request::path_params
  852. *
  853. * Capture name is a substring of a pattern from : to /.
  854. * The rest of the pattern is matched against the request path directly
  855. * Parameters are captured starting from the next character after
  856. * the end of the last matched static pattern fragment until the next /.
  857. *
  858. * Example pattern:
  859. * "/path/fragments/:capture/more/fragments/:second_capture"
  860. * Static fragments:
  861. * "/path/fragments/", "more/fragments/"
  862. *
  863. * Given the following request path:
  864. * "/path/fragments/:1/more/fragments/:2"
  865. * the resulting capture will be
  866. * {{"capture", "1"}, {"second_capture", "2"}}
  867. */
  868. class PathParamsMatcher final : public MatcherBase {
  869. public:
  870. PathParamsMatcher(const std::string &pattern);
  871. bool match(Request &request) const override;
  872. private:
  873. // Treat segment separators as the end of path parameter capture
  874. // Does not need to handle query parameters as they are parsed before path
  875. // matching
  876. static constexpr char separator = '/';
  877. // Contains static path fragments to match against, excluding the '/' after
  878. // path params
  879. // Fragments are separated by path params
  880. std::vector<std::string> static_fragments_;
  881. // Stores the names of the path parameters to be used as keys in the
  882. // Request::path_params map
  883. std::vector<std::string> param_names_;
  884. };
  885. /**
  886. * Performs std::regex_match on request path
  887. * and stores the result in Request::matches
  888. *
  889. * Note that regex match is performed directly on the whole request.
  890. * This means that wildcard patterns may match multiple path segments with /:
  891. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  892. */
  893. class RegexMatcher final : public MatcherBase {
  894. public:
  895. RegexMatcher(const std::string &pattern)
  896. : MatcherBase(pattern), regex_(pattern) {}
  897. bool match(Request &request) const override;
  898. private:
  899. std::regex regex_;
  900. };
  901. int close_socket(socket_t sock);
  902. ssize_t write_headers(Stream &strm, const Headers &headers);
  903. } // namespace detail
  904. class Server {
  905. public:
  906. using Handler = std::function<void(const Request &, Response &)>;
  907. using ExceptionHandler =
  908. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  909. enum class HandlerResponse {
  910. Handled,
  911. Unhandled,
  912. };
  913. using HandlerWithResponse =
  914. std::function<HandlerResponse(const Request &, Response &)>;
  915. using HandlerWithContentReader = std::function<void(
  916. const Request &, Response &, const ContentReader &content_reader)>;
  917. using Expect100ContinueHandler =
  918. std::function<int(const Request &, Response &)>;
  919. Server();
  920. virtual ~Server();
  921. virtual bool is_valid() const;
  922. Server &Get(const std::string &pattern, Handler handler);
  923. Server &Post(const std::string &pattern, Handler handler);
  924. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  925. Server &Put(const std::string &pattern, Handler handler);
  926. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  927. Server &Patch(const std::string &pattern, Handler handler);
  928. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  929. Server &Delete(const std::string &pattern, Handler handler);
  930. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  931. Server &Options(const std::string &pattern, Handler handler);
  932. bool set_base_dir(const std::string &dir,
  933. const std::string &mount_point = std::string());
  934. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  935. Headers headers = Headers());
  936. bool remove_mount_point(const std::string &mount_point);
  937. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  938. const std::string &mime);
  939. Server &set_default_file_mimetype(const std::string &mime);
  940. Server &set_file_request_handler(Handler handler);
  941. template <class ErrorHandlerFunc>
  942. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  943. return set_error_handler_core(
  944. std::forward<ErrorHandlerFunc>(handler),
  945. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  946. }
  947. Server &set_exception_handler(ExceptionHandler handler);
  948. Server &set_pre_routing_handler(HandlerWithResponse handler);
  949. Server &set_post_routing_handler(Handler handler);
  950. Server &set_pre_request_handler(HandlerWithResponse handler);
  951. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  952. Server &set_logger(Logger logger);
  953. Server &set_pre_compression_logger(Logger logger);
  954. Server &set_error_logger(ErrorLogger error_logger);
  955. Server &set_address_family(int family);
  956. Server &set_tcp_nodelay(bool on);
  957. Server &set_ipv6_v6only(bool on);
  958. Server &set_socket_options(SocketOptions socket_options);
  959. Server &set_default_headers(Headers headers);
  960. Server &
  961. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  962. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  963. Server &set_keep_alive_max_count(size_t count);
  964. Server &set_keep_alive_timeout(time_t sec);
  965. Server &set_read_timeout(time_t sec, time_t usec = 0);
  966. template <class Rep, class Period>
  967. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  968. Server &set_write_timeout(time_t sec, time_t usec = 0);
  969. template <class Rep, class Period>
  970. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  971. Server &set_idle_interval(time_t sec, time_t usec = 0);
  972. template <class Rep, class Period>
  973. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  974. Server &set_payload_max_length(size_t length);
  975. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  976. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  977. bool listen_after_bind();
  978. bool listen(const std::string &host, int port, int socket_flags = 0);
  979. bool is_running() const;
  980. void wait_until_ready() const;
  981. void stop();
  982. void decommission();
  983. std::function<TaskQueue *(void)> new_task_queue;
  984. protected:
  985. bool process_request(Stream &strm, const std::string &remote_addr,
  986. int remote_port, const std::string &local_addr,
  987. int local_port, bool close_connection,
  988. bool &connection_closed,
  989. const std::function<void(Request &)> &setup_request);
  990. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  991. std::vector<std::string> trusted_proxies_;
  992. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  993. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  994. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  995. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  996. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  997. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  998. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  999. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1000. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1001. private:
  1002. using Handlers =
  1003. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1004. using HandlersForContentReader =
  1005. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1006. HandlerWithContentReader>>;
  1007. static std::unique_ptr<detail::MatcherBase>
  1008. make_matcher(const std::string &pattern);
  1009. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1010. Server &set_error_handler_core(Handler handler, std::false_type);
  1011. socket_t create_server_socket(const std::string &host, int port,
  1012. int socket_flags,
  1013. SocketOptions socket_options) const;
  1014. int bind_internal(const std::string &host, int port, int socket_flags);
  1015. bool listen_internal();
  1016. bool routing(Request &req, Response &res, Stream &strm);
  1017. bool handle_file_request(Request &req, Response &res);
  1018. bool check_if_not_modified(const Request &req, Response &res,
  1019. const std::string &etag, time_t mtime) const;
  1020. bool check_if_range(Request &req, const std::string &etag,
  1021. time_t mtime) const;
  1022. bool dispatch_request(Request &req, Response &res,
  1023. const Handlers &handlers) const;
  1024. bool dispatch_request_for_content_reader(
  1025. Request &req, Response &res, ContentReader content_reader,
  1026. const HandlersForContentReader &handlers) const;
  1027. bool parse_request_line(const char *s, Request &req) const;
  1028. void apply_ranges(const Request &req, Response &res,
  1029. std::string &content_type, std::string &boundary) const;
  1030. bool write_response(Stream &strm, bool close_connection, Request &req,
  1031. Response &res);
  1032. bool write_response_with_content(Stream &strm, bool close_connection,
  1033. const Request &req, Response &res);
  1034. bool write_response_core(Stream &strm, bool close_connection,
  1035. const Request &req, Response &res,
  1036. bool need_apply_ranges);
  1037. bool write_content_with_provider(Stream &strm, const Request &req,
  1038. Response &res, const std::string &boundary,
  1039. const std::string &content_type);
  1040. bool read_content(Stream &strm, Request &req, Response &res);
  1041. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1042. Response &res,
  1043. ContentReceiver receiver,
  1044. FormDataHeader multipart_header,
  1045. ContentReceiver multipart_receiver);
  1046. bool read_content_core(Stream &strm, Request &req, Response &res,
  1047. ContentReceiver receiver,
  1048. FormDataHeader multipart_header,
  1049. ContentReceiver multipart_receiver) const;
  1050. virtual bool process_and_close_socket(socket_t sock);
  1051. void output_log(const Request &req, const Response &res) const;
  1052. void output_pre_compression_log(const Request &req,
  1053. const Response &res) const;
  1054. void output_error_log(const Error &err, const Request *req) const;
  1055. std::atomic<bool> is_running_{false};
  1056. std::atomic<bool> is_decommissioned{false};
  1057. struct MountPointEntry {
  1058. std::string mount_point;
  1059. std::string base_dir;
  1060. Headers headers;
  1061. };
  1062. std::vector<MountPointEntry> base_dirs_;
  1063. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1064. std::string default_file_mimetype_ = "application/octet-stream";
  1065. Handler file_request_handler_;
  1066. Handlers get_handlers_;
  1067. Handlers post_handlers_;
  1068. HandlersForContentReader post_handlers_for_content_reader_;
  1069. Handlers put_handlers_;
  1070. HandlersForContentReader put_handlers_for_content_reader_;
  1071. Handlers patch_handlers_;
  1072. HandlersForContentReader patch_handlers_for_content_reader_;
  1073. Handlers delete_handlers_;
  1074. HandlersForContentReader delete_handlers_for_content_reader_;
  1075. Handlers options_handlers_;
  1076. HandlerWithResponse error_handler_;
  1077. ExceptionHandler exception_handler_;
  1078. HandlerWithResponse pre_routing_handler_;
  1079. Handler post_routing_handler_;
  1080. HandlerWithResponse pre_request_handler_;
  1081. Expect100ContinueHandler expect_100_continue_handler_;
  1082. mutable std::mutex logger_mutex_;
  1083. Logger logger_;
  1084. Logger pre_compression_logger_;
  1085. ErrorLogger error_logger_;
  1086. int address_family_ = AF_UNSPEC;
  1087. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1088. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1089. SocketOptions socket_options_ = default_socket_options;
  1090. Headers default_headers_;
  1091. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1092. detail::write_headers;
  1093. };
  1094. class Result {
  1095. public:
  1096. Result() = default;
  1097. Result(std::unique_ptr<Response> &&res, Error err,
  1098. Headers &&request_headers = Headers{})
  1099. : res_(std::move(res)), err_(err),
  1100. request_headers_(std::move(request_headers)) {}
  1101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1102. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1103. int ssl_error)
  1104. : res_(std::move(res)), err_(err),
  1105. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1106. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1107. int ssl_error, unsigned long ssl_openssl_error)
  1108. : res_(std::move(res)), err_(err),
  1109. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1110. ssl_openssl_error_(ssl_openssl_error) {}
  1111. #endif
  1112. // Response
  1113. operator bool() const { return res_ != nullptr; }
  1114. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1115. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1116. const Response &value() const { return *res_; }
  1117. Response &value() { return *res_; }
  1118. const Response &operator*() const { return *res_; }
  1119. Response &operator*() { return *res_; }
  1120. const Response *operator->() const { return res_.get(); }
  1121. Response *operator->() { return res_.get(); }
  1122. // Error
  1123. Error error() const { return err_; }
  1124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1125. // SSL Error
  1126. int ssl_error() const { return ssl_error_; }
  1127. // OpenSSL Error
  1128. unsigned long ssl_openssl_error() const { return ssl_openssl_error_; }
  1129. #endif
  1130. // Request Headers
  1131. bool has_request_header(const std::string &key) const;
  1132. std::string get_request_header_value(const std::string &key,
  1133. const char *def = "",
  1134. size_t id = 0) const;
  1135. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1136. size_t id = 0) const;
  1137. size_t get_request_header_value_count(const std::string &key) const;
  1138. private:
  1139. std::unique_ptr<Response> res_;
  1140. Error err_ = Error::Unknown;
  1141. Headers request_headers_;
  1142. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1143. int ssl_error_ = 0;
  1144. unsigned long ssl_openssl_error_ = 0;
  1145. #endif
  1146. };
  1147. struct ClientConnection {
  1148. socket_t sock = INVALID_SOCKET;
  1149. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1150. SSL *ssl = nullptr;
  1151. #endif
  1152. bool is_open() const { return sock != INVALID_SOCKET; }
  1153. ClientConnection() = default;
  1154. ~ClientConnection() {
  1155. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1156. if (ssl) {
  1157. SSL_free(ssl);
  1158. ssl = nullptr;
  1159. }
  1160. #endif
  1161. if (sock != INVALID_SOCKET) {
  1162. detail::close_socket(sock);
  1163. sock = INVALID_SOCKET;
  1164. }
  1165. }
  1166. ClientConnection(const ClientConnection &) = delete;
  1167. ClientConnection &operator=(const ClientConnection &) = delete;
  1168. ClientConnection(ClientConnection &&other) noexcept
  1169. : sock(other.sock)
  1170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1171. ,
  1172. ssl(other.ssl)
  1173. #endif
  1174. {
  1175. other.sock = INVALID_SOCKET;
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. other.ssl = nullptr;
  1178. #endif
  1179. }
  1180. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1181. if (this != &other) {
  1182. sock = other.sock;
  1183. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1184. ssl = other.ssl;
  1185. #endif
  1186. other.sock = INVALID_SOCKET;
  1187. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1188. other.ssl = nullptr;
  1189. #endif
  1190. }
  1191. return *this;
  1192. }
  1193. };
  1194. namespace detail {
  1195. struct ChunkedDecoder;
  1196. struct BodyReader {
  1197. Stream *stream = nullptr;
  1198. size_t content_length = 0;
  1199. size_t bytes_read = 0;
  1200. bool chunked = false;
  1201. bool eof = false;
  1202. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1203. Error last_error = Error::Success;
  1204. ssize_t read(char *buf, size_t len);
  1205. bool has_error() const { return last_error != Error::Success; }
  1206. };
  1207. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1208. size_t len) {
  1209. (void)stream;
  1210. return br.read(buf, len);
  1211. }
  1212. class decompressor;
  1213. } // namespace detail
  1214. class ClientImpl {
  1215. public:
  1216. explicit ClientImpl(const std::string &host);
  1217. explicit ClientImpl(const std::string &host, int port);
  1218. explicit ClientImpl(const std::string &host, int port,
  1219. const std::string &client_cert_path,
  1220. const std::string &client_key_path);
  1221. virtual ~ClientImpl();
  1222. virtual bool is_valid() const;
  1223. struct StreamHandle {
  1224. std::unique_ptr<Response> response;
  1225. Error error = Error::Success;
  1226. StreamHandle() = default;
  1227. StreamHandle(const StreamHandle &) = delete;
  1228. StreamHandle &operator=(const StreamHandle &) = delete;
  1229. StreamHandle(StreamHandle &&) = default;
  1230. StreamHandle &operator=(StreamHandle &&) = default;
  1231. ~StreamHandle() = default;
  1232. bool is_valid() const {
  1233. return response != nullptr && error == Error::Success;
  1234. }
  1235. ssize_t read(char *buf, size_t len);
  1236. void parse_trailers_if_needed();
  1237. Error get_read_error() const { return body_reader_.last_error; }
  1238. bool has_read_error() const { return body_reader_.has_error(); }
  1239. bool trailers_parsed_ = false;
  1240. private:
  1241. friend class ClientImpl;
  1242. ssize_t read_with_decompression(char *buf, size_t len);
  1243. std::unique_ptr<ClientConnection> connection_;
  1244. std::unique_ptr<Stream> socket_stream_;
  1245. Stream *stream_ = nullptr;
  1246. detail::BodyReader body_reader_;
  1247. std::unique_ptr<detail::decompressor> decompressor_;
  1248. std::string decompress_buffer_;
  1249. size_t decompress_offset_ = 0;
  1250. };
  1251. // clang-format off
  1252. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1253. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1254. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1255. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1256. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1257. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1258. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1259. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1260. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1261. Result Head(const std::string &path);
  1262. Result Head(const std::string &path, const Headers &headers);
  1263. Result Post(const std::string &path);
  1264. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1265. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1266. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1267. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1268. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1269. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1270. Result Post(const std::string &path, const Params &params);
  1271. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1272. Result Post(const std::string &path, const Headers &headers);
  1273. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1274. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1275. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1276. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1277. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1278. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1279. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1280. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1281. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1282. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1283. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1284. Result Put(const std::string &path);
  1285. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1286. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1287. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1288. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1289. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1290. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1291. Result Put(const std::string &path, const Params &params);
  1292. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1293. Result Put(const std::string &path, const Headers &headers);
  1294. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1295. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1296. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1297. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1298. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1299. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1300. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1301. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1302. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1303. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1304. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1305. Result Patch(const std::string &path);
  1306. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1307. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1308. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1309. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1310. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1311. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1312. Result Patch(const std::string &path, const Params &params);
  1313. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1314. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1315. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1316. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1317. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1318. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1319. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1320. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1321. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1322. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1323. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1324. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1325. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1326. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1327. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1328. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1329. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1330. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1331. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1332. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1333. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1334. Result Options(const std::string &path);
  1335. Result Options(const std::string &path, const Headers &headers);
  1336. // clang-format on
  1337. // Streaming API: Open a stream for reading response body incrementally
  1338. // Socket ownership is transferred to StreamHandle for true streaming
  1339. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1340. StreamHandle open_stream(const std::string &method, const std::string &path,
  1341. const Params &params = {},
  1342. const Headers &headers = {},
  1343. const std::string &body = {},
  1344. const std::string &content_type = {});
  1345. bool send(Request &req, Response &res, Error &error);
  1346. Result send(const Request &req);
  1347. void stop();
  1348. std::string host() const;
  1349. int port() const;
  1350. size_t is_socket_open() const;
  1351. socket_t socket() const;
  1352. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1353. void set_default_headers(Headers headers);
  1354. void
  1355. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1356. void set_address_family(int family);
  1357. void set_tcp_nodelay(bool on);
  1358. void set_ipv6_v6only(bool on);
  1359. void set_socket_options(SocketOptions socket_options);
  1360. void set_connection_timeout(time_t sec, time_t usec = 0);
  1361. template <class Rep, class Period>
  1362. void
  1363. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1364. void set_read_timeout(time_t sec, time_t usec = 0);
  1365. template <class Rep, class Period>
  1366. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1367. void set_write_timeout(time_t sec, time_t usec = 0);
  1368. template <class Rep, class Period>
  1369. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1370. void set_max_timeout(time_t msec);
  1371. template <class Rep, class Period>
  1372. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1373. void set_basic_auth(const std::string &username, const std::string &password);
  1374. void set_bearer_token_auth(const std::string &token);
  1375. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1376. void set_digest_auth(const std::string &username,
  1377. const std::string &password);
  1378. #endif
  1379. void set_keep_alive(bool on);
  1380. void set_follow_location(bool on);
  1381. void set_path_encode(bool on);
  1382. void set_compress(bool on);
  1383. void set_decompress(bool on);
  1384. void set_interface(const std::string &intf);
  1385. void set_proxy(const std::string &host, int port);
  1386. void set_proxy_basic_auth(const std::string &username,
  1387. const std::string &password);
  1388. void set_proxy_bearer_token_auth(const std::string &token);
  1389. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1390. void set_proxy_digest_auth(const std::string &username,
  1391. const std::string &password);
  1392. #endif
  1393. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1394. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1395. const std::string &ca_cert_dir_path = std::string());
  1396. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1397. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1398. #endif
  1399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1400. void enable_server_certificate_verification(bool enabled);
  1401. void enable_server_hostname_verification(bool enabled);
  1402. void set_server_certificate_verifier(
  1403. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1404. #endif
  1405. void set_logger(Logger logger);
  1406. void set_error_logger(ErrorLogger error_logger);
  1407. protected:
  1408. struct Socket {
  1409. socket_t sock = INVALID_SOCKET;
  1410. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1411. SSL *ssl = nullptr;
  1412. #endif
  1413. bool is_open() const { return sock != INVALID_SOCKET; }
  1414. };
  1415. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1416. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1417. // All of:
  1418. // shutdown_ssl
  1419. // shutdown_socket
  1420. // close_socket
  1421. // should ONLY be called when socket_mutex_ is locked.
  1422. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1423. // with a DIFFERENT thread sending requests using that socket.
  1424. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1425. void shutdown_socket(Socket &socket) const;
  1426. void close_socket(Socket &socket);
  1427. bool process_request(Stream &strm, Request &req, Response &res,
  1428. bool close_connection, Error &error);
  1429. bool write_content_with_provider(Stream &strm, const Request &req,
  1430. Error &error) const;
  1431. void copy_settings(const ClientImpl &rhs);
  1432. void output_log(const Request &req, const Response &res) const;
  1433. void output_error_log(const Error &err, const Request *req) const;
  1434. // Socket endpoint information
  1435. const std::string host_;
  1436. const int port_;
  1437. // Current open socket
  1438. Socket socket_;
  1439. mutable std::mutex socket_mutex_;
  1440. std::recursive_mutex request_mutex_;
  1441. // These are all protected under socket_mutex
  1442. size_t socket_requests_in_flight_ = 0;
  1443. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1444. bool socket_should_be_closed_when_request_is_done_ = false;
  1445. // Hostname-IP map
  1446. std::map<std::string, std::string> addr_map_;
  1447. // Default headers
  1448. Headers default_headers_;
  1449. // Header writer
  1450. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1451. detail::write_headers;
  1452. // Settings
  1453. std::string client_cert_path_;
  1454. std::string client_key_path_;
  1455. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1456. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1457. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1458. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1459. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1460. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1461. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1462. std::string basic_auth_username_;
  1463. std::string basic_auth_password_;
  1464. std::string bearer_token_auth_token_;
  1465. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1466. std::string digest_auth_username_;
  1467. std::string digest_auth_password_;
  1468. #endif
  1469. bool keep_alive_ = false;
  1470. bool follow_location_ = false;
  1471. bool path_encode_ = true;
  1472. int address_family_ = AF_UNSPEC;
  1473. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1474. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1475. SocketOptions socket_options_ = nullptr;
  1476. bool compress_ = false;
  1477. bool decompress_ = true;
  1478. std::string interface_;
  1479. std::string proxy_host_;
  1480. int proxy_port_ = -1;
  1481. std::string proxy_basic_auth_username_;
  1482. std::string proxy_basic_auth_password_;
  1483. std::string proxy_bearer_token_auth_token_;
  1484. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1485. std::string proxy_digest_auth_username_;
  1486. std::string proxy_digest_auth_password_;
  1487. #endif
  1488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1489. std::string ca_cert_file_path_;
  1490. std::string ca_cert_dir_path_;
  1491. X509_STORE *ca_cert_store_ = nullptr;
  1492. #endif
  1493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1494. bool server_certificate_verification_ = true;
  1495. bool server_hostname_verification_ = true;
  1496. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1497. #endif
  1498. mutable std::mutex logger_mutex_;
  1499. Logger logger_;
  1500. ErrorLogger error_logger_;
  1501. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1502. int last_ssl_error_ = 0;
  1503. unsigned long last_openssl_error_ = 0;
  1504. #endif
  1505. private:
  1506. bool send_(Request &req, Response &res, Error &error);
  1507. Result send_(Request &&req);
  1508. socket_t create_client_socket(Error &error) const;
  1509. bool read_response_line(Stream &strm, const Request &req,
  1510. Response &res) const;
  1511. bool write_request(Stream &strm, Request &req, bool close_connection,
  1512. Error &error);
  1513. void prepare_default_headers(Request &r, bool for_stream,
  1514. const std::string &ct);
  1515. bool redirect(Request &req, Response &res, Error &error);
  1516. bool create_redirect_client(const std::string &scheme,
  1517. const std::string &host, int port, Request &req,
  1518. Response &res, const std::string &path,
  1519. const std::string &location, Error &error);
  1520. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1521. bool handle_request(Stream &strm, Request &req, Response &res,
  1522. bool close_connection, Error &error);
  1523. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  1524. Request &req, const char *body, size_t content_length,
  1525. ContentProvider content_provider,
  1526. ContentProviderWithoutLength content_provider_without_length,
  1527. const std::string &content_type, ContentReceiver content_receiver,
  1528. Error &error);
  1529. Result send_with_content_provider_and_receiver(
  1530. const std::string &method, const std::string &path,
  1531. const Headers &headers, const char *body, size_t content_length,
  1532. ContentProvider content_provider,
  1533. ContentProviderWithoutLength content_provider_without_length,
  1534. const std::string &content_type, ContentReceiver content_receiver,
  1535. UploadProgress progress);
  1536. ContentProviderWithoutLength get_multipart_content_provider(
  1537. const std::string &boundary, const UploadFormDataItems &items,
  1538. const FormDataProviderItems &provider_items) const;
  1539. virtual bool
  1540. process_socket(const Socket &socket,
  1541. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1542. std::function<bool(Stream &strm)> callback);
  1543. virtual bool is_ssl() const;
  1544. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  1545. };
  1546. class Client {
  1547. public:
  1548. // Universal interface
  1549. explicit Client(const std::string &scheme_host_port);
  1550. explicit Client(const std::string &scheme_host_port,
  1551. const std::string &client_cert_path,
  1552. const std::string &client_key_path);
  1553. // HTTP only interface
  1554. explicit Client(const std::string &host, int port);
  1555. explicit Client(const std::string &host, int port,
  1556. const std::string &client_cert_path,
  1557. const std::string &client_key_path);
  1558. Client(Client &&) = default;
  1559. Client &operator=(Client &&) = default;
  1560. ~Client();
  1561. bool is_valid() const;
  1562. // clang-format off
  1563. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1564. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1565. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1566. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1567. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1568. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1569. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1570. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1571. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1572. Result Head(const std::string &path);
  1573. Result Head(const std::string &path, const Headers &headers);
  1574. Result Post(const std::string &path);
  1575. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1576. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1577. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1578. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1579. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1580. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1581. Result Post(const std::string &path, const Params &params);
  1582. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1583. Result Post(const std::string &path, const Headers &headers);
  1584. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1585. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1586. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1587. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1588. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1589. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1590. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1591. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1592. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1593. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1594. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1595. Result Put(const std::string &path);
  1596. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1597. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1598. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1599. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1600. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1601. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1602. Result Put(const std::string &path, const Params &params);
  1603. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1604. Result Put(const std::string &path, const Headers &headers);
  1605. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1606. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1607. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1608. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1609. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1610. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1611. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1612. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1613. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1614. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1615. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1616. Result Patch(const std::string &path);
  1617. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1618. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1619. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1620. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1621. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1622. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1623. Result Patch(const std::string &path, const Params &params);
  1624. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1625. Result Patch(const std::string &path, const Headers &headers);
  1626. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1627. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1628. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1629. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1630. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1631. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1632. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1633. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1634. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1635. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1636. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1637. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1638. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1639. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1640. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1641. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1642. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1643. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1644. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1645. Result Options(const std::string &path);
  1646. Result Options(const std::string &path, const Headers &headers);
  1647. // clang-format on
  1648. // Streaming API: Open a stream for reading response body incrementally
  1649. // Socket ownership is transferred to StreamHandle for true streaming
  1650. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1651. ClientImpl::StreamHandle open_stream(const std::string &method,
  1652. const std::string &path,
  1653. const Params &params = {},
  1654. const Headers &headers = {},
  1655. const std::string &body = {},
  1656. const std::string &content_type = {});
  1657. bool send(Request &req, Response &res, Error &error);
  1658. Result send(const Request &req);
  1659. void stop();
  1660. std::string host() const;
  1661. int port() const;
  1662. size_t is_socket_open() const;
  1663. socket_t socket() const;
  1664. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1665. void set_default_headers(Headers headers);
  1666. void
  1667. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1668. void set_address_family(int family);
  1669. void set_tcp_nodelay(bool on);
  1670. void set_socket_options(SocketOptions socket_options);
  1671. void set_connection_timeout(time_t sec, time_t usec = 0);
  1672. template <class Rep, class Period>
  1673. void
  1674. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1675. void set_read_timeout(time_t sec, time_t usec = 0);
  1676. template <class Rep, class Period>
  1677. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1678. void set_write_timeout(time_t sec, time_t usec = 0);
  1679. template <class Rep, class Period>
  1680. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1681. void set_max_timeout(time_t msec);
  1682. template <class Rep, class Period>
  1683. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1684. void set_basic_auth(const std::string &username, const std::string &password);
  1685. void set_bearer_token_auth(const std::string &token);
  1686. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1687. void set_digest_auth(const std::string &username,
  1688. const std::string &password);
  1689. #endif
  1690. void set_keep_alive(bool on);
  1691. void set_follow_location(bool on);
  1692. void set_path_encode(bool on);
  1693. void set_url_encode(bool on);
  1694. void set_compress(bool on);
  1695. void set_decompress(bool on);
  1696. void set_interface(const std::string &intf);
  1697. void set_proxy(const std::string &host, int port);
  1698. void set_proxy_basic_auth(const std::string &username,
  1699. const std::string &password);
  1700. void set_proxy_bearer_token_auth(const std::string &token);
  1701. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1702. void set_proxy_digest_auth(const std::string &username,
  1703. const std::string &password);
  1704. #endif
  1705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1706. void enable_server_certificate_verification(bool enabled);
  1707. void enable_server_hostname_verification(bool enabled);
  1708. void set_server_certificate_verifier(
  1709. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1710. #endif
  1711. void set_logger(Logger logger);
  1712. void set_error_logger(ErrorLogger error_logger);
  1713. // SSL
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1716. const std::string &ca_cert_dir_path = std::string());
  1717. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1718. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1719. long get_openssl_verify_result() const;
  1720. SSL_CTX *ssl_context() const;
  1721. #endif
  1722. private:
  1723. std::unique_ptr<ClientImpl> cli_;
  1724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1725. bool is_ssl_ = false;
  1726. #endif
  1727. };
  1728. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1729. class SSLServer : public Server {
  1730. public:
  1731. SSLServer(const char *cert_path, const char *private_key_path,
  1732. const char *client_ca_cert_file_path = nullptr,
  1733. const char *client_ca_cert_dir_path = nullptr,
  1734. const char *private_key_password = nullptr);
  1735. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1736. X509_STORE *client_ca_cert_store = nullptr);
  1737. SSLServer(
  1738. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1739. ~SSLServer() override;
  1740. bool is_valid() const override;
  1741. SSL_CTX *ssl_context() const;
  1742. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1743. X509_STORE *client_ca_cert_store = nullptr);
  1744. int ssl_last_error() const { return last_ssl_error_; }
  1745. private:
  1746. bool process_and_close_socket(socket_t sock) override;
  1747. STACK_OF(X509_NAME) * extract_ca_names_from_x509_store(X509_STORE *store);
  1748. SSL_CTX *ctx_;
  1749. std::mutex ctx_mutex_;
  1750. int last_ssl_error_ = 0;
  1751. };
  1752. class SSLClient final : public ClientImpl {
  1753. public:
  1754. explicit SSLClient(const std::string &host);
  1755. explicit SSLClient(const std::string &host, int port);
  1756. explicit SSLClient(const std::string &host, int port,
  1757. const std::string &client_cert_path,
  1758. const std::string &client_key_path,
  1759. const std::string &private_key_password = std::string());
  1760. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1761. EVP_PKEY *client_key,
  1762. const std::string &private_key_password = std::string());
  1763. ~SSLClient() override;
  1764. bool is_valid() const override;
  1765. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1766. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1767. long get_openssl_verify_result() const;
  1768. SSL_CTX *ssl_context() const;
  1769. private:
  1770. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1771. bool ensure_socket_connection(Socket &socket, Error &error) override;
  1772. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1773. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1774. bool
  1775. process_socket(const Socket &socket,
  1776. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1777. std::function<bool(Stream &strm)> callback) override;
  1778. bool is_ssl() const override;
  1779. bool connect_with_proxy(
  1780. Socket &sock,
  1781. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1782. Response &res, bool &success, Error &error);
  1783. bool initialize_ssl(Socket &socket, Error &error);
  1784. bool load_certs();
  1785. bool verify_host(X509 *server_cert) const;
  1786. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1787. bool verify_host_with_common_name(X509 *server_cert) const;
  1788. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1789. SSL_CTX *ctx_;
  1790. std::mutex ctx_mutex_;
  1791. std::once_flag initialize_cert_;
  1792. std::vector<std::string> host_components_;
  1793. long verify_result_ = 0;
  1794. friend class ClientImpl;
  1795. };
  1796. #endif
  1797. /*
  1798. * Implementation of template methods.
  1799. */
  1800. namespace detail {
  1801. template <typename T, typename U>
  1802. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1803. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1804. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1805. duration - std::chrono::seconds(sec))
  1806. .count();
  1807. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1808. }
  1809. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1810. return N - 1;
  1811. }
  1812. inline bool is_numeric(const std::string &str) {
  1813. return !str.empty() &&
  1814. std::all_of(str.cbegin(), str.cend(),
  1815. [](unsigned char c) { return std::isdigit(c); });
  1816. }
  1817. inline size_t get_header_value_u64(const Headers &headers,
  1818. const std::string &key, size_t def,
  1819. size_t id, bool &is_invalid_value) {
  1820. is_invalid_value = false;
  1821. auto rng = headers.equal_range(key);
  1822. auto it = rng.first;
  1823. std::advance(it, static_cast<ssize_t>(id));
  1824. if (it != rng.second) {
  1825. if (is_numeric(it->second)) {
  1826. return std::strtoull(it->second.data(), nullptr, 10);
  1827. } else {
  1828. is_invalid_value = true;
  1829. }
  1830. }
  1831. return def;
  1832. }
  1833. inline size_t get_header_value_u64(const Headers &headers,
  1834. const std::string &key, size_t def,
  1835. size_t id) {
  1836. auto dummy = false;
  1837. return get_header_value_u64(headers, key, def, id, dummy);
  1838. }
  1839. } // namespace detail
  1840. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1841. size_t id) const {
  1842. return detail::get_header_value_u64(headers, key, def, id);
  1843. }
  1844. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1845. size_t id) const {
  1846. return detail::get_header_value_u64(headers, key, def, id);
  1847. }
  1848. namespace detail {
  1849. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1850. const void *optval, socklen_t optlen) {
  1851. return setsockopt(sock, level, optname,
  1852. #ifdef _WIN32
  1853. reinterpret_cast<const char *>(optval),
  1854. #else
  1855. optval,
  1856. #endif
  1857. optlen) == 0;
  1858. }
  1859. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1860. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1861. }
  1862. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1863. time_t sec, time_t usec) {
  1864. #ifdef _WIN32
  1865. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1866. #else
  1867. timeval timeout;
  1868. timeout.tv_sec = static_cast<long>(sec);
  1869. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1870. #endif
  1871. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1872. }
  1873. } // namespace detail
  1874. inline void default_socket_options(socket_t sock) {
  1875. detail::set_socket_opt(sock, SOL_SOCKET,
  1876. #ifdef SO_REUSEPORT
  1877. SO_REUSEPORT,
  1878. #else
  1879. SO_REUSEADDR,
  1880. #endif
  1881. 1);
  1882. }
  1883. inline std::string get_bearer_token_auth(const Request &req) {
  1884. if (req.has_header("Authorization")) {
  1885. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1886. return req.get_header_value("Authorization")
  1887. .substr(bearer_header_prefix_len);
  1888. }
  1889. return "";
  1890. }
  1891. template <class Rep, class Period>
  1892. inline Server &
  1893. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1894. detail::duration_to_sec_and_usec(
  1895. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1896. return *this;
  1897. }
  1898. template <class Rep, class Period>
  1899. inline Server &
  1900. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1901. detail::duration_to_sec_and_usec(
  1902. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1903. return *this;
  1904. }
  1905. template <class Rep, class Period>
  1906. inline Server &
  1907. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1908. detail::duration_to_sec_and_usec(
  1909. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1910. return *this;
  1911. }
  1912. inline size_t Result::get_request_header_value_u64(const std::string &key,
  1913. size_t def,
  1914. size_t id) const {
  1915. return detail::get_header_value_u64(request_headers_, key, def, id);
  1916. }
  1917. template <class Rep, class Period>
  1918. inline void ClientImpl::set_connection_timeout(
  1919. const std::chrono::duration<Rep, Period> &duration) {
  1920. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1921. set_connection_timeout(sec, usec);
  1922. });
  1923. }
  1924. template <class Rep, class Period>
  1925. inline void ClientImpl::set_read_timeout(
  1926. const std::chrono::duration<Rep, Period> &duration) {
  1927. detail::duration_to_sec_and_usec(
  1928. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1929. }
  1930. template <class Rep, class Period>
  1931. inline void ClientImpl::set_write_timeout(
  1932. const std::chrono::duration<Rep, Period> &duration) {
  1933. detail::duration_to_sec_and_usec(
  1934. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1935. }
  1936. template <class Rep, class Period>
  1937. inline void ClientImpl::set_max_timeout(
  1938. const std::chrono::duration<Rep, Period> &duration) {
  1939. auto msec =
  1940. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1941. set_max_timeout(msec);
  1942. }
  1943. template <class Rep, class Period>
  1944. inline void Client::set_connection_timeout(
  1945. const std::chrono::duration<Rep, Period> &duration) {
  1946. cli_->set_connection_timeout(duration);
  1947. }
  1948. template <class Rep, class Period>
  1949. inline void
  1950. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1951. cli_->set_read_timeout(duration);
  1952. }
  1953. template <class Rep, class Period>
  1954. inline void
  1955. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1956. cli_->set_write_timeout(duration);
  1957. }
  1958. inline void Client::set_max_timeout(time_t msec) {
  1959. cli_->set_max_timeout(msec);
  1960. }
  1961. template <class Rep, class Period>
  1962. inline void
  1963. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1964. cli_->set_max_timeout(duration);
  1965. }
  1966. /*
  1967. * Forward declarations and types that will be part of the .h file if split into
  1968. * .h + .cc.
  1969. */
  1970. std::string hosted_at(const std::string &hostname);
  1971. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1972. // JavaScript-style URL encoding/decoding functions
  1973. std::string encode_uri_component(const std::string &value);
  1974. std::string encode_uri(const std::string &value);
  1975. std::string decode_uri_component(const std::string &value);
  1976. std::string decode_uri(const std::string &value);
  1977. // RFC 3986 compliant URL component encoding/decoding functions
  1978. std::string encode_path_component(const std::string &component);
  1979. std::string decode_path_component(const std::string &component);
  1980. std::string encode_query_component(const std::string &component,
  1981. bool space_as_plus = true);
  1982. std::string decode_query_component(const std::string &component,
  1983. bool plus_as_space = true);
  1984. std::string append_query_params(const std::string &path, const Params &params);
  1985. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1986. std::pair<std::string, std::string>
  1987. make_basic_authentication_header(const std::string &username,
  1988. const std::string &password,
  1989. bool is_proxy = false);
  1990. namespace detail {
  1991. #if defined(_WIN32)
  1992. inline std::wstring u8string_to_wstring(const char *s) {
  1993. if (!s) { return std::wstring(); }
  1994. auto len = static_cast<int>(strlen(s));
  1995. if (!len) { return std::wstring(); }
  1996. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  1997. if (!wlen) { return std::wstring(); }
  1998. std::wstring ws;
  1999. ws.resize(wlen);
  2000. wlen = ::MultiByteToWideChar(
  2001. CP_UTF8, 0, s, len,
  2002. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2003. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2004. return ws;
  2005. }
  2006. #endif
  2007. struct FileStat {
  2008. FileStat(const std::string &path);
  2009. bool is_file() const;
  2010. bool is_dir() const;
  2011. time_t mtime() const;
  2012. size_t size() const;
  2013. private:
  2014. #if defined(_WIN32)
  2015. struct _stat st_;
  2016. #else
  2017. struct stat st_;
  2018. #endif
  2019. int ret_ = -1;
  2020. };
  2021. std::string make_host_and_port_string(const std::string &host, int port,
  2022. bool is_ssl);
  2023. std::string trim_copy(const std::string &s);
  2024. void divide(
  2025. const char *data, std::size_t size, char d,
  2026. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2027. fn);
  2028. void divide(
  2029. const std::string &str, char d,
  2030. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2031. fn);
  2032. void split(const char *b, const char *e, char d,
  2033. std::function<void(const char *, const char *)> fn);
  2034. void split(const char *b, const char *e, char d, size_t m,
  2035. std::function<void(const char *, const char *)> fn);
  2036. bool process_client_socket(
  2037. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2038. time_t write_timeout_sec, time_t write_timeout_usec,
  2039. time_t max_timeout_msec,
  2040. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2041. std::function<bool(Stream &)> callback);
  2042. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2043. int port, int address_family, bool tcp_nodelay,
  2044. bool ipv6_v6only, SocketOptions socket_options,
  2045. time_t connection_timeout_sec,
  2046. time_t connection_timeout_usec,
  2047. time_t read_timeout_sec, time_t read_timeout_usec,
  2048. time_t write_timeout_sec,
  2049. time_t write_timeout_usec,
  2050. const std::string &intf, Error &error);
  2051. const char *get_header_value(const Headers &headers, const std::string &key,
  2052. const char *def, size_t id);
  2053. std::string params_to_query_str(const Params &params);
  2054. void parse_query_text(const char *data, std::size_t size, Params &params);
  2055. void parse_query_text(const std::string &s, Params &params);
  2056. bool parse_multipart_boundary(const std::string &content_type,
  2057. std::string &boundary);
  2058. bool parse_range_header(const std::string &s, Ranges &ranges);
  2059. bool parse_accept_header(const std::string &s,
  2060. std::vector<std::string> &content_types);
  2061. int close_socket(socket_t sock);
  2062. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2063. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2064. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2065. EncodingType encoding_type(const Request &req, const Response &res);
  2066. class BufferStream final : public Stream {
  2067. public:
  2068. BufferStream() = default;
  2069. ~BufferStream() override = default;
  2070. bool is_readable() const override;
  2071. bool wait_readable() const override;
  2072. bool wait_writable() const override;
  2073. ssize_t read(char *ptr, size_t size) override;
  2074. ssize_t write(const char *ptr, size_t size) override;
  2075. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2076. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2077. socket_t socket() const override;
  2078. time_t duration() const override;
  2079. const std::string &get_buffer() const;
  2080. private:
  2081. std::string buffer;
  2082. size_t position = 0;
  2083. };
  2084. class compressor {
  2085. public:
  2086. virtual ~compressor() = default;
  2087. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2088. virtual bool compress(const char *data, size_t data_length, bool last,
  2089. Callback callback) = 0;
  2090. };
  2091. class decompressor {
  2092. public:
  2093. virtual ~decompressor() = default;
  2094. virtual bool is_valid() const = 0;
  2095. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2096. virtual bool decompress(const char *data, size_t data_length,
  2097. Callback callback) = 0;
  2098. };
  2099. class nocompressor final : public compressor {
  2100. public:
  2101. ~nocompressor() override = default;
  2102. bool compress(const char *data, size_t data_length, bool /*last*/,
  2103. Callback callback) override;
  2104. };
  2105. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2106. class gzip_compressor final : public compressor {
  2107. public:
  2108. gzip_compressor();
  2109. ~gzip_compressor() override;
  2110. bool compress(const char *data, size_t data_length, bool last,
  2111. Callback callback) override;
  2112. private:
  2113. bool is_valid_ = false;
  2114. z_stream strm_;
  2115. };
  2116. class gzip_decompressor final : public decompressor {
  2117. public:
  2118. gzip_decompressor();
  2119. ~gzip_decompressor() override;
  2120. bool is_valid() const override;
  2121. bool decompress(const char *data, size_t data_length,
  2122. Callback callback) override;
  2123. private:
  2124. bool is_valid_ = false;
  2125. z_stream strm_;
  2126. };
  2127. #endif
  2128. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2129. class brotli_compressor final : public compressor {
  2130. public:
  2131. brotli_compressor();
  2132. ~brotli_compressor();
  2133. bool compress(const char *data, size_t data_length, bool last,
  2134. Callback callback) override;
  2135. private:
  2136. BrotliEncoderState *state_ = nullptr;
  2137. };
  2138. class brotli_decompressor final : public decompressor {
  2139. public:
  2140. brotli_decompressor();
  2141. ~brotli_decompressor();
  2142. bool is_valid() const override;
  2143. bool decompress(const char *data, size_t data_length,
  2144. Callback callback) override;
  2145. private:
  2146. BrotliDecoderResult decoder_r;
  2147. BrotliDecoderState *decoder_s = nullptr;
  2148. };
  2149. #endif
  2150. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2151. class zstd_compressor : public compressor {
  2152. public:
  2153. zstd_compressor();
  2154. ~zstd_compressor();
  2155. bool compress(const char *data, size_t data_length, bool last,
  2156. Callback callback) override;
  2157. private:
  2158. ZSTD_CCtx *ctx_ = nullptr;
  2159. };
  2160. class zstd_decompressor : public decompressor {
  2161. public:
  2162. zstd_decompressor();
  2163. ~zstd_decompressor();
  2164. bool is_valid() const override;
  2165. bool decompress(const char *data, size_t data_length,
  2166. Callback callback) override;
  2167. private:
  2168. ZSTD_DCtx *ctx_ = nullptr;
  2169. };
  2170. #endif
  2171. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2172. // to store data. The call can set memory on stack for performance.
  2173. class stream_line_reader {
  2174. public:
  2175. stream_line_reader(Stream &strm, char *fixed_buffer,
  2176. size_t fixed_buffer_size);
  2177. const char *ptr() const;
  2178. size_t size() const;
  2179. bool end_with_crlf() const;
  2180. bool getline();
  2181. private:
  2182. void append(char c);
  2183. Stream &strm_;
  2184. char *fixed_buffer_;
  2185. const size_t fixed_buffer_size_;
  2186. size_t fixed_buffer_used_size_ = 0;
  2187. std::string growable_buffer_;
  2188. };
  2189. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2190. const Headers &src_headers);
  2191. struct ChunkedDecoder {
  2192. Stream &strm;
  2193. size_t chunk_remaining = 0;
  2194. bool finished = false;
  2195. char line_buf[64];
  2196. size_t last_chunk_total = 0;
  2197. size_t last_chunk_offset = 0;
  2198. explicit ChunkedDecoder(Stream &s);
  2199. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2200. size_t &out_chunk_total);
  2201. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2202. };
  2203. class mmap {
  2204. public:
  2205. mmap(const char *path);
  2206. ~mmap();
  2207. bool open(const char *path);
  2208. void close();
  2209. bool is_open() const;
  2210. size_t size() const;
  2211. const char *data() const;
  2212. private:
  2213. #if defined(_WIN32)
  2214. HANDLE hFile_ = NULL;
  2215. HANDLE hMapping_ = NULL;
  2216. #else
  2217. int fd_ = -1;
  2218. #endif
  2219. size_t size_ = 0;
  2220. void *addr_ = nullptr;
  2221. bool is_open_empty_file = false;
  2222. };
  2223. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2224. namespace fields {
  2225. bool is_token_char(char c);
  2226. bool is_token(const std::string &s);
  2227. bool is_field_name(const std::string &s);
  2228. bool is_vchar(char c);
  2229. bool is_obs_text(char c);
  2230. bool is_field_vchar(char c);
  2231. bool is_field_content(const std::string &s);
  2232. bool is_field_value(const std::string &s);
  2233. } // namespace fields
  2234. } // namespace detail
  2235. namespace stream {
  2236. class Result {
  2237. public:
  2238. Result() : chunk_size_(8192) {}
  2239. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192)
  2240. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  2241. Result(Result &&other) noexcept
  2242. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  2243. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  2244. finished_(other.finished_) {
  2245. other.current_size_ = 0;
  2246. other.finished_ = true;
  2247. }
  2248. Result &operator=(Result &&other) noexcept {
  2249. if (this != &other) {
  2250. handle_ = std::move(other.handle_);
  2251. buffer_ = std::move(other.buffer_);
  2252. current_size_ = other.current_size_;
  2253. chunk_size_ = other.chunk_size_;
  2254. finished_ = other.finished_;
  2255. other.current_size_ = 0;
  2256. other.finished_ = true;
  2257. }
  2258. return *this;
  2259. }
  2260. Result(const Result &) = delete;
  2261. Result &operator=(const Result &) = delete;
  2262. // Check if the result is valid (connection succeeded and response received)
  2263. bool is_valid() const { return handle_.is_valid(); }
  2264. explicit operator bool() const { return is_valid(); }
  2265. // Response status code
  2266. int status() const {
  2267. return handle_.response ? handle_.response->status : -1;
  2268. }
  2269. // Response headers
  2270. const Headers &headers() const {
  2271. static const Headers empty_headers;
  2272. return handle_.response ? handle_.response->headers : empty_headers;
  2273. }
  2274. std::string get_header_value(const std::string &key,
  2275. const char *def = "") const {
  2276. return handle_.response ? handle_.response->get_header_value(key, def)
  2277. : def;
  2278. }
  2279. bool has_header(const std::string &key) const {
  2280. return handle_.response ? handle_.response->has_header(key) : false;
  2281. }
  2282. // Error information
  2283. Error error() const { return handle_.error; }
  2284. Error read_error() const { return handle_.get_read_error(); }
  2285. bool has_read_error() const { return handle_.has_read_error(); }
  2286. // Streaming iteration API
  2287. // Call next() to read the next chunk, then access data via data()/size()
  2288. // Returns true if data was read, false when stream is exhausted
  2289. bool next() {
  2290. if (!handle_.is_valid() || finished_) { return false; }
  2291. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  2292. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  2293. if (n > 0) {
  2294. current_size_ = static_cast<size_t>(n);
  2295. return true;
  2296. }
  2297. current_size_ = 0;
  2298. finished_ = true;
  2299. return false;
  2300. }
  2301. // Pointer to current chunk data (valid after next() returns true)
  2302. const char *data() const { return buffer_.data(); }
  2303. // Size of current chunk (valid after next() returns true)
  2304. size_t size() const { return current_size_; }
  2305. // Convenience method: read all remaining data into a string
  2306. std::string read_all() {
  2307. std::string result;
  2308. while (next()) {
  2309. result.append(data(), size());
  2310. }
  2311. return result;
  2312. }
  2313. private:
  2314. ClientImpl::StreamHandle handle_;
  2315. std::string buffer_;
  2316. size_t current_size_ = 0;
  2317. size_t chunk_size_;
  2318. bool finished_ = false;
  2319. };
  2320. // GET
  2321. template <typename ClientType>
  2322. inline Result Get(ClientType &cli, const std::string &path,
  2323. size_t chunk_size = 8192) {
  2324. return Result{cli.open_stream("GET", path), chunk_size};
  2325. }
  2326. template <typename ClientType>
  2327. inline Result Get(ClientType &cli, const std::string &path,
  2328. const Headers &headers, size_t chunk_size = 8192) {
  2329. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2330. }
  2331. template <typename ClientType>
  2332. inline Result Get(ClientType &cli, const std::string &path,
  2333. const Params &params, size_t chunk_size = 8192) {
  2334. return Result{cli.open_stream("GET", path, params), chunk_size};
  2335. }
  2336. template <typename ClientType>
  2337. inline Result Get(ClientType &cli, const std::string &path,
  2338. const Params &params, const Headers &headers,
  2339. size_t chunk_size = 8192) {
  2340. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2341. }
  2342. // POST
  2343. template <typename ClientType>
  2344. inline Result Post(ClientType &cli, const std::string &path,
  2345. const std::string &body, const std::string &content_type,
  2346. size_t chunk_size = 8192) {
  2347. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2348. chunk_size};
  2349. }
  2350. template <typename ClientType>
  2351. inline Result Post(ClientType &cli, const std::string &path,
  2352. const Headers &headers, const std::string &body,
  2353. const std::string &content_type, size_t chunk_size = 8192) {
  2354. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2355. chunk_size};
  2356. }
  2357. template <typename ClientType>
  2358. inline Result Post(ClientType &cli, const std::string &path,
  2359. const Params &params, const std::string &body,
  2360. const std::string &content_type, size_t chunk_size = 8192) {
  2361. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2362. chunk_size};
  2363. }
  2364. template <typename ClientType>
  2365. inline Result Post(ClientType &cli, const std::string &path,
  2366. const Params &params, const Headers &headers,
  2367. const std::string &body, const std::string &content_type,
  2368. size_t chunk_size = 8192) {
  2369. return Result{
  2370. cli.open_stream("POST", path, params, headers, body, content_type),
  2371. chunk_size};
  2372. }
  2373. // PUT
  2374. template <typename ClientType>
  2375. inline Result Put(ClientType &cli, const std::string &path,
  2376. const std::string &body, const std::string &content_type,
  2377. size_t chunk_size = 8192) {
  2378. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2379. chunk_size};
  2380. }
  2381. template <typename ClientType>
  2382. inline Result Put(ClientType &cli, const std::string &path,
  2383. const Headers &headers, const std::string &body,
  2384. const std::string &content_type, size_t chunk_size = 8192) {
  2385. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2386. chunk_size};
  2387. }
  2388. template <typename ClientType>
  2389. inline Result Put(ClientType &cli, const std::string &path,
  2390. const Params &params, const std::string &body,
  2391. const std::string &content_type, size_t chunk_size = 8192) {
  2392. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2393. chunk_size};
  2394. }
  2395. template <typename ClientType>
  2396. inline Result Put(ClientType &cli, const std::string &path,
  2397. const Params &params, const Headers &headers,
  2398. const std::string &body, const std::string &content_type,
  2399. size_t chunk_size = 8192) {
  2400. return Result{
  2401. cli.open_stream("PUT", path, params, headers, body, content_type),
  2402. chunk_size};
  2403. }
  2404. // PATCH
  2405. template <typename ClientType>
  2406. inline Result Patch(ClientType &cli, const std::string &path,
  2407. const std::string &body, const std::string &content_type,
  2408. size_t chunk_size = 8192) {
  2409. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2410. chunk_size};
  2411. }
  2412. template <typename ClientType>
  2413. inline Result Patch(ClientType &cli, const std::string &path,
  2414. const Headers &headers, const std::string &body,
  2415. const std::string &content_type, size_t chunk_size = 8192) {
  2416. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2417. chunk_size};
  2418. }
  2419. template <typename ClientType>
  2420. inline Result Patch(ClientType &cli, const std::string &path,
  2421. const Params &params, const std::string &body,
  2422. const std::string &content_type, size_t chunk_size = 8192) {
  2423. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2424. chunk_size};
  2425. }
  2426. template <typename ClientType>
  2427. inline Result Patch(ClientType &cli, const std::string &path,
  2428. const Params &params, const Headers &headers,
  2429. const std::string &body, const std::string &content_type,
  2430. size_t chunk_size = 8192) {
  2431. return Result{
  2432. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2433. chunk_size};
  2434. }
  2435. // DELETE
  2436. template <typename ClientType>
  2437. inline Result Delete(ClientType &cli, const std::string &path,
  2438. size_t chunk_size = 8192) {
  2439. return Result{cli.open_stream("DELETE", path), chunk_size};
  2440. }
  2441. template <typename ClientType>
  2442. inline Result Delete(ClientType &cli, const std::string &path,
  2443. const Headers &headers, size_t chunk_size = 8192) {
  2444. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2445. }
  2446. template <typename ClientType>
  2447. inline Result Delete(ClientType &cli, const std::string &path,
  2448. const std::string &body, const std::string &content_type,
  2449. size_t chunk_size = 8192) {
  2450. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2451. chunk_size};
  2452. }
  2453. template <typename ClientType>
  2454. inline Result Delete(ClientType &cli, const std::string &path,
  2455. const Headers &headers, const std::string &body,
  2456. const std::string &content_type,
  2457. size_t chunk_size = 8192) {
  2458. return Result{
  2459. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2460. chunk_size};
  2461. }
  2462. template <typename ClientType>
  2463. inline Result Delete(ClientType &cli, const std::string &path,
  2464. const Params &params, size_t chunk_size = 8192) {
  2465. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2466. }
  2467. template <typename ClientType>
  2468. inline Result Delete(ClientType &cli, const std::string &path,
  2469. const Params &params, const Headers &headers,
  2470. size_t chunk_size = 8192) {
  2471. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  2472. }
  2473. template <typename ClientType>
  2474. inline Result Delete(ClientType &cli, const std::string &path,
  2475. const Params &params, const std::string &body,
  2476. const std::string &content_type,
  2477. size_t chunk_size = 8192) {
  2478. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  2479. chunk_size};
  2480. }
  2481. template <typename ClientType>
  2482. inline Result Delete(ClientType &cli, const std::string &path,
  2483. const Params &params, const Headers &headers,
  2484. const std::string &body, const std::string &content_type,
  2485. size_t chunk_size = 8192) {
  2486. return Result{
  2487. cli.open_stream("DELETE", path, params, headers, body, content_type),
  2488. chunk_size};
  2489. }
  2490. // HEAD
  2491. template <typename ClientType>
  2492. inline Result Head(ClientType &cli, const std::string &path,
  2493. size_t chunk_size = 8192) {
  2494. return Result{cli.open_stream("HEAD", path), chunk_size};
  2495. }
  2496. template <typename ClientType>
  2497. inline Result Head(ClientType &cli, const std::string &path,
  2498. const Headers &headers, size_t chunk_size = 8192) {
  2499. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  2500. }
  2501. template <typename ClientType>
  2502. inline Result Head(ClientType &cli, const std::string &path,
  2503. const Params &params, size_t chunk_size = 8192) {
  2504. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  2505. }
  2506. template <typename ClientType>
  2507. inline Result Head(ClientType &cli, const std::string &path,
  2508. const Params &params, const Headers &headers,
  2509. size_t chunk_size = 8192) {
  2510. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  2511. }
  2512. // OPTIONS
  2513. template <typename ClientType>
  2514. inline Result Options(ClientType &cli, const std::string &path,
  2515. size_t chunk_size = 8192) {
  2516. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  2517. }
  2518. template <typename ClientType>
  2519. inline Result Options(ClientType &cli, const std::string &path,
  2520. const Headers &headers, size_t chunk_size = 8192) {
  2521. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  2522. }
  2523. template <typename ClientType>
  2524. inline Result Options(ClientType &cli, const std::string &path,
  2525. const Params &params, size_t chunk_size = 8192) {
  2526. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  2527. }
  2528. template <typename ClientType>
  2529. inline Result Options(ClientType &cli, const std::string &path,
  2530. const Params &params, const Headers &headers,
  2531. size_t chunk_size = 8192) {
  2532. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  2533. }
  2534. } // namespace stream
  2535. namespace sse {
  2536. struct SSEMessage {
  2537. std::string event; // Event type (default: "message")
  2538. std::string data; // Event payload
  2539. std::string id; // Event ID for Last-Event-ID header
  2540. SSEMessage() : event("message") {}
  2541. void clear() {
  2542. event = "message";
  2543. data.clear();
  2544. id.clear();
  2545. }
  2546. };
  2547. class SSEClient {
  2548. public:
  2549. using MessageHandler = std::function<void(const SSEMessage &)>;
  2550. using ErrorHandler = std::function<void(Error)>;
  2551. using OpenHandler = std::function<void()>;
  2552. SSEClient(Client &client, const std::string &path)
  2553. : client_(client), path_(path) {}
  2554. SSEClient(Client &client, const std::string &path, const Headers &headers)
  2555. : client_(client), path_(path), headers_(headers) {}
  2556. ~SSEClient() { stop(); }
  2557. SSEClient(const SSEClient &) = delete;
  2558. SSEClient &operator=(const SSEClient &) = delete;
  2559. // Event handlers
  2560. SSEClient &on_message(MessageHandler handler) {
  2561. on_message_ = std::move(handler);
  2562. return *this;
  2563. }
  2564. SSEClient &on_event(const std::string &type, MessageHandler handler) {
  2565. event_handlers_[type] = std::move(handler);
  2566. return *this;
  2567. }
  2568. SSEClient &on_open(OpenHandler handler) {
  2569. on_open_ = std::move(handler);
  2570. return *this;
  2571. }
  2572. SSEClient &on_error(ErrorHandler handler) {
  2573. on_error_ = std::move(handler);
  2574. return *this;
  2575. }
  2576. SSEClient &set_reconnect_interval(int ms) {
  2577. reconnect_interval_ms_ = ms;
  2578. return *this;
  2579. }
  2580. SSEClient &set_max_reconnect_attempts(int n) {
  2581. max_reconnect_attempts_ = n;
  2582. return *this;
  2583. }
  2584. // State accessors
  2585. bool is_connected() const { return connected_.load(); }
  2586. const std::string &last_event_id() const { return last_event_id_; }
  2587. // Blocking start - runs event loop with auto-reconnect
  2588. void start() {
  2589. running_.store(true);
  2590. run_event_loop();
  2591. }
  2592. // Non-blocking start - runs in background thread
  2593. void start_async() {
  2594. running_.store(true);
  2595. async_thread_ = std::thread([this]() { run_event_loop(); });
  2596. }
  2597. // Stop the client (thread-safe)
  2598. void stop() {
  2599. running_.store(false);
  2600. client_.stop(); // Cancel any pending operations
  2601. if (async_thread_.joinable()) { async_thread_.join(); }
  2602. }
  2603. private:
  2604. // Parse a single SSE field line
  2605. // Returns true if this line ends an event (blank line)
  2606. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms) {
  2607. // Blank line signals end of event
  2608. if (line.empty() || line == "\r") { return true; }
  2609. // Lines starting with ':' are comments (ignored)
  2610. if (!line.empty() && line[0] == ':') { return false; }
  2611. // Find the colon separator
  2612. auto colon_pos = line.find(':');
  2613. if (colon_pos == std::string::npos) {
  2614. // Line with no colon is treated as field name with empty value
  2615. return false;
  2616. }
  2617. auto field = line.substr(0, colon_pos);
  2618. std::string value;
  2619. // Value starts after colon, skip optional single space
  2620. if (colon_pos + 1 < line.size()) {
  2621. auto value_start = colon_pos + 1;
  2622. if (line[value_start] == ' ') { value_start++; }
  2623. value = line.substr(value_start);
  2624. // Remove trailing \r if present
  2625. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  2626. }
  2627. // Handle known fields
  2628. if (field == "event") {
  2629. msg.event = value;
  2630. } else if (field == "data") {
  2631. // Multiple data lines are concatenated with newlines
  2632. if (!msg.data.empty()) { msg.data += "\n"; }
  2633. msg.data += value;
  2634. } else if (field == "id") {
  2635. // Empty id is valid (clears the last event ID)
  2636. msg.id = value;
  2637. } else if (field == "retry") {
  2638. // Parse retry interval in milliseconds
  2639. try {
  2640. retry_ms = std::stoi(value);
  2641. } catch (...) {
  2642. // Invalid retry value, ignore
  2643. }
  2644. }
  2645. // Unknown fields are ignored per SSE spec
  2646. return false;
  2647. }
  2648. // Main event loop with auto-reconnect
  2649. void run_event_loop() {
  2650. auto reconnect_count = 0;
  2651. while (running_.load()) {
  2652. // Build headers, including Last-Event-ID if we have one
  2653. auto request_headers = headers_;
  2654. if (!last_event_id_.empty()) {
  2655. request_headers.emplace("Last-Event-ID", last_event_id_);
  2656. }
  2657. // Open streaming connection
  2658. auto result = stream::Get(client_, path_, request_headers);
  2659. // Connection error handling
  2660. if (!result) {
  2661. connected_.store(false);
  2662. if (on_error_) { on_error_(result.error()); }
  2663. if (!should_reconnect(reconnect_count)) { break; }
  2664. wait_for_reconnect();
  2665. reconnect_count++;
  2666. continue;
  2667. }
  2668. if (result.status() != 200) {
  2669. connected_.store(false);
  2670. // For certain errors, don't reconnect
  2671. if (result.status() == 204 || // No Content - server wants us to stop
  2672. result.status() == 404 || // Not Found
  2673. result.status() == 401 || // Unauthorized
  2674. result.status() == 403) { // Forbidden
  2675. if (on_error_) { on_error_(Error::Connection); }
  2676. break;
  2677. }
  2678. if (on_error_) { on_error_(Error::Connection); }
  2679. if (!should_reconnect(reconnect_count)) { break; }
  2680. wait_for_reconnect();
  2681. reconnect_count++;
  2682. continue;
  2683. }
  2684. // Connection successful
  2685. connected_.store(true);
  2686. reconnect_count = 0;
  2687. if (on_open_) { on_open_(); }
  2688. // Event receiving loop
  2689. std::string buffer;
  2690. SSEMessage current_msg;
  2691. while (running_.load() && result.next()) {
  2692. buffer.append(result.data(), result.size());
  2693. // Process complete lines in the buffer
  2694. size_t line_start = 0;
  2695. size_t newline_pos;
  2696. while ((newline_pos = buffer.find('\n', line_start)) !=
  2697. std::string::npos) {
  2698. auto line = buffer.substr(line_start, newline_pos - line_start);
  2699. line_start = newline_pos + 1;
  2700. // Parse the line and check if event is complete
  2701. auto event_complete =
  2702. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  2703. if (event_complete && !current_msg.data.empty()) {
  2704. // Update last_event_id for reconnection
  2705. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  2706. // Dispatch event to appropriate handler
  2707. dispatch_event(current_msg);
  2708. current_msg.clear();
  2709. }
  2710. }
  2711. // Keep unprocessed data in buffer
  2712. buffer.erase(0, line_start);
  2713. }
  2714. // Connection ended
  2715. connected_.store(false);
  2716. if (!running_.load()) { break; }
  2717. // Check for read errors
  2718. if (result.has_read_error()) {
  2719. if (on_error_) { on_error_(result.read_error()); }
  2720. }
  2721. if (!should_reconnect(reconnect_count)) { break; }
  2722. wait_for_reconnect();
  2723. reconnect_count++;
  2724. }
  2725. connected_.store(false);
  2726. }
  2727. // Dispatch event to appropriate handler
  2728. void dispatch_event(const SSEMessage &msg) {
  2729. // Check for specific event type handler first
  2730. auto it = event_handlers_.find(msg.event);
  2731. if (it != event_handlers_.end()) {
  2732. it->second(msg);
  2733. return;
  2734. }
  2735. // Fall back to generic message handler
  2736. if (on_message_) { on_message_(msg); }
  2737. }
  2738. // Check if we should attempt to reconnect
  2739. bool should_reconnect(int count) const {
  2740. if (!running_.load()) { return false; }
  2741. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  2742. return count < max_reconnect_attempts_;
  2743. }
  2744. // Wait for reconnect interval
  2745. void wait_for_reconnect() {
  2746. // Use small increments to check running_ flag frequently
  2747. auto waited = 0;
  2748. while (running_.load() && waited < reconnect_interval_ms_) {
  2749. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2750. waited += 100;
  2751. }
  2752. }
  2753. // Client and path
  2754. Client &client_;
  2755. std::string path_;
  2756. Headers headers_;
  2757. // Callbacks
  2758. MessageHandler on_message_;
  2759. std::map<std::string, MessageHandler> event_handlers_;
  2760. OpenHandler on_open_;
  2761. ErrorHandler on_error_;
  2762. // Configuration
  2763. int reconnect_interval_ms_ = 3000;
  2764. int max_reconnect_attempts_ = 0; // 0 = unlimited
  2765. // State
  2766. std::atomic<bool> running_{false};
  2767. std::atomic<bool> connected_{false};
  2768. std::string last_event_id_;
  2769. // Async support
  2770. std::thread async_thread_;
  2771. };
  2772. } // namespace sse
  2773. // ----------------------------------------------------------------------------
  2774. /*
  2775. * Implementation that will be part of the .cc file if split into .h + .cc.
  2776. */
  2777. namespace detail {
  2778. inline bool is_hex(char c, int &v) {
  2779. if (isdigit(c)) {
  2780. v = c - '0';
  2781. return true;
  2782. } else if ('A' <= c && c <= 'F') {
  2783. v = c - 'A' + 10;
  2784. return true;
  2785. } else if ('a' <= c && c <= 'f') {
  2786. v = c - 'a' + 10;
  2787. return true;
  2788. }
  2789. return false;
  2790. }
  2791. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2792. int &val) {
  2793. if (i >= s.size()) { return false; }
  2794. val = 0;
  2795. for (; cnt; i++, cnt--) {
  2796. if (!s[i]) { return false; }
  2797. auto v = 0;
  2798. if (is_hex(s[i], v)) {
  2799. val = val * 16 + v;
  2800. } else {
  2801. return false;
  2802. }
  2803. }
  2804. return true;
  2805. }
  2806. inline std::string from_i_to_hex(size_t n) {
  2807. static const auto charset = "0123456789abcdef";
  2808. std::string ret;
  2809. do {
  2810. ret = charset[n & 15] + ret;
  2811. n >>= 4;
  2812. } while (n > 0);
  2813. return ret;
  2814. }
  2815. inline std::string compute_etag(const FileStat &fs) {
  2816. if (!fs.is_file()) { return std::string(); }
  2817. // If mtime cannot be determined (negative value indicates an error
  2818. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  2819. // value like 0 could collide with a real file that legitimately has
  2820. // mtime == 0 (epoch) and lead to misleading validators.
  2821. auto mtime_raw = fs.mtime();
  2822. if (mtime_raw < 0) { return std::string(); }
  2823. auto mtime = static_cast<size_t>(mtime_raw);
  2824. auto size = fs.size();
  2825. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  2826. from_i_to_hex(size) + "\"";
  2827. }
  2828. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  2829. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  2830. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  2831. inline std::string file_mtime_to_http_date(time_t mtime) {
  2832. if (mtime < 0) { return std::string(); }
  2833. struct tm tm_buf;
  2834. #ifdef _WIN32
  2835. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  2836. #else
  2837. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  2838. #endif
  2839. char buf[64];
  2840. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  2841. return std::string();
  2842. }
  2843. return std::string(buf);
  2844. }
  2845. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  2846. inline time_t parse_http_date(const std::string &date_str) {
  2847. struct tm tm_buf;
  2848. // Create a classic locale object once for all parsing attempts
  2849. const std::locale classic_locale = std::locale::classic();
  2850. // Try to parse using std::get_time (C++11, cross-platform)
  2851. auto try_parse = [&](const char *fmt) -> bool {
  2852. std::istringstream ss(date_str);
  2853. ss.imbue(classic_locale);
  2854. memset(&tm_buf, 0, sizeof(tm_buf));
  2855. ss >> std::get_time(&tm_buf, fmt);
  2856. return !ss.fail();
  2857. };
  2858. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  2859. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  2860. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  2861. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  2862. // asctime format: "Sun Nov 6 08:49:37 1994"
  2863. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  2864. return static_cast<time_t>(-1);
  2865. }
  2866. }
  2867. }
  2868. #ifdef _WIN32
  2869. return _mkgmtime(&tm_buf);
  2870. #else
  2871. return timegm(&tm_buf);
  2872. #endif
  2873. }
  2874. inline bool is_weak_etag(const std::string &s) {
  2875. // Check if the string is a weak ETag (starts with 'W/"')
  2876. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  2877. }
  2878. inline bool is_strong_etag(const std::string &s) {
  2879. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  2880. // chars)
  2881. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  2882. }
  2883. inline size_t to_utf8(int code, char *buff) {
  2884. if (code < 0x0080) {
  2885. buff[0] = static_cast<char>(code & 0x7F);
  2886. return 1;
  2887. } else if (code < 0x0800) {
  2888. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2889. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2890. return 2;
  2891. } else if (code < 0xD800) {
  2892. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2893. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2894. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2895. return 3;
  2896. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2897. return 0;
  2898. } else if (code < 0x10000) {
  2899. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2900. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2901. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2902. return 3;
  2903. } else if (code < 0x110000) {
  2904. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2905. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2906. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2907. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2908. return 4;
  2909. }
  2910. // NOTREACHED
  2911. return 0;
  2912. }
  2913. // NOTE: This code came up with the following stackoverflow post:
  2914. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2915. inline std::string base64_encode(const std::string &in) {
  2916. static const auto lookup =
  2917. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2918. std::string out;
  2919. out.reserve(in.size());
  2920. auto val = 0;
  2921. auto valb = -6;
  2922. for (auto c : in) {
  2923. val = (val << 8) + static_cast<uint8_t>(c);
  2924. valb += 8;
  2925. while (valb >= 0) {
  2926. out.push_back(lookup[(val >> valb) & 0x3F]);
  2927. valb -= 6;
  2928. }
  2929. }
  2930. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  2931. while (out.size() % 4) {
  2932. out.push_back('=');
  2933. }
  2934. return out;
  2935. }
  2936. inline bool is_valid_path(const std::string &path) {
  2937. size_t level = 0;
  2938. size_t i = 0;
  2939. // Skip slash
  2940. while (i < path.size() && path[i] == '/') {
  2941. i++;
  2942. }
  2943. while (i < path.size()) {
  2944. // Read component
  2945. auto beg = i;
  2946. while (i < path.size() && path[i] != '/') {
  2947. if (path[i] == '\0') {
  2948. return false;
  2949. } else if (path[i] == '\\') {
  2950. return false;
  2951. }
  2952. i++;
  2953. }
  2954. auto len = i - beg;
  2955. assert(len > 0);
  2956. if (!path.compare(beg, len, ".")) {
  2957. ;
  2958. } else if (!path.compare(beg, len, "..")) {
  2959. if (level == 0) { return false; }
  2960. level--;
  2961. } else {
  2962. level++;
  2963. }
  2964. // Skip slash
  2965. while (i < path.size() && path[i] == '/') {
  2966. i++;
  2967. }
  2968. }
  2969. return true;
  2970. }
  2971. inline FileStat::FileStat(const std::string &path) {
  2972. #if defined(_WIN32)
  2973. auto wpath = u8string_to_wstring(path.c_str());
  2974. ret_ = _wstat(wpath.c_str(), &st_);
  2975. #else
  2976. ret_ = stat(path.c_str(), &st_);
  2977. #endif
  2978. }
  2979. inline bool FileStat::is_file() const {
  2980. return ret_ >= 0 && S_ISREG(st_.st_mode);
  2981. }
  2982. inline bool FileStat::is_dir() const {
  2983. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  2984. }
  2985. inline time_t FileStat::mtime() const {
  2986. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  2987. : static_cast<time_t>(-1);
  2988. }
  2989. inline size_t FileStat::size() const {
  2990. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  2991. }
  2992. inline std::string encode_path(const std::string &s) {
  2993. std::string result;
  2994. result.reserve(s.size());
  2995. for (size_t i = 0; s[i]; i++) {
  2996. switch (s[i]) {
  2997. case ' ': result += "%20"; break;
  2998. case '+': result += "%2B"; break;
  2999. case '\r': result += "%0D"; break;
  3000. case '\n': result += "%0A"; break;
  3001. case '\'': result += "%27"; break;
  3002. case ',': result += "%2C"; break;
  3003. // case ':': result += "%3A"; break; // ok? probably...
  3004. case ';': result += "%3B"; break;
  3005. default:
  3006. auto c = static_cast<uint8_t>(s[i]);
  3007. if (c >= 0x80) {
  3008. result += '%';
  3009. char hex[4];
  3010. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  3011. assert(len == 2);
  3012. result.append(hex, static_cast<size_t>(len));
  3013. } else {
  3014. result += s[i];
  3015. }
  3016. break;
  3017. }
  3018. }
  3019. return result;
  3020. }
  3021. inline std::string file_extension(const std::string &path) {
  3022. std::smatch m;
  3023. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  3024. if (std::regex_search(path, m, re)) { return m[1].str(); }
  3025. return std::string();
  3026. }
  3027. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  3028. template <typename T>
  3029. inline bool parse_header(const char *beg, const char *end, T fn);
  3030. template <typename T>
  3031. inline bool parse_header(const char *beg, const char *end, T fn) {
  3032. // Skip trailing spaces and tabs.
  3033. while (beg < end && is_space_or_tab(end[-1])) {
  3034. end--;
  3035. }
  3036. auto p = beg;
  3037. while (p < end && *p != ':') {
  3038. p++;
  3039. }
  3040. auto name = std::string(beg, p);
  3041. if (!detail::fields::is_field_name(name)) { return false; }
  3042. if (p == end) { return false; }
  3043. auto key_end = p;
  3044. if (*p++ != ':') { return false; }
  3045. while (p < end && is_space_or_tab(*p)) {
  3046. p++;
  3047. }
  3048. if (p <= end) {
  3049. auto key_len = key_end - beg;
  3050. if (!key_len) { return false; }
  3051. auto key = std::string(beg, key_end);
  3052. auto val = std::string(p, end);
  3053. if (!detail::fields::is_field_value(val)) { return false; }
  3054. if (case_ignore::equal(key, "Location") ||
  3055. case_ignore::equal(key, "Referer")) {
  3056. fn(key, val);
  3057. } else {
  3058. fn(key, decode_path_component(val));
  3059. }
  3060. return true;
  3061. }
  3062. return false;
  3063. }
  3064. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  3065. const Headers &src_headers) {
  3066. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3067. // transfer coding is complete when a chunk with a chunk-size of zero is
  3068. // received, possibly followed by a trailer section, and finally terminated by
  3069. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3070. //
  3071. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3072. // doesn't care for the existence of the final CRLF. In other words, it seems
  3073. // to be ok whether the final CRLF exists or not in the chunked data.
  3074. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3075. //
  3076. // According to the reference code in RFC 9112, cpp-httplib now allows
  3077. // chunked transfer coding data without the final CRLF.
  3078. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3079. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3080. "transfer-encoding",
  3081. "content-length",
  3082. "host",
  3083. "authorization",
  3084. "www-authenticate",
  3085. "proxy-authenticate",
  3086. "proxy-authorization",
  3087. "cookie",
  3088. "set-cookie",
  3089. "cache-control",
  3090. "expect",
  3091. "max-forwards",
  3092. "pragma",
  3093. "range",
  3094. "te",
  3095. "age",
  3096. "expires",
  3097. "date",
  3098. "location",
  3099. "retry-after",
  3100. "vary",
  3101. "warning",
  3102. "content-encoding",
  3103. "content-type",
  3104. "content-range",
  3105. "trailer"};
  3106. case_ignore::unordered_set<std::string> declared_trailers;
  3107. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  3108. if (trailer_header && std::strlen(trailer_header)) {
  3109. auto len = std::strlen(trailer_header);
  3110. split(trailer_header, trailer_header + len, ',',
  3111. [&](const char *b, const char *e) {
  3112. const char *kbeg = b;
  3113. const char *kend = e;
  3114. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  3115. ++kbeg;
  3116. }
  3117. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  3118. --kend;
  3119. }
  3120. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  3121. if (!key.empty() &&
  3122. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3123. declared_trailers.insert(key);
  3124. }
  3125. });
  3126. }
  3127. size_t trailer_header_count = 0;
  3128. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3129. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3130. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3131. constexpr auto line_terminator_len = 2;
  3132. auto line_beg = line_reader.ptr();
  3133. auto line_end =
  3134. line_reader.ptr() + line_reader.size() - line_terminator_len;
  3135. if (!parse_header(line_beg, line_end,
  3136. [&](const std::string &key, const std::string &val) {
  3137. if (declared_trailers.find(key) !=
  3138. declared_trailers.end()) {
  3139. dest.emplace(key, val);
  3140. trailer_header_count++;
  3141. }
  3142. })) {
  3143. return false;
  3144. }
  3145. if (!line_reader.getline()) { return false; }
  3146. }
  3147. return true;
  3148. }
  3149. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  3150. size_t right) {
  3151. while (b + left < e && is_space_or_tab(b[left])) {
  3152. left++;
  3153. }
  3154. while (right > 0 && is_space_or_tab(b[right - 1])) {
  3155. right--;
  3156. }
  3157. return std::make_pair(left, right);
  3158. }
  3159. inline std::string trim_copy(const std::string &s) {
  3160. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  3161. return s.substr(r.first, r.second - r.first);
  3162. }
  3163. inline std::string trim_double_quotes_copy(const std::string &s) {
  3164. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  3165. return s.substr(1, s.size() - 2);
  3166. }
  3167. return s;
  3168. }
  3169. inline void
  3170. divide(const char *data, std::size_t size, char d,
  3171. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3172. fn) {
  3173. const auto it = std::find(data, data + size, d);
  3174. const auto found = static_cast<std::size_t>(it != data + size);
  3175. const auto lhs_data = data;
  3176. const auto lhs_size = static_cast<std::size_t>(it - data);
  3177. const auto rhs_data = it + found;
  3178. const auto rhs_size = size - lhs_size - found;
  3179. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  3180. }
  3181. inline void
  3182. divide(const std::string &str, char d,
  3183. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  3184. fn) {
  3185. divide(str.data(), str.size(), d, std::move(fn));
  3186. }
  3187. inline void split(const char *b, const char *e, char d,
  3188. std::function<void(const char *, const char *)> fn) {
  3189. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  3190. }
  3191. inline void split(const char *b, const char *e, char d, size_t m,
  3192. std::function<void(const char *, const char *)> fn) {
  3193. size_t i = 0;
  3194. size_t beg = 0;
  3195. size_t count = 1;
  3196. while (e ? (b + i < e) : (b[i] != '\0')) {
  3197. if (b[i] == d && count < m) {
  3198. auto r = trim(b, e, beg, i);
  3199. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3200. beg = i + 1;
  3201. count++;
  3202. }
  3203. i++;
  3204. }
  3205. if (i) {
  3206. auto r = trim(b, e, beg, i);
  3207. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  3208. }
  3209. }
  3210. inline bool split_find(const char *b, const char *e, char d, size_t m,
  3211. std::function<bool(const char *, const char *)> fn) {
  3212. size_t i = 0;
  3213. size_t beg = 0;
  3214. size_t count = 1;
  3215. while (e ? (b + i < e) : (b[i] != '\0')) {
  3216. if (b[i] == d && count < m) {
  3217. auto r = trim(b, e, beg, i);
  3218. if (r.first < r.second) {
  3219. auto found = fn(&b[r.first], &b[r.second]);
  3220. if (found) { return true; }
  3221. }
  3222. beg = i + 1;
  3223. count++;
  3224. }
  3225. i++;
  3226. }
  3227. if (i) {
  3228. auto r = trim(b, e, beg, i);
  3229. if (r.first < r.second) {
  3230. auto found = fn(&b[r.first], &b[r.second]);
  3231. if (found) { return true; }
  3232. }
  3233. }
  3234. return false;
  3235. }
  3236. inline bool split_find(const char *b, const char *e, char d,
  3237. std::function<bool(const char *, const char *)> fn) {
  3238. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  3239. std::move(fn));
  3240. }
  3241. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  3242. size_t fixed_buffer_size)
  3243. : strm_(strm), fixed_buffer_(fixed_buffer),
  3244. fixed_buffer_size_(fixed_buffer_size) {}
  3245. inline const char *stream_line_reader::ptr() const {
  3246. if (growable_buffer_.empty()) {
  3247. return fixed_buffer_;
  3248. } else {
  3249. return growable_buffer_.data();
  3250. }
  3251. }
  3252. inline size_t stream_line_reader::size() const {
  3253. if (growable_buffer_.empty()) {
  3254. return fixed_buffer_used_size_;
  3255. } else {
  3256. return growable_buffer_.size();
  3257. }
  3258. }
  3259. inline bool stream_line_reader::end_with_crlf() const {
  3260. auto end = ptr() + size();
  3261. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  3262. }
  3263. inline bool stream_line_reader::getline() {
  3264. fixed_buffer_used_size_ = 0;
  3265. growable_buffer_.clear();
  3266. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3267. char prev_byte = 0;
  3268. #endif
  3269. for (size_t i = 0;; i++) {
  3270. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  3271. // Treat exceptionally long lines as an error to
  3272. // prevent infinite loops/memory exhaustion
  3273. return false;
  3274. }
  3275. char byte;
  3276. auto n = strm_.read(&byte, 1);
  3277. if (n < 0) {
  3278. return false;
  3279. } else if (n == 0) {
  3280. if (i == 0) {
  3281. return false;
  3282. } else {
  3283. break;
  3284. }
  3285. }
  3286. append(byte);
  3287. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3288. if (byte == '\n') { break; }
  3289. #else
  3290. if (prev_byte == '\r' && byte == '\n') { break; }
  3291. prev_byte = byte;
  3292. #endif
  3293. }
  3294. return true;
  3295. }
  3296. inline void stream_line_reader::append(char c) {
  3297. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  3298. fixed_buffer_[fixed_buffer_used_size_++] = c;
  3299. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  3300. } else {
  3301. if (growable_buffer_.empty()) {
  3302. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  3303. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  3304. }
  3305. growable_buffer_ += c;
  3306. }
  3307. }
  3308. inline mmap::mmap(const char *path) { open(path); }
  3309. inline mmap::~mmap() { close(); }
  3310. inline bool mmap::open(const char *path) {
  3311. close();
  3312. #if defined(_WIN32)
  3313. auto wpath = u8string_to_wstring(path);
  3314. if (wpath.empty()) { return false; }
  3315. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  3316. OPEN_EXISTING, NULL);
  3317. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  3318. LARGE_INTEGER size{};
  3319. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  3320. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  3321. // See:
  3322. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  3323. if (static_cast<ULONGLONG>(size.QuadPart) >
  3324. (std::numeric_limits<decltype(size_)>::max)()) {
  3325. // `size_t` might be 32-bits, on 32-bits Windows.
  3326. return false;
  3327. }
  3328. size_ = static_cast<size_t>(size.QuadPart);
  3329. hMapping_ =
  3330. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  3331. // Special treatment for an empty file...
  3332. if (hMapping_ == NULL && size_ == 0) {
  3333. close();
  3334. is_open_empty_file = true;
  3335. return true;
  3336. }
  3337. if (hMapping_ == NULL) {
  3338. close();
  3339. return false;
  3340. }
  3341. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  3342. if (addr_ == nullptr) {
  3343. close();
  3344. return false;
  3345. }
  3346. #else
  3347. fd_ = ::open(path, O_RDONLY);
  3348. if (fd_ == -1) { return false; }
  3349. struct stat sb;
  3350. if (fstat(fd_, &sb) == -1) {
  3351. close();
  3352. return false;
  3353. }
  3354. size_ = static_cast<size_t>(sb.st_size);
  3355. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  3356. // Special treatment for an empty file...
  3357. if (addr_ == MAP_FAILED && size_ == 0) {
  3358. close();
  3359. is_open_empty_file = true;
  3360. return false;
  3361. }
  3362. #endif
  3363. return true;
  3364. }
  3365. inline bool mmap::is_open() const {
  3366. return is_open_empty_file ? true : addr_ != nullptr;
  3367. }
  3368. inline size_t mmap::size() const { return size_; }
  3369. inline const char *mmap::data() const {
  3370. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  3371. }
  3372. inline void mmap::close() {
  3373. #if defined(_WIN32)
  3374. if (addr_) {
  3375. ::UnmapViewOfFile(addr_);
  3376. addr_ = nullptr;
  3377. }
  3378. if (hMapping_) {
  3379. ::CloseHandle(hMapping_);
  3380. hMapping_ = NULL;
  3381. }
  3382. if (hFile_ != INVALID_HANDLE_VALUE) {
  3383. ::CloseHandle(hFile_);
  3384. hFile_ = INVALID_HANDLE_VALUE;
  3385. }
  3386. is_open_empty_file = false;
  3387. #else
  3388. if (addr_ != nullptr) {
  3389. munmap(addr_, size_);
  3390. addr_ = nullptr;
  3391. }
  3392. if (fd_ != -1) {
  3393. ::close(fd_);
  3394. fd_ = -1;
  3395. }
  3396. #endif
  3397. size_ = 0;
  3398. }
  3399. inline int close_socket(socket_t sock) {
  3400. #ifdef _WIN32
  3401. return closesocket(sock);
  3402. #else
  3403. return close(sock);
  3404. #endif
  3405. }
  3406. template <typename T> inline ssize_t handle_EINTR(T fn) {
  3407. ssize_t res = 0;
  3408. while (true) {
  3409. res = fn();
  3410. if (res < 0 && errno == EINTR) {
  3411. std::this_thread::sleep_for(std::chrono::microseconds{1});
  3412. continue;
  3413. }
  3414. break;
  3415. }
  3416. return res;
  3417. }
  3418. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  3419. return handle_EINTR([&]() {
  3420. return recv(sock,
  3421. #ifdef _WIN32
  3422. static_cast<char *>(ptr), static_cast<int>(size),
  3423. #else
  3424. ptr, size,
  3425. #endif
  3426. flags);
  3427. });
  3428. }
  3429. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  3430. int flags) {
  3431. return handle_EINTR([&]() {
  3432. return send(sock,
  3433. #ifdef _WIN32
  3434. static_cast<const char *>(ptr), static_cast<int>(size),
  3435. #else
  3436. ptr, size,
  3437. #endif
  3438. flags);
  3439. });
  3440. }
  3441. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  3442. #ifdef _WIN32
  3443. return ::WSAPoll(fds, nfds, timeout);
  3444. #else
  3445. return ::poll(fds, nfds, timeout);
  3446. #endif
  3447. }
  3448. template <bool Read>
  3449. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  3450. #ifdef __APPLE__
  3451. if (sock >= FD_SETSIZE) { return -1; }
  3452. fd_set fds, *rfds, *wfds;
  3453. FD_ZERO(&fds);
  3454. FD_SET(sock, &fds);
  3455. rfds = (Read ? &fds : nullptr);
  3456. wfds = (Read ? nullptr : &fds);
  3457. timeval tv;
  3458. tv.tv_sec = static_cast<long>(sec);
  3459. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3460. return handle_EINTR([&]() {
  3461. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  3462. });
  3463. #else
  3464. struct pollfd pfd;
  3465. pfd.fd = sock;
  3466. pfd.events = (Read ? POLLIN : POLLOUT);
  3467. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3468. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  3469. #endif
  3470. }
  3471. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  3472. return select_impl<true>(sock, sec, usec);
  3473. }
  3474. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  3475. return select_impl<false>(sock, sec, usec);
  3476. }
  3477. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  3478. time_t usec) {
  3479. #ifdef __APPLE__
  3480. if (sock >= FD_SETSIZE) { return Error::Connection; }
  3481. fd_set fdsr, fdsw;
  3482. FD_ZERO(&fdsr);
  3483. FD_ZERO(&fdsw);
  3484. FD_SET(sock, &fdsr);
  3485. FD_SET(sock, &fdsw);
  3486. timeval tv;
  3487. tv.tv_sec = static_cast<long>(sec);
  3488. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  3489. auto ret = handle_EINTR([&]() {
  3490. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  3491. });
  3492. if (ret == 0) { return Error::ConnectionTimeout; }
  3493. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  3494. auto error = 0;
  3495. socklen_t len = sizeof(error);
  3496. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3497. reinterpret_cast<char *>(&error), &len);
  3498. auto successful = res >= 0 && !error;
  3499. return successful ? Error::Success : Error::Connection;
  3500. }
  3501. return Error::Connection;
  3502. #else
  3503. struct pollfd pfd_read;
  3504. pfd_read.fd = sock;
  3505. pfd_read.events = POLLIN | POLLOUT;
  3506. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  3507. auto poll_res =
  3508. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  3509. if (poll_res == 0) { return Error::ConnectionTimeout; }
  3510. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  3511. auto error = 0;
  3512. socklen_t len = sizeof(error);
  3513. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  3514. reinterpret_cast<char *>(&error), &len);
  3515. auto successful = res >= 0 && !error;
  3516. return successful ? Error::Success : Error::Connection;
  3517. }
  3518. return Error::Connection;
  3519. #endif
  3520. }
  3521. inline bool is_socket_alive(socket_t sock) {
  3522. const auto val = detail::select_read(sock, 0, 0);
  3523. if (val == 0) {
  3524. return true;
  3525. } else if (val < 0 && errno == EBADF) {
  3526. return false;
  3527. }
  3528. char buf[1];
  3529. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  3530. }
  3531. class SocketStream final : public Stream {
  3532. public:
  3533. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3534. time_t write_timeout_sec, time_t write_timeout_usec,
  3535. time_t max_timeout_msec = 0,
  3536. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3537. (std::chrono::steady_clock::time_point::min)());
  3538. ~SocketStream() override;
  3539. bool is_readable() const override;
  3540. bool wait_readable() const override;
  3541. bool wait_writable() const override;
  3542. ssize_t read(char *ptr, size_t size) override;
  3543. ssize_t write(const char *ptr, size_t size) override;
  3544. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3545. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3546. socket_t socket() const override;
  3547. time_t duration() const override;
  3548. private:
  3549. socket_t sock_;
  3550. time_t read_timeout_sec_;
  3551. time_t read_timeout_usec_;
  3552. time_t write_timeout_sec_;
  3553. time_t write_timeout_usec_;
  3554. time_t max_timeout_msec_;
  3555. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3556. std::vector<char> read_buff_;
  3557. size_t read_buff_off_ = 0;
  3558. size_t read_buff_content_size_ = 0;
  3559. static const size_t read_buff_size_ = 1024l * 4;
  3560. };
  3561. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3562. class SSLSocketStream final : public Stream {
  3563. public:
  3564. SSLSocketStream(
  3565. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  3566. time_t read_timeout_usec, time_t write_timeout_sec,
  3567. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  3568. std::chrono::time_point<std::chrono::steady_clock> start_time =
  3569. (std::chrono::steady_clock::time_point::min)());
  3570. ~SSLSocketStream() override;
  3571. bool is_readable() const override;
  3572. bool wait_readable() const override;
  3573. bool wait_writable() const override;
  3574. ssize_t read(char *ptr, size_t size) override;
  3575. ssize_t write(const char *ptr, size_t size) override;
  3576. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  3577. void get_local_ip_and_port(std::string &ip, int &port) const override;
  3578. socket_t socket() const override;
  3579. time_t duration() const override;
  3580. private:
  3581. socket_t sock_;
  3582. SSL *ssl_;
  3583. time_t read_timeout_sec_;
  3584. time_t read_timeout_usec_;
  3585. time_t write_timeout_sec_;
  3586. time_t write_timeout_usec_;
  3587. time_t max_timeout_msec_;
  3588. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  3589. };
  3590. #endif
  3591. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3592. time_t keep_alive_timeout_sec) {
  3593. using namespace std::chrono;
  3594. const auto interval_usec =
  3595. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  3596. // Avoid expensive `steady_clock::now()` call for the first time
  3597. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  3598. const auto start = steady_clock::now() - microseconds{interval_usec};
  3599. const auto timeout = seconds{keep_alive_timeout_sec};
  3600. while (true) {
  3601. if (svr_sock == INVALID_SOCKET) {
  3602. break; // Server socket is closed
  3603. }
  3604. auto val = select_read(sock, 0, interval_usec);
  3605. if (val < 0) {
  3606. break; // Ssocket error
  3607. } else if (val == 0) {
  3608. if (steady_clock::now() - start > timeout) {
  3609. break; // Timeout
  3610. }
  3611. } else {
  3612. return true; // Ready for read
  3613. }
  3614. }
  3615. return false;
  3616. }
  3617. template <typename T>
  3618. inline bool
  3619. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3620. size_t keep_alive_max_count,
  3621. time_t keep_alive_timeout_sec, T callback) {
  3622. assert(keep_alive_max_count > 0);
  3623. auto ret = false;
  3624. auto count = keep_alive_max_count;
  3625. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  3626. auto close_connection = count == 1;
  3627. auto connection_closed = false;
  3628. ret = callback(close_connection, connection_closed);
  3629. if (!ret || connection_closed) { break; }
  3630. count--;
  3631. }
  3632. return ret;
  3633. }
  3634. template <typename T>
  3635. inline bool
  3636. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  3637. size_t keep_alive_max_count,
  3638. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  3639. time_t read_timeout_usec, time_t write_timeout_sec,
  3640. time_t write_timeout_usec, T callback) {
  3641. return process_server_socket_core(
  3642. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  3643. [&](bool close_connection, bool &connection_closed) {
  3644. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3645. write_timeout_sec, write_timeout_usec);
  3646. return callback(strm, close_connection, connection_closed);
  3647. });
  3648. }
  3649. inline bool process_client_socket(
  3650. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3651. time_t write_timeout_sec, time_t write_timeout_usec,
  3652. time_t max_timeout_msec,
  3653. std::chrono::time_point<std::chrono::steady_clock> start_time,
  3654. std::function<bool(Stream &)> callback) {
  3655. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  3656. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  3657. start_time);
  3658. return callback(strm);
  3659. }
  3660. inline int shutdown_socket(socket_t sock) {
  3661. #ifdef _WIN32
  3662. return shutdown(sock, SD_BOTH);
  3663. #else
  3664. return shutdown(sock, SHUT_RDWR);
  3665. #endif
  3666. }
  3667. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  3668. if (s.size() > 1 && s[0] == '\0') {
  3669. auto ret = s;
  3670. ret[0] = '@';
  3671. return ret;
  3672. }
  3673. return s;
  3674. }
  3675. inline std::string
  3676. unescape_abstract_namespace_unix_domain(const std::string &s) {
  3677. if (s.size() > 1 && s[0] == '@') {
  3678. auto ret = s;
  3679. ret[0] = '\0';
  3680. return ret;
  3681. }
  3682. return s;
  3683. }
  3684. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  3685. const struct addrinfo *hints,
  3686. struct addrinfo **res, time_t timeout_sec) {
  3687. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  3688. if (timeout_sec <= 0) {
  3689. // No timeout specified, use standard getaddrinfo
  3690. return getaddrinfo(node, service, hints, res);
  3691. }
  3692. #ifdef _WIN32
  3693. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  3694. OVERLAPPED overlapped = {0};
  3695. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  3696. if (!event) { return EAI_FAIL; }
  3697. overlapped.hEvent = event;
  3698. PADDRINFOEXW result_addrinfo = nullptr;
  3699. HANDLE cancel_handle = nullptr;
  3700. ADDRINFOEXW hints_ex = {0};
  3701. if (hints) {
  3702. hints_ex.ai_flags = hints->ai_flags;
  3703. hints_ex.ai_family = hints->ai_family;
  3704. hints_ex.ai_socktype = hints->ai_socktype;
  3705. hints_ex.ai_protocol = hints->ai_protocol;
  3706. }
  3707. auto wnode = u8string_to_wstring(node);
  3708. auto wservice = u8string_to_wstring(service);
  3709. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  3710. hints ? &hints_ex : nullptr, &result_addrinfo,
  3711. nullptr, &overlapped, nullptr, &cancel_handle);
  3712. if (ret == WSA_IO_PENDING) {
  3713. auto wait_result =
  3714. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  3715. if (wait_result == WAIT_TIMEOUT) {
  3716. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  3717. ::CloseHandle(event);
  3718. return EAI_AGAIN;
  3719. }
  3720. DWORD bytes_returned;
  3721. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  3722. &bytes_returned, FALSE)) {
  3723. ::CloseHandle(event);
  3724. return ::WSAGetLastError();
  3725. }
  3726. }
  3727. ::CloseHandle(event);
  3728. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  3729. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  3730. return 0;
  3731. }
  3732. return ret;
  3733. #elif TARGET_OS_MAC
  3734. if (!node) { return EAI_NONAME; }
  3735. // macOS implementation using CFHost API for asynchronous DNS resolution
  3736. CFStringRef hostname_ref = CFStringCreateWithCString(
  3737. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  3738. if (!hostname_ref) { return EAI_MEMORY; }
  3739. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  3740. CFRelease(hostname_ref);
  3741. if (!host_ref) { return EAI_MEMORY; }
  3742. // Set up context for callback
  3743. struct CFHostContext {
  3744. bool completed = false;
  3745. bool success = false;
  3746. CFArrayRef addresses = nullptr;
  3747. std::mutex mutex;
  3748. std::condition_variable cv;
  3749. } context;
  3750. CFHostClientContext client_context;
  3751. memset(&client_context, 0, sizeof(client_context));
  3752. client_context.info = &context;
  3753. // Set callback
  3754. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  3755. const CFStreamError *error, void *info) {
  3756. auto ctx = static_cast<CFHostContext *>(info);
  3757. std::lock_guard<std::mutex> lock(ctx->mutex);
  3758. if (error && error->error != 0) {
  3759. ctx->success = false;
  3760. } else {
  3761. Boolean hasBeenResolved;
  3762. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  3763. if (ctx->addresses && hasBeenResolved) {
  3764. CFRetain(ctx->addresses);
  3765. ctx->success = true;
  3766. } else {
  3767. ctx->success = false;
  3768. }
  3769. }
  3770. ctx->completed = true;
  3771. ctx->cv.notify_one();
  3772. };
  3773. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  3774. CFRelease(host_ref);
  3775. return EAI_SYSTEM;
  3776. }
  3777. // Schedule on run loop
  3778. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  3779. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3780. // Start resolution
  3781. CFStreamError stream_error;
  3782. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  3783. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3784. CFRelease(host_ref);
  3785. return EAI_FAIL;
  3786. }
  3787. // Wait for completion with timeout
  3788. auto timeout_time =
  3789. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  3790. bool timed_out = false;
  3791. {
  3792. std::unique_lock<std::mutex> lock(context.mutex);
  3793. while (!context.completed) {
  3794. auto now = std::chrono::steady_clock::now();
  3795. if (now >= timeout_time) {
  3796. timed_out = true;
  3797. break;
  3798. }
  3799. // Run the runloop for a short time
  3800. lock.unlock();
  3801. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  3802. lock.lock();
  3803. }
  3804. }
  3805. // Clean up
  3806. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3807. CFHostSetClient(host_ref, nullptr, nullptr);
  3808. if (timed_out || !context.completed) {
  3809. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  3810. CFRelease(host_ref);
  3811. return EAI_AGAIN;
  3812. }
  3813. if (!context.success || !context.addresses) {
  3814. CFRelease(host_ref);
  3815. return EAI_NODATA;
  3816. }
  3817. // Convert CFArray to addrinfo
  3818. CFIndex count = CFArrayGetCount(context.addresses);
  3819. if (count == 0) {
  3820. CFRelease(context.addresses);
  3821. CFRelease(host_ref);
  3822. return EAI_NODATA;
  3823. }
  3824. struct addrinfo *result_addrinfo = nullptr;
  3825. struct addrinfo **current = &result_addrinfo;
  3826. for (CFIndex i = 0; i < count; i++) {
  3827. CFDataRef addr_data =
  3828. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  3829. if (!addr_data) continue;
  3830. const struct sockaddr *sockaddr_ptr =
  3831. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  3832. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  3833. // Allocate addrinfo structure
  3834. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  3835. if (!*current) {
  3836. freeaddrinfo(result_addrinfo);
  3837. CFRelease(context.addresses);
  3838. CFRelease(host_ref);
  3839. return EAI_MEMORY;
  3840. }
  3841. memset(*current, 0, sizeof(struct addrinfo));
  3842. // Set up addrinfo fields
  3843. (*current)->ai_family = sockaddr_ptr->sa_family;
  3844. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  3845. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  3846. (*current)->ai_addrlen = sockaddr_len;
  3847. // Copy sockaddr
  3848. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  3849. if (!(*current)->ai_addr) {
  3850. freeaddrinfo(result_addrinfo);
  3851. CFRelease(context.addresses);
  3852. CFRelease(host_ref);
  3853. return EAI_MEMORY;
  3854. }
  3855. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  3856. // Set port if service is specified
  3857. if (service && strlen(service) > 0) {
  3858. int port = atoi(service);
  3859. if (port > 0) {
  3860. if (sockaddr_ptr->sa_family == AF_INET) {
  3861. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  3862. ->sin_port = htons(static_cast<uint16_t>(port));
  3863. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  3864. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  3865. ->sin6_port = htons(static_cast<uint16_t>(port));
  3866. }
  3867. }
  3868. }
  3869. current = &((*current)->ai_next);
  3870. }
  3871. CFRelease(context.addresses);
  3872. CFRelease(host_ref);
  3873. *res = result_addrinfo;
  3874. return 0;
  3875. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  3876. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  3877. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  3878. struct gaicb request;
  3879. struct gaicb *requests[1] = {&request};
  3880. struct sigevent sevp;
  3881. struct timespec timeout;
  3882. // Initialize the request structure
  3883. memset(&request, 0, sizeof(request));
  3884. request.ar_name = node;
  3885. request.ar_service = service;
  3886. request.ar_request = hints;
  3887. // Set up timeout
  3888. timeout.tv_sec = timeout_sec;
  3889. timeout.tv_nsec = 0;
  3890. // Initialize sigevent structure (not used, but required)
  3891. memset(&sevp, 0, sizeof(sevp));
  3892. sevp.sigev_notify = SIGEV_NONE;
  3893. // Start asynchronous resolution
  3894. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  3895. if (start_result != 0) { return start_result; }
  3896. // Wait for completion with timeout
  3897. int wait_result =
  3898. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  3899. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  3900. // Completed successfully, get the result
  3901. int gai_result = gai_error(&request);
  3902. if (gai_result == 0) {
  3903. *res = request.ar_result;
  3904. return 0;
  3905. } else {
  3906. // Clean up on error
  3907. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  3908. return gai_result;
  3909. }
  3910. } else if (wait_result == EAI_AGAIN) {
  3911. // Timeout occurred, cancel the request
  3912. gai_cancel(&request);
  3913. return EAI_AGAIN;
  3914. } else {
  3915. // Other error occurred
  3916. gai_cancel(&request);
  3917. return wait_result;
  3918. }
  3919. #else
  3920. // Fallback implementation using thread-based timeout for other Unix systems
  3921. struct GetAddrInfoState {
  3922. ~GetAddrInfoState() {
  3923. if (info) { freeaddrinfo(info); }
  3924. }
  3925. std::mutex mutex;
  3926. std::condition_variable result_cv;
  3927. bool completed = false;
  3928. int result = EAI_SYSTEM;
  3929. std::string node;
  3930. std::string service;
  3931. struct addrinfo hints;
  3932. struct addrinfo *info = nullptr;
  3933. };
  3934. // Allocate on the heap, so the resolver thread can keep using the data.
  3935. auto state = std::make_shared<GetAddrInfoState>();
  3936. if (node) { state->node = node; }
  3937. state->service = service;
  3938. state->hints = *hints;
  3939. std::thread resolve_thread([state]() {
  3940. auto thread_result =
  3941. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  3942. &state->info);
  3943. std::lock_guard<std::mutex> lock(state->mutex);
  3944. state->result = thread_result;
  3945. state->completed = true;
  3946. state->result_cv.notify_one();
  3947. });
  3948. // Wait for completion or timeout
  3949. std::unique_lock<std::mutex> lock(state->mutex);
  3950. auto finished =
  3951. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  3952. [&] { return state->completed; });
  3953. if (finished) {
  3954. // Operation completed within timeout
  3955. resolve_thread.join();
  3956. *res = state->info;
  3957. state->info = nullptr; // Pass ownership to caller
  3958. return state->result;
  3959. } else {
  3960. // Timeout occurred
  3961. resolve_thread.detach(); // Let the thread finish in background
  3962. return EAI_AGAIN; // Return timeout error
  3963. }
  3964. #endif
  3965. #else
  3966. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  3967. return getaddrinfo(node, service, hints, res);
  3968. #endif
  3969. }
  3970. template <typename BindOrConnect>
  3971. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  3972. int address_family, int socket_flags, bool tcp_nodelay,
  3973. bool ipv6_v6only, SocketOptions socket_options,
  3974. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  3975. // Get address info
  3976. const char *node = nullptr;
  3977. struct addrinfo hints;
  3978. struct addrinfo *result;
  3979. memset(&hints, 0, sizeof(struct addrinfo));
  3980. hints.ai_socktype = SOCK_STREAM;
  3981. hints.ai_protocol = IPPROTO_IP;
  3982. if (!ip.empty()) {
  3983. node = ip.c_str();
  3984. // Ask getaddrinfo to convert IP in c-string to address
  3985. hints.ai_family = AF_UNSPEC;
  3986. hints.ai_flags = AI_NUMERICHOST;
  3987. } else {
  3988. if (!host.empty()) { node = host.c_str(); }
  3989. hints.ai_family = address_family;
  3990. hints.ai_flags = socket_flags;
  3991. }
  3992. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  3993. if (hints.ai_family == AF_UNIX) {
  3994. const auto addrlen = host.length();
  3995. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  3996. #ifdef SOCK_CLOEXEC
  3997. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  3998. hints.ai_protocol);
  3999. #else
  4000. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  4001. #endif
  4002. if (sock != INVALID_SOCKET) {
  4003. sockaddr_un addr{};
  4004. addr.sun_family = AF_UNIX;
  4005. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  4006. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  4007. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  4008. hints.ai_addrlen = static_cast<socklen_t>(
  4009. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  4010. #ifndef SOCK_CLOEXEC
  4011. #ifndef _WIN32
  4012. fcntl(sock, F_SETFD, FD_CLOEXEC);
  4013. #endif
  4014. #endif
  4015. if (socket_options) { socket_options(sock); }
  4016. #ifdef _WIN32
  4017. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  4018. // remove the option.
  4019. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  4020. #endif
  4021. bool dummy;
  4022. if (!bind_or_connect(sock, hints, dummy)) {
  4023. close_socket(sock);
  4024. sock = INVALID_SOCKET;
  4025. }
  4026. }
  4027. return sock;
  4028. }
  4029. #endif
  4030. auto service = std::to_string(port);
  4031. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  4032. timeout_sec)) {
  4033. #if defined __linux__ && !defined __ANDROID__
  4034. res_init();
  4035. #endif
  4036. return INVALID_SOCKET;
  4037. }
  4038. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4039. for (auto rp = result; rp; rp = rp->ai_next) {
  4040. // Create a socket
  4041. #ifdef _WIN32
  4042. auto sock =
  4043. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  4044. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  4045. /**
  4046. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  4047. * and above the socket creation fails on older Windows Systems.
  4048. *
  4049. * Let's try to create a socket the old way in this case.
  4050. *
  4051. * Reference:
  4052. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  4053. *
  4054. * WSA_FLAG_NO_HANDLE_INHERIT:
  4055. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  4056. * SP1, and later
  4057. *
  4058. */
  4059. if (sock == INVALID_SOCKET) {
  4060. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4061. }
  4062. #else
  4063. #ifdef SOCK_CLOEXEC
  4064. auto sock =
  4065. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  4066. #else
  4067. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  4068. #endif
  4069. #endif
  4070. if (sock == INVALID_SOCKET) { continue; }
  4071. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  4072. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  4073. close_socket(sock);
  4074. continue;
  4075. }
  4076. #endif
  4077. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  4078. if (rp->ai_family == AF_INET6) {
  4079. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  4080. }
  4081. if (socket_options) { socket_options(sock); }
  4082. // bind or connect
  4083. auto quit = false;
  4084. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  4085. close_socket(sock);
  4086. if (quit) { break; }
  4087. }
  4088. return INVALID_SOCKET;
  4089. }
  4090. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  4091. #ifdef _WIN32
  4092. auto flags = nonblocking ? 1UL : 0UL;
  4093. ioctlsocket(sock, FIONBIO, &flags);
  4094. #else
  4095. auto flags = fcntl(sock, F_GETFL, 0);
  4096. fcntl(sock, F_SETFL,
  4097. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  4098. #endif
  4099. }
  4100. inline bool is_connection_error() {
  4101. #ifdef _WIN32
  4102. return WSAGetLastError() != WSAEWOULDBLOCK;
  4103. #else
  4104. return errno != EINPROGRESS;
  4105. #endif
  4106. }
  4107. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  4108. struct addrinfo hints;
  4109. struct addrinfo *result;
  4110. memset(&hints, 0, sizeof(struct addrinfo));
  4111. hints.ai_family = AF_UNSPEC;
  4112. hints.ai_socktype = SOCK_STREAM;
  4113. hints.ai_protocol = 0;
  4114. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  4115. return false;
  4116. }
  4117. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  4118. auto ret = false;
  4119. for (auto rp = result; rp; rp = rp->ai_next) {
  4120. const auto &ai = *rp;
  4121. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4122. ret = true;
  4123. break;
  4124. }
  4125. }
  4126. return ret;
  4127. }
  4128. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  4129. #define USE_IF2IP
  4130. #endif
  4131. #ifdef USE_IF2IP
  4132. inline std::string if2ip(int address_family, const std::string &ifn) {
  4133. struct ifaddrs *ifap;
  4134. getifaddrs(&ifap);
  4135. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  4136. std::string addr_candidate;
  4137. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  4138. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  4139. (AF_UNSPEC == address_family ||
  4140. ifa->ifa_addr->sa_family == address_family)) {
  4141. if (ifa->ifa_addr->sa_family == AF_INET) {
  4142. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  4143. char buf[INET_ADDRSTRLEN];
  4144. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  4145. return std::string(buf, INET_ADDRSTRLEN);
  4146. }
  4147. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  4148. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  4149. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  4150. char buf[INET6_ADDRSTRLEN] = {};
  4151. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  4152. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  4153. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  4154. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  4155. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  4156. } else {
  4157. return std::string(buf, INET6_ADDRSTRLEN);
  4158. }
  4159. }
  4160. }
  4161. }
  4162. }
  4163. }
  4164. return addr_candidate;
  4165. }
  4166. #endif
  4167. inline socket_t create_client_socket(
  4168. const std::string &host, const std::string &ip, int port,
  4169. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  4170. SocketOptions socket_options, time_t connection_timeout_sec,
  4171. time_t connection_timeout_usec, time_t read_timeout_sec,
  4172. time_t read_timeout_usec, time_t write_timeout_sec,
  4173. time_t write_timeout_usec, const std::string &intf, Error &error) {
  4174. auto sock = create_socket(
  4175. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  4176. std::move(socket_options),
  4177. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  4178. if (!intf.empty()) {
  4179. #ifdef USE_IF2IP
  4180. auto ip_from_if = if2ip(address_family, intf);
  4181. if (ip_from_if.empty()) { ip_from_if = intf; }
  4182. if (!bind_ip_address(sock2, ip_from_if)) {
  4183. error = Error::BindIPAddress;
  4184. return false;
  4185. }
  4186. #endif
  4187. }
  4188. set_nonblocking(sock2, true);
  4189. auto ret =
  4190. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  4191. if (ret < 0) {
  4192. if (is_connection_error()) {
  4193. error = Error::Connection;
  4194. return false;
  4195. }
  4196. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  4197. connection_timeout_usec);
  4198. if (error != Error::Success) {
  4199. if (error == Error::ConnectionTimeout) { quit = true; }
  4200. return false;
  4201. }
  4202. }
  4203. set_nonblocking(sock2, false);
  4204. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  4205. read_timeout_usec);
  4206. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  4207. write_timeout_usec);
  4208. error = Error::Success;
  4209. return true;
  4210. },
  4211. connection_timeout_sec); // Pass DNS timeout
  4212. if (sock != INVALID_SOCKET) {
  4213. error = Error::Success;
  4214. } else {
  4215. if (error == Error::Success) { error = Error::Connection; }
  4216. }
  4217. return sock;
  4218. }
  4219. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  4220. socklen_t addr_len, std::string &ip, int &port) {
  4221. if (addr.ss_family == AF_INET) {
  4222. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  4223. } else if (addr.ss_family == AF_INET6) {
  4224. port =
  4225. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  4226. } else {
  4227. return false;
  4228. }
  4229. std::array<char, NI_MAXHOST> ipstr{};
  4230. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  4231. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  4232. 0, NI_NUMERICHOST)) {
  4233. return false;
  4234. }
  4235. ip = ipstr.data();
  4236. return true;
  4237. }
  4238. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4239. struct sockaddr_storage addr;
  4240. socklen_t addr_len = sizeof(addr);
  4241. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4242. &addr_len)) {
  4243. get_ip_and_port(addr, addr_len, ip, port);
  4244. }
  4245. }
  4246. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  4247. struct sockaddr_storage addr;
  4248. socklen_t addr_len = sizeof(addr);
  4249. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  4250. &addr_len)) {
  4251. #ifndef _WIN32
  4252. if (addr.ss_family == AF_UNIX) {
  4253. #if defined(__linux__)
  4254. struct ucred ucred;
  4255. socklen_t len = sizeof(ucred);
  4256. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  4257. port = ucred.pid;
  4258. }
  4259. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  4260. pid_t pid;
  4261. socklen_t len = sizeof(pid);
  4262. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  4263. port = pid;
  4264. }
  4265. #endif
  4266. return;
  4267. }
  4268. #endif
  4269. get_ip_and_port(addr, addr_len, ip, port);
  4270. }
  4271. }
  4272. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  4273. unsigned int h) {
  4274. return (l == 0)
  4275. ? h
  4276. : str2tag_core(
  4277. s + 1, l - 1,
  4278. // Unsets the 6 high bits of h, therefore no overflow happens
  4279. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  4280. h * 33) ^
  4281. static_cast<unsigned char>(*s));
  4282. }
  4283. inline unsigned int str2tag(const std::string &s) {
  4284. return str2tag_core(s.data(), s.size(), 0);
  4285. }
  4286. namespace udl {
  4287. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  4288. return str2tag_core(s, l, 0);
  4289. }
  4290. } // namespace udl
  4291. inline std::string
  4292. find_content_type(const std::string &path,
  4293. const std::map<std::string, std::string> &user_data,
  4294. const std::string &default_content_type) {
  4295. auto ext = file_extension(path);
  4296. auto it = user_data.find(ext);
  4297. if (it != user_data.end()) { return it->second; }
  4298. using udl::operator""_t;
  4299. switch (str2tag(ext)) {
  4300. default: return default_content_type;
  4301. case "css"_t: return "text/css";
  4302. case "csv"_t: return "text/csv";
  4303. case "htm"_t:
  4304. case "html"_t: return "text/html";
  4305. case "js"_t:
  4306. case "mjs"_t: return "text/javascript";
  4307. case "txt"_t: return "text/plain";
  4308. case "vtt"_t: return "text/vtt";
  4309. case "apng"_t: return "image/apng";
  4310. case "avif"_t: return "image/avif";
  4311. case "bmp"_t: return "image/bmp";
  4312. case "gif"_t: return "image/gif";
  4313. case "png"_t: return "image/png";
  4314. case "svg"_t: return "image/svg+xml";
  4315. case "webp"_t: return "image/webp";
  4316. case "ico"_t: return "image/x-icon";
  4317. case "tif"_t: return "image/tiff";
  4318. case "tiff"_t: return "image/tiff";
  4319. case "jpg"_t:
  4320. case "jpeg"_t: return "image/jpeg";
  4321. case "mp4"_t: return "video/mp4";
  4322. case "mpeg"_t: return "video/mpeg";
  4323. case "webm"_t: return "video/webm";
  4324. case "mp3"_t: return "audio/mp3";
  4325. case "mpga"_t: return "audio/mpeg";
  4326. case "weba"_t: return "audio/webm";
  4327. case "wav"_t: return "audio/wave";
  4328. case "otf"_t: return "font/otf";
  4329. case "ttf"_t: return "font/ttf";
  4330. case "woff"_t: return "font/woff";
  4331. case "woff2"_t: return "font/woff2";
  4332. case "7z"_t: return "application/x-7z-compressed";
  4333. case "atom"_t: return "application/atom+xml";
  4334. case "pdf"_t: return "application/pdf";
  4335. case "json"_t: return "application/json";
  4336. case "rss"_t: return "application/rss+xml";
  4337. case "tar"_t: return "application/x-tar";
  4338. case "xht"_t:
  4339. case "xhtml"_t: return "application/xhtml+xml";
  4340. case "xslt"_t: return "application/xslt+xml";
  4341. case "xml"_t: return "application/xml";
  4342. case "gz"_t: return "application/gzip";
  4343. case "zip"_t: return "application/zip";
  4344. case "wasm"_t: return "application/wasm";
  4345. }
  4346. }
  4347. inline bool can_compress_content_type(const std::string &content_type) {
  4348. using udl::operator""_t;
  4349. auto tag = str2tag(content_type);
  4350. switch (tag) {
  4351. case "image/svg+xml"_t:
  4352. case "application/javascript"_t:
  4353. case "application/json"_t:
  4354. case "application/xml"_t:
  4355. case "application/protobuf"_t:
  4356. case "application/xhtml+xml"_t: return true;
  4357. case "text/event-stream"_t: return false;
  4358. default: return !content_type.rfind("text/", 0);
  4359. }
  4360. }
  4361. inline EncodingType encoding_type(const Request &req, const Response &res) {
  4362. auto ret =
  4363. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  4364. if (!ret) { return EncodingType::None; }
  4365. const auto &s = req.get_header_value("Accept-Encoding");
  4366. (void)(s);
  4367. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4368. // TODO: 'Accept-Encoding' has br, not br;q=0
  4369. ret = s.find("br") != std::string::npos;
  4370. if (ret) { return EncodingType::Brotli; }
  4371. #endif
  4372. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4373. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  4374. ret = s.find("gzip") != std::string::npos;
  4375. if (ret) { return EncodingType::Gzip; }
  4376. #endif
  4377. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4378. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  4379. ret = s.find("zstd") != std::string::npos;
  4380. if (ret) { return EncodingType::Zstd; }
  4381. #endif
  4382. return EncodingType::None;
  4383. }
  4384. inline bool nocompressor::compress(const char *data, size_t data_length,
  4385. bool /*last*/, Callback callback) {
  4386. if (!data_length) { return true; }
  4387. return callback(data, data_length);
  4388. }
  4389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4390. inline gzip_compressor::gzip_compressor() {
  4391. std::memset(&strm_, 0, sizeof(strm_));
  4392. strm_.zalloc = Z_NULL;
  4393. strm_.zfree = Z_NULL;
  4394. strm_.opaque = Z_NULL;
  4395. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  4396. Z_DEFAULT_STRATEGY) == Z_OK;
  4397. }
  4398. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  4399. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  4400. bool last, Callback callback) {
  4401. assert(is_valid_);
  4402. do {
  4403. constexpr size_t max_avail_in =
  4404. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4405. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4406. (std::min)(data_length, max_avail_in));
  4407. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4408. data_length -= strm_.avail_in;
  4409. data += strm_.avail_in;
  4410. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  4411. auto ret = Z_OK;
  4412. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4413. do {
  4414. strm_.avail_out = static_cast<uInt>(buff.size());
  4415. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4416. ret = deflate(&strm_, flush);
  4417. if (ret == Z_STREAM_ERROR) { return false; }
  4418. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4419. return false;
  4420. }
  4421. } while (strm_.avail_out == 0);
  4422. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  4423. (flush == Z_NO_FLUSH && ret == Z_OK));
  4424. assert(strm_.avail_in == 0);
  4425. } while (data_length > 0);
  4426. return true;
  4427. }
  4428. inline gzip_decompressor::gzip_decompressor() {
  4429. std::memset(&strm_, 0, sizeof(strm_));
  4430. strm_.zalloc = Z_NULL;
  4431. strm_.zfree = Z_NULL;
  4432. strm_.opaque = Z_NULL;
  4433. // 15 is the value of wbits, which should be at the maximum possible value
  4434. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  4435. // that the stream type should be automatically detected either gzip or
  4436. // deflate.
  4437. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  4438. }
  4439. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  4440. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  4441. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  4442. Callback callback) {
  4443. assert(is_valid_);
  4444. auto ret = Z_OK;
  4445. do {
  4446. constexpr size_t max_avail_in =
  4447. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  4448. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  4449. (std::min)(data_length, max_avail_in));
  4450. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  4451. data_length -= strm_.avail_in;
  4452. data += strm_.avail_in;
  4453. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4454. while (strm_.avail_in > 0 && ret == Z_OK) {
  4455. strm_.avail_out = static_cast<uInt>(buff.size());
  4456. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  4457. ret = inflate(&strm_, Z_NO_FLUSH);
  4458. assert(ret != Z_STREAM_ERROR);
  4459. switch (ret) {
  4460. case Z_NEED_DICT:
  4461. case Z_DATA_ERROR:
  4462. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  4463. }
  4464. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  4465. return false;
  4466. }
  4467. }
  4468. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  4469. } while (data_length > 0);
  4470. return true;
  4471. }
  4472. #endif
  4473. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4474. inline brotli_compressor::brotli_compressor() {
  4475. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  4476. }
  4477. inline brotli_compressor::~brotli_compressor() {
  4478. BrotliEncoderDestroyInstance(state_);
  4479. }
  4480. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  4481. bool last, Callback callback) {
  4482. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4483. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  4484. auto available_in = data_length;
  4485. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4486. for (;;) {
  4487. if (last) {
  4488. if (BrotliEncoderIsFinished(state_)) { break; }
  4489. } else {
  4490. if (!available_in) { break; }
  4491. }
  4492. auto available_out = buff.size();
  4493. auto next_out = buff.data();
  4494. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  4495. &available_out, &next_out, nullptr)) {
  4496. return false;
  4497. }
  4498. auto output_bytes = buff.size() - available_out;
  4499. if (output_bytes) {
  4500. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  4501. }
  4502. }
  4503. return true;
  4504. }
  4505. inline brotli_decompressor::brotli_decompressor() {
  4506. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  4507. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  4508. : BROTLI_DECODER_RESULT_ERROR;
  4509. }
  4510. inline brotli_decompressor::~brotli_decompressor() {
  4511. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  4512. }
  4513. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  4514. inline bool brotli_decompressor::decompress(const char *data,
  4515. size_t data_length,
  4516. Callback callback) {
  4517. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4518. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  4519. return 0;
  4520. }
  4521. auto next_in = reinterpret_cast<const uint8_t *>(data);
  4522. size_t avail_in = data_length;
  4523. size_t total_out;
  4524. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  4525. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4526. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  4527. char *next_out = buff.data();
  4528. size_t avail_out = buff.size();
  4529. decoder_r = BrotliDecoderDecompressStream(
  4530. decoder_s, &avail_in, &next_in, &avail_out,
  4531. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  4532. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  4533. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  4534. }
  4535. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  4536. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  4537. }
  4538. #endif
  4539. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4540. inline zstd_compressor::zstd_compressor() {
  4541. ctx_ = ZSTD_createCCtx();
  4542. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  4543. }
  4544. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  4545. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  4546. bool last, Callback callback) {
  4547. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4548. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  4549. ZSTD_inBuffer input = {data, data_length, 0};
  4550. bool finished;
  4551. do {
  4552. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4553. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  4554. if (ZSTD_isError(remaining)) { return false; }
  4555. if (!callback(buff.data(), output.pos)) { return false; }
  4556. finished = last ? (remaining == 0) : (input.pos == input.size);
  4557. } while (!finished);
  4558. return true;
  4559. }
  4560. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  4561. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  4562. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  4563. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  4564. Callback callback) {
  4565. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  4566. ZSTD_inBuffer input = {data, data_length, 0};
  4567. while (input.pos < input.size) {
  4568. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  4569. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  4570. if (ZSTD_isError(remaining)) { return false; }
  4571. if (!callback(buff.data(), output.pos)) { return false; }
  4572. }
  4573. return true;
  4574. }
  4575. #endif
  4576. inline std::unique_ptr<decompressor>
  4577. create_decompressor(const std::string &encoding) {
  4578. std::unique_ptr<decompressor> decompressor;
  4579. if (encoding == "gzip" || encoding == "deflate") {
  4580. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4581. decompressor = detail::make_unique<gzip_decompressor>();
  4582. #endif
  4583. } else if (encoding.find("br") != std::string::npos) {
  4584. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4585. decompressor = detail::make_unique<brotli_decompressor>();
  4586. #endif
  4587. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  4588. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4589. decompressor = detail::make_unique<zstd_decompressor>();
  4590. #endif
  4591. }
  4592. return decompressor;
  4593. }
  4594. inline bool is_prohibited_header_name(const std::string &name) {
  4595. using udl::operator""_t;
  4596. switch (str2tag(name)) {
  4597. case "REMOTE_ADDR"_t:
  4598. case "REMOTE_PORT"_t:
  4599. case "LOCAL_ADDR"_t:
  4600. case "LOCAL_PORT"_t: return true;
  4601. default: return false;
  4602. }
  4603. }
  4604. inline bool has_header(const Headers &headers, const std::string &key) {
  4605. if (is_prohibited_header_name(key)) { return false; }
  4606. return headers.find(key) != headers.end();
  4607. }
  4608. inline const char *get_header_value(const Headers &headers,
  4609. const std::string &key, const char *def,
  4610. size_t id) {
  4611. if (is_prohibited_header_name(key)) {
  4612. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4613. std::string msg = "Prohibited header name '" + key + "' is specified.";
  4614. throw std::invalid_argument(msg);
  4615. #else
  4616. return "";
  4617. #endif
  4618. }
  4619. auto rng = headers.equal_range(key);
  4620. auto it = rng.first;
  4621. std::advance(it, static_cast<ssize_t>(id));
  4622. if (it != rng.second) { return it->second.c_str(); }
  4623. return def;
  4624. }
  4625. inline bool read_headers(Stream &strm, Headers &headers) {
  4626. const auto bufsiz = 2048;
  4627. char buf[bufsiz];
  4628. stream_line_reader line_reader(strm, buf, bufsiz);
  4629. size_t header_count = 0;
  4630. for (;;) {
  4631. if (!line_reader.getline()) { return false; }
  4632. // Check if the line ends with CRLF.
  4633. auto line_terminator_len = 2;
  4634. if (line_reader.end_with_crlf()) {
  4635. // Blank line indicates end of headers.
  4636. if (line_reader.size() == 2) { break; }
  4637. } else {
  4638. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4639. // Blank line indicates end of headers.
  4640. if (line_reader.size() == 1) { break; }
  4641. line_terminator_len = 1;
  4642. #else
  4643. continue; // Skip invalid line.
  4644. #endif
  4645. }
  4646. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4647. // Check header count limit
  4648. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4649. // Exclude line terminator
  4650. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  4651. if (!parse_header(line_reader.ptr(), end,
  4652. [&](const std::string &key, const std::string &val) {
  4653. headers.emplace(key, val);
  4654. })) {
  4655. return false;
  4656. }
  4657. header_count++;
  4658. }
  4659. return true;
  4660. }
  4661. inline bool read_content_with_length(Stream &strm, size_t len,
  4662. DownloadProgress progress,
  4663. ContentReceiverWithProgress out) {
  4664. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4665. detail::BodyReader br;
  4666. br.stream = &strm;
  4667. br.content_length = len;
  4668. br.chunked = false;
  4669. br.bytes_read = 0;
  4670. br.last_error = Error::Success;
  4671. size_t r = 0;
  4672. while (r < len) {
  4673. auto read_len = static_cast<size_t>(len - r);
  4674. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  4675. auto n = detail::read_body_content(&strm, br, buf, to_read);
  4676. if (n <= 0) { return false; }
  4677. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  4678. r += static_cast<size_t>(n);
  4679. if (progress) {
  4680. if (!progress(r, len)) { return false; }
  4681. }
  4682. }
  4683. return true;
  4684. }
  4685. inline void skip_content_with_length(Stream &strm, size_t len) {
  4686. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4687. size_t r = 0;
  4688. while (r < len) {
  4689. auto read_len = static_cast<size_t>(len - r);
  4690. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  4691. if (n <= 0) { return; }
  4692. r += static_cast<size_t>(n);
  4693. }
  4694. }
  4695. enum class ReadContentResult {
  4696. Success, // Successfully read the content
  4697. PayloadTooLarge, // The content exceeds the specified payload limit
  4698. Error // An error occurred while reading the content
  4699. };
  4700. inline ReadContentResult
  4701. read_content_without_length(Stream &strm, size_t payload_max_length,
  4702. ContentReceiverWithProgress out) {
  4703. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4704. size_t r = 0;
  4705. for (;;) {
  4706. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  4707. if (n == 0) { return ReadContentResult::Success; }
  4708. if (n < 0) { return ReadContentResult::Error; }
  4709. // Check if adding this data would exceed the payload limit
  4710. if (r > payload_max_length ||
  4711. payload_max_length - r < static_cast<size_t>(n)) {
  4712. return ReadContentResult::PayloadTooLarge;
  4713. }
  4714. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  4715. return ReadContentResult::Error;
  4716. }
  4717. r += static_cast<size_t>(n);
  4718. }
  4719. return ReadContentResult::Success;
  4720. }
  4721. template <typename T>
  4722. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  4723. size_t payload_max_length,
  4724. ContentReceiverWithProgress out) {
  4725. detail::ChunkedDecoder dec(strm);
  4726. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  4727. size_t total_len = 0;
  4728. for (;;) {
  4729. size_t chunk_offset = 0;
  4730. size_t chunk_total = 0;
  4731. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  4732. if (n < 0) { return ReadContentResult::Error; }
  4733. if (n == 0) {
  4734. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  4735. return ReadContentResult::Error;
  4736. }
  4737. return ReadContentResult::Success;
  4738. }
  4739. if (total_len > payload_max_length ||
  4740. payload_max_length - total_len < static_cast<size_t>(n)) {
  4741. return ReadContentResult::PayloadTooLarge;
  4742. }
  4743. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  4744. return ReadContentResult::Error;
  4745. }
  4746. total_len += static_cast<size_t>(n);
  4747. }
  4748. }
  4749. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  4750. return case_ignore::equal(
  4751. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  4752. }
  4753. template <typename T, typename U>
  4754. bool prepare_content_receiver(T &x, int &status,
  4755. ContentReceiverWithProgress receiver,
  4756. bool decompress, U callback) {
  4757. if (decompress) {
  4758. std::string encoding = x.get_header_value("Content-Encoding");
  4759. std::unique_ptr<decompressor> decompressor;
  4760. if (!encoding.empty()) {
  4761. decompressor = detail::create_decompressor(encoding);
  4762. if (!decompressor) {
  4763. // Unsupported encoding or no support compiled in
  4764. status = StatusCode::UnsupportedMediaType_415;
  4765. return false;
  4766. }
  4767. }
  4768. if (decompressor) {
  4769. if (decompressor->is_valid()) {
  4770. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  4771. size_t off, size_t len) {
  4772. return decompressor->decompress(buf, n,
  4773. [&](const char *buf2, size_t n2) {
  4774. return receiver(buf2, n2, off, len);
  4775. });
  4776. };
  4777. return callback(std::move(out));
  4778. } else {
  4779. status = StatusCode::InternalServerError_500;
  4780. return false;
  4781. }
  4782. }
  4783. }
  4784. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  4785. size_t len) {
  4786. return receiver(buf, n, off, len);
  4787. };
  4788. return callback(std::move(out));
  4789. }
  4790. template <typename T>
  4791. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  4792. DownloadProgress progress,
  4793. ContentReceiverWithProgress receiver, bool decompress) {
  4794. return prepare_content_receiver(
  4795. x, status, std::move(receiver), decompress,
  4796. [&](const ContentReceiverWithProgress &out) {
  4797. auto ret = true;
  4798. auto exceed_payload_max_length = false;
  4799. if (is_chunked_transfer_encoding(x.headers)) {
  4800. auto result = read_content_chunked(strm, x, payload_max_length, out);
  4801. if (result == ReadContentResult::Success) {
  4802. ret = true;
  4803. } else if (result == ReadContentResult::PayloadTooLarge) {
  4804. exceed_payload_max_length = true;
  4805. ret = false;
  4806. } else {
  4807. ret = false;
  4808. }
  4809. } else if (!has_header(x.headers, "Content-Length")) {
  4810. auto result =
  4811. read_content_without_length(strm, payload_max_length, out);
  4812. if (result == ReadContentResult::Success) {
  4813. ret = true;
  4814. } else if (result == ReadContentResult::PayloadTooLarge) {
  4815. exceed_payload_max_length = true;
  4816. ret = false;
  4817. } else {
  4818. ret = false;
  4819. }
  4820. } else {
  4821. auto is_invalid_value = false;
  4822. auto len = get_header_value_u64(x.headers, "Content-Length",
  4823. (std::numeric_limits<size_t>::max)(),
  4824. 0, is_invalid_value);
  4825. if (is_invalid_value) {
  4826. ret = false;
  4827. } else if (len > payload_max_length) {
  4828. exceed_payload_max_length = true;
  4829. skip_content_with_length(strm, len);
  4830. ret = false;
  4831. } else if (len > 0) {
  4832. ret = read_content_with_length(strm, len, std::move(progress), out);
  4833. }
  4834. }
  4835. if (!ret) {
  4836. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  4837. : StatusCode::BadRequest_400;
  4838. }
  4839. return ret;
  4840. });
  4841. }
  4842. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  4843. const std::string &path) {
  4844. std::string s = method;
  4845. s += ' ';
  4846. s += path;
  4847. s += " HTTP/1.1\r\n";
  4848. return strm.write(s.data(), s.size());
  4849. }
  4850. inline ssize_t write_response_line(Stream &strm, int status) {
  4851. std::string s = "HTTP/1.1 ";
  4852. s += std::to_string(status);
  4853. s += ' ';
  4854. s += httplib::status_message(status);
  4855. s += "\r\n";
  4856. return strm.write(s.data(), s.size());
  4857. }
  4858. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  4859. ssize_t write_len = 0;
  4860. for (const auto &x : headers) {
  4861. std::string s;
  4862. s = x.first;
  4863. s += ": ";
  4864. s += x.second;
  4865. s += "\r\n";
  4866. auto len = strm.write(s.data(), s.size());
  4867. if (len < 0) { return len; }
  4868. write_len += len;
  4869. }
  4870. auto len = strm.write("\r\n");
  4871. if (len < 0) { return len; }
  4872. write_len += len;
  4873. return write_len;
  4874. }
  4875. inline bool write_data(Stream &strm, const char *d, size_t l) {
  4876. size_t offset = 0;
  4877. while (offset < l) {
  4878. auto length = strm.write(d + offset, l - offset);
  4879. if (length < 0) { return false; }
  4880. offset += static_cast<size_t>(length);
  4881. }
  4882. return true;
  4883. }
  4884. template <typename T>
  4885. inline bool write_content_with_progress(Stream &strm,
  4886. const ContentProvider &content_provider,
  4887. size_t offset, size_t length,
  4888. T is_shutting_down,
  4889. const UploadProgress &upload_progress,
  4890. Error &error) {
  4891. size_t end_offset = offset + length;
  4892. size_t start_offset = offset;
  4893. auto ok = true;
  4894. DataSink data_sink;
  4895. data_sink.write = [&](const char *d, size_t l) -> bool {
  4896. if (ok) {
  4897. if (write_data(strm, d, l)) {
  4898. offset += l;
  4899. if (upload_progress && length > 0) {
  4900. size_t current_written = offset - start_offset;
  4901. if (!upload_progress(current_written, length)) {
  4902. ok = false;
  4903. return false;
  4904. }
  4905. }
  4906. } else {
  4907. ok = false;
  4908. }
  4909. }
  4910. return ok;
  4911. };
  4912. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4913. while (offset < end_offset && !is_shutting_down()) {
  4914. if (!strm.wait_writable()) {
  4915. error = Error::Write;
  4916. return false;
  4917. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  4918. error = Error::Canceled;
  4919. return false;
  4920. } else if (!ok) {
  4921. error = Error::Write;
  4922. return false;
  4923. }
  4924. }
  4925. error = Error::Success;
  4926. return true;
  4927. }
  4928. template <typename T>
  4929. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4930. size_t offset, size_t length, T is_shutting_down,
  4931. Error &error) {
  4932. return write_content_with_progress<T>(strm, content_provider, offset, length,
  4933. is_shutting_down, nullptr, error);
  4934. }
  4935. template <typename T>
  4936. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4937. size_t offset, size_t length,
  4938. const T &is_shutting_down) {
  4939. auto error = Error::Success;
  4940. return write_content(strm, content_provider, offset, length, is_shutting_down,
  4941. error);
  4942. }
  4943. template <typename T>
  4944. inline bool
  4945. write_content_without_length(Stream &strm,
  4946. const ContentProvider &content_provider,
  4947. const T &is_shutting_down) {
  4948. size_t offset = 0;
  4949. auto data_available = true;
  4950. auto ok = true;
  4951. DataSink data_sink;
  4952. data_sink.write = [&](const char *d, size_t l) -> bool {
  4953. if (ok) {
  4954. offset += l;
  4955. if (!write_data(strm, d, l)) { ok = false; }
  4956. }
  4957. return ok;
  4958. };
  4959. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4960. data_sink.done = [&](void) { data_available = false; };
  4961. while (data_available && !is_shutting_down()) {
  4962. if (!strm.wait_writable()) {
  4963. return false;
  4964. } else if (!content_provider(offset, 0, data_sink)) {
  4965. return false;
  4966. } else if (!ok) {
  4967. return false;
  4968. }
  4969. }
  4970. return true;
  4971. }
  4972. template <typename T, typename U>
  4973. inline bool
  4974. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  4975. const T &is_shutting_down, U &compressor, Error &error) {
  4976. size_t offset = 0;
  4977. auto data_available = true;
  4978. auto ok = true;
  4979. DataSink data_sink;
  4980. data_sink.write = [&](const char *d, size_t l) -> bool {
  4981. if (ok) {
  4982. data_available = l > 0;
  4983. offset += l;
  4984. std::string payload;
  4985. if (compressor.compress(d, l, false,
  4986. [&](const char *data, size_t data_len) {
  4987. payload.append(data, data_len);
  4988. return true;
  4989. })) {
  4990. if (!payload.empty()) {
  4991. // Emit chunked response header and footer for each chunk
  4992. auto chunk =
  4993. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4994. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  4995. }
  4996. } else {
  4997. ok = false;
  4998. }
  4999. }
  5000. return ok;
  5001. };
  5002. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  5003. auto done_with_trailer = [&](const Headers *trailer) {
  5004. if (!ok) { return; }
  5005. data_available = false;
  5006. std::string payload;
  5007. if (!compressor.compress(nullptr, 0, true,
  5008. [&](const char *data, size_t data_len) {
  5009. payload.append(data, data_len);
  5010. return true;
  5011. })) {
  5012. ok = false;
  5013. return;
  5014. }
  5015. if (!payload.empty()) {
  5016. // Emit chunked response header and footer for each chunk
  5017. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  5018. if (!write_data(strm, chunk.data(), chunk.size())) {
  5019. ok = false;
  5020. return;
  5021. }
  5022. }
  5023. constexpr const char done_marker[] = "0\r\n";
  5024. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  5025. // Trailer
  5026. if (trailer) {
  5027. for (const auto &kv : *trailer) {
  5028. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  5029. if (!write_data(strm, field_line.data(), field_line.size())) {
  5030. ok = false;
  5031. }
  5032. }
  5033. }
  5034. constexpr const char crlf[] = "\r\n";
  5035. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  5036. };
  5037. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  5038. data_sink.done_with_trailer = [&](const Headers &trailer) {
  5039. done_with_trailer(&trailer);
  5040. };
  5041. while (data_available && !is_shutting_down()) {
  5042. if (!strm.wait_writable()) {
  5043. error = Error::Write;
  5044. return false;
  5045. } else if (!content_provider(offset, 0, data_sink)) {
  5046. error = Error::Canceled;
  5047. return false;
  5048. } else if (!ok) {
  5049. error = Error::Write;
  5050. return false;
  5051. }
  5052. }
  5053. error = Error::Success;
  5054. return true;
  5055. }
  5056. template <typename T, typename U>
  5057. inline bool write_content_chunked(Stream &strm,
  5058. const ContentProvider &content_provider,
  5059. const T &is_shutting_down, U &compressor) {
  5060. auto error = Error::Success;
  5061. return write_content_chunked(strm, content_provider, is_shutting_down,
  5062. compressor, error);
  5063. }
  5064. template <typename T>
  5065. inline bool redirect(T &cli, Request &req, Response &res,
  5066. const std::string &path, const std::string &location,
  5067. Error &error) {
  5068. Request new_req = req;
  5069. new_req.path = path;
  5070. new_req.redirect_count_ -= 1;
  5071. if (res.status == StatusCode::SeeOther_303 &&
  5072. (req.method != "GET" && req.method != "HEAD")) {
  5073. new_req.method = "GET";
  5074. new_req.body.clear();
  5075. new_req.headers.clear();
  5076. }
  5077. Response new_res;
  5078. auto ret = cli.send(new_req, new_res, error);
  5079. if (ret) {
  5080. req = std::move(new_req);
  5081. res = std::move(new_res);
  5082. if (res.location.empty()) { res.location = location; }
  5083. }
  5084. return ret;
  5085. }
  5086. inline std::string params_to_query_str(const Params &params) {
  5087. std::string query;
  5088. for (auto it = params.begin(); it != params.end(); ++it) {
  5089. if (it != params.begin()) { query += '&'; }
  5090. query += encode_query_component(it->first);
  5091. query += '=';
  5092. query += encode_query_component(it->second);
  5093. }
  5094. return query;
  5095. }
  5096. inline void parse_query_text(const char *data, std::size_t size,
  5097. Params &params) {
  5098. std::set<std::string> cache;
  5099. split(data, data + size, '&', [&](const char *b, const char *e) {
  5100. std::string kv(b, e);
  5101. if (cache.find(kv) != cache.end()) { return; }
  5102. cache.insert(std::move(kv));
  5103. std::string key;
  5104. std::string val;
  5105. divide(b, static_cast<std::size_t>(e - b), '=',
  5106. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  5107. std::size_t rhs_size) {
  5108. key.assign(lhs_data, lhs_size);
  5109. val.assign(rhs_data, rhs_size);
  5110. });
  5111. if (!key.empty()) {
  5112. params.emplace(decode_query_component(key), decode_query_component(val));
  5113. }
  5114. });
  5115. }
  5116. inline void parse_query_text(const std::string &s, Params &params) {
  5117. parse_query_text(s.data(), s.size(), params);
  5118. }
  5119. // Normalize a query string by decoding and re-encoding each key/value pair
  5120. // while preserving the original parameter order. This avoids double-encoding
  5121. // and ensures consistent encoding without reordering (unlike Params which
  5122. // uses std::multimap and sorts keys).
  5123. inline std::string normalize_query_string(const std::string &query) {
  5124. std::string result;
  5125. split(query.data(), query.data() + query.size(), '&',
  5126. [&](const char *b, const char *e) {
  5127. std::string key;
  5128. std::string val;
  5129. divide(b, static_cast<std::size_t>(e - b), '=',
  5130. [&](const char *lhs_data, std::size_t lhs_size,
  5131. const char *rhs_data, std::size_t rhs_size) {
  5132. key.assign(lhs_data, lhs_size);
  5133. val.assign(rhs_data, rhs_size);
  5134. });
  5135. if (!key.empty()) {
  5136. auto dec_key = decode_query_component(key);
  5137. auto dec_val = decode_query_component(val);
  5138. if (!result.empty()) { result += '&'; }
  5139. result += encode_query_component(dec_key);
  5140. if (!val.empty() || std::find(b, e, '=') != e) {
  5141. result += '=';
  5142. result += encode_query_component(dec_val);
  5143. }
  5144. }
  5145. });
  5146. return result;
  5147. }
  5148. inline bool parse_multipart_boundary(const std::string &content_type,
  5149. std::string &boundary) {
  5150. auto boundary_keyword = "boundary=";
  5151. auto pos = content_type.find(boundary_keyword);
  5152. if (pos == std::string::npos) { return false; }
  5153. auto end = content_type.find(';', pos);
  5154. auto beg = pos + strlen(boundary_keyword);
  5155. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  5156. return !boundary.empty();
  5157. }
  5158. inline void parse_disposition_params(const std::string &s, Params &params) {
  5159. std::set<std::string> cache;
  5160. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  5161. std::string kv(b, e);
  5162. if (cache.find(kv) != cache.end()) { return; }
  5163. cache.insert(kv);
  5164. std::string key;
  5165. std::string val;
  5166. split(b, e, '=', [&](const char *b2, const char *e2) {
  5167. if (key.empty()) {
  5168. key.assign(b2, e2);
  5169. } else {
  5170. val.assign(b2, e2);
  5171. }
  5172. });
  5173. if (!key.empty()) {
  5174. params.emplace(trim_double_quotes_copy((key)),
  5175. trim_double_quotes_copy((val)));
  5176. }
  5177. });
  5178. }
  5179. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5180. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  5181. #else
  5182. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  5183. #endif
  5184. auto is_valid = [](const std::string &str) {
  5185. return std::all_of(str.cbegin(), str.cend(),
  5186. [](unsigned char c) { return std::isdigit(c); });
  5187. };
  5188. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  5189. const auto pos = static_cast<size_t>(6);
  5190. const auto len = static_cast<size_t>(s.size() - 6);
  5191. auto all_valid_ranges = true;
  5192. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  5193. if (!all_valid_ranges) { return; }
  5194. const auto it = std::find(b, e, '-');
  5195. if (it == e) {
  5196. all_valid_ranges = false;
  5197. return;
  5198. }
  5199. const auto lhs = std::string(b, it);
  5200. const auto rhs = std::string(it + 1, e);
  5201. if (!is_valid(lhs) || !is_valid(rhs)) {
  5202. all_valid_ranges = false;
  5203. return;
  5204. }
  5205. const auto first =
  5206. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  5207. const auto last =
  5208. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  5209. if ((first == -1 && last == -1) ||
  5210. (first != -1 && last != -1 && first > last)) {
  5211. all_valid_ranges = false;
  5212. return;
  5213. }
  5214. ranges.emplace_back(first, last);
  5215. });
  5216. return all_valid_ranges && !ranges.empty();
  5217. }
  5218. return false;
  5219. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5220. }
  5221. #else
  5222. } catch (...) { return false; }
  5223. #endif
  5224. inline bool parse_accept_header(const std::string &s,
  5225. std::vector<std::string> &content_types) {
  5226. content_types.clear();
  5227. // Empty string is considered valid (no preference)
  5228. if (s.empty()) { return true; }
  5229. // Check for invalid patterns: leading/trailing commas or consecutive commas
  5230. if (s.front() == ',' || s.back() == ',' ||
  5231. s.find(",,") != std::string::npos) {
  5232. return false;
  5233. }
  5234. struct AcceptEntry {
  5235. std::string media_type;
  5236. double quality;
  5237. int order; // Original order in header
  5238. };
  5239. std::vector<AcceptEntry> entries;
  5240. int order = 0;
  5241. bool has_invalid_entry = false;
  5242. // Split by comma and parse each entry
  5243. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5244. std::string entry(b, e);
  5245. entry = trim_copy(entry);
  5246. if (entry.empty()) {
  5247. has_invalid_entry = true;
  5248. return;
  5249. }
  5250. AcceptEntry accept_entry;
  5251. accept_entry.quality = 1.0; // Default quality
  5252. accept_entry.order = order++;
  5253. // Find q= parameter
  5254. auto q_pos = entry.find(";q=");
  5255. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  5256. if (q_pos != std::string::npos) {
  5257. // Extract media type (before q parameter)
  5258. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  5259. // Extract quality value
  5260. auto q_start = entry.find('=', q_pos) + 1;
  5261. auto q_end = entry.find(';', q_start);
  5262. if (q_end == std::string::npos) { q_end = entry.length(); }
  5263. std::string quality_str =
  5264. trim_copy(entry.substr(q_start, q_end - q_start));
  5265. if (quality_str.empty()) {
  5266. has_invalid_entry = true;
  5267. return;
  5268. }
  5269. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5270. {
  5271. std::istringstream iss(quality_str);
  5272. iss >> accept_entry.quality;
  5273. // Check if conversion was successful and entire string was consumed
  5274. if (iss.fail() || !iss.eof()) {
  5275. has_invalid_entry = true;
  5276. return;
  5277. }
  5278. }
  5279. #else
  5280. try {
  5281. accept_entry.quality = std::stod(quality_str);
  5282. } catch (...) {
  5283. has_invalid_entry = true;
  5284. return;
  5285. }
  5286. #endif
  5287. // Check if quality is in valid range [0.0, 1.0]
  5288. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  5289. has_invalid_entry = true;
  5290. return;
  5291. }
  5292. } else {
  5293. // No quality parameter, use entire entry as media type
  5294. accept_entry.media_type = entry;
  5295. }
  5296. // Remove additional parameters from media type
  5297. auto param_pos = accept_entry.media_type.find(';');
  5298. if (param_pos != std::string::npos) {
  5299. accept_entry.media_type =
  5300. trim_copy(accept_entry.media_type.substr(0, param_pos));
  5301. }
  5302. // Basic validation of media type format
  5303. if (accept_entry.media_type.empty()) {
  5304. has_invalid_entry = true;
  5305. return;
  5306. }
  5307. // Check for basic media type format (should contain '/' or be '*')
  5308. if (accept_entry.media_type != "*" &&
  5309. accept_entry.media_type.find('/') == std::string::npos) {
  5310. has_invalid_entry = true;
  5311. return;
  5312. }
  5313. entries.push_back(std::move(accept_entry));
  5314. });
  5315. // Return false if any invalid entry was found
  5316. if (has_invalid_entry) { return false; }
  5317. // Sort by quality (descending), then by original order (ascending)
  5318. std::sort(entries.begin(), entries.end(),
  5319. [](const AcceptEntry &a, const AcceptEntry &b) {
  5320. if (a.quality != b.quality) {
  5321. return a.quality > b.quality; // Higher quality first
  5322. }
  5323. return a.order < b.order; // Earlier order first for same quality
  5324. });
  5325. // Extract sorted media types
  5326. content_types.reserve(entries.size());
  5327. for (auto &entry : entries) {
  5328. content_types.push_back(std::move(entry.media_type));
  5329. }
  5330. return true;
  5331. }
  5332. class FormDataParser {
  5333. public:
  5334. FormDataParser() = default;
  5335. void set_boundary(std::string &&boundary) {
  5336. boundary_ = std::move(boundary);
  5337. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  5338. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  5339. }
  5340. bool is_valid() const { return is_valid_; }
  5341. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  5342. const ContentReceiver &content_callback) {
  5343. buf_append(buf, n);
  5344. while (buf_size() > 0) {
  5345. switch (state_) {
  5346. case 0: { // Initial boundary
  5347. auto pos = buf_find(dash_boundary_crlf_);
  5348. if (pos == buf_size()) { return true; }
  5349. buf_erase(pos + dash_boundary_crlf_.size());
  5350. state_ = 1;
  5351. break;
  5352. }
  5353. case 1: { // New entry
  5354. clear_file_info();
  5355. state_ = 2;
  5356. break;
  5357. }
  5358. case 2: { // Headers
  5359. auto pos = buf_find(crlf_);
  5360. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5361. while (pos < buf_size()) {
  5362. // Empty line
  5363. if (pos == 0) {
  5364. if (!header_callback(file_)) {
  5365. is_valid_ = false;
  5366. return false;
  5367. }
  5368. buf_erase(crlf_.size());
  5369. state_ = 3;
  5370. break;
  5371. }
  5372. const auto header = buf_head(pos);
  5373. if (!parse_header(header.data(), header.data() + header.size(),
  5374. [&](const std::string &, const std::string &) {})) {
  5375. is_valid_ = false;
  5376. return false;
  5377. }
  5378. // Parse and emplace space trimmed headers into a map
  5379. if (!parse_header(
  5380. header.data(), header.data() + header.size(),
  5381. [&](const std::string &key, const std::string &val) {
  5382. file_.headers.emplace(key, val);
  5383. })) {
  5384. is_valid_ = false;
  5385. return false;
  5386. }
  5387. constexpr const char header_content_type[] = "Content-Type:";
  5388. if (start_with_case_ignore(header, header_content_type)) {
  5389. file_.content_type =
  5390. trim_copy(header.substr(str_len(header_content_type)));
  5391. } else {
  5392. thread_local const std::regex re_content_disposition(
  5393. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  5394. std::regex_constants::icase);
  5395. std::smatch m;
  5396. if (std::regex_match(header, m, re_content_disposition)) {
  5397. Params params;
  5398. parse_disposition_params(m[1], params);
  5399. auto it = params.find("name");
  5400. if (it != params.end()) {
  5401. file_.name = it->second;
  5402. } else {
  5403. is_valid_ = false;
  5404. return false;
  5405. }
  5406. it = params.find("filename");
  5407. if (it != params.end()) { file_.filename = it->second; }
  5408. it = params.find("filename*");
  5409. if (it != params.end()) {
  5410. // Only allow UTF-8 encoding...
  5411. thread_local const std::regex re_rfc5987_encoding(
  5412. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  5413. std::smatch m2;
  5414. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  5415. file_.filename = decode_path_component(m2[1]); // override...
  5416. } else {
  5417. is_valid_ = false;
  5418. return false;
  5419. }
  5420. }
  5421. }
  5422. }
  5423. buf_erase(pos + crlf_.size());
  5424. pos = buf_find(crlf_);
  5425. }
  5426. if (state_ != 3) { return true; }
  5427. break;
  5428. }
  5429. case 3: { // Body
  5430. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  5431. auto pos = buf_find(crlf_dash_boundary_);
  5432. if (pos < buf_size()) {
  5433. if (!content_callback(buf_data(), pos)) {
  5434. is_valid_ = false;
  5435. return false;
  5436. }
  5437. buf_erase(pos + crlf_dash_boundary_.size());
  5438. state_ = 4;
  5439. } else {
  5440. auto len = buf_size() - crlf_dash_boundary_.size();
  5441. if (len > 0) {
  5442. if (!content_callback(buf_data(), len)) {
  5443. is_valid_ = false;
  5444. return false;
  5445. }
  5446. buf_erase(len);
  5447. }
  5448. return true;
  5449. }
  5450. break;
  5451. }
  5452. case 4: { // Boundary
  5453. if (crlf_.size() > buf_size()) { return true; }
  5454. if (buf_start_with(crlf_)) {
  5455. buf_erase(crlf_.size());
  5456. state_ = 1;
  5457. } else {
  5458. if (dash_.size() > buf_size()) { return true; }
  5459. if (buf_start_with(dash_)) {
  5460. buf_erase(dash_.size());
  5461. is_valid_ = true;
  5462. buf_erase(buf_size()); // Remove epilogue
  5463. } else {
  5464. return true;
  5465. }
  5466. }
  5467. break;
  5468. }
  5469. }
  5470. }
  5471. return true;
  5472. }
  5473. private:
  5474. void clear_file_info() {
  5475. file_.name.clear();
  5476. file_.filename.clear();
  5477. file_.content_type.clear();
  5478. file_.headers.clear();
  5479. }
  5480. bool start_with_case_ignore(const std::string &a, const char *b) const {
  5481. const auto b_len = strlen(b);
  5482. if (a.size() < b_len) { return false; }
  5483. for (size_t i = 0; i < b_len; i++) {
  5484. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  5485. return false;
  5486. }
  5487. }
  5488. return true;
  5489. }
  5490. const std::string dash_ = "--";
  5491. const std::string crlf_ = "\r\n";
  5492. std::string boundary_;
  5493. std::string dash_boundary_crlf_;
  5494. std::string crlf_dash_boundary_;
  5495. size_t state_ = 0;
  5496. bool is_valid_ = false;
  5497. FormData file_;
  5498. // Buffer
  5499. bool start_with(const std::string &a, size_t spos, size_t epos,
  5500. const std::string &b) const {
  5501. if (epos - spos < b.size()) { return false; }
  5502. for (size_t i = 0; i < b.size(); i++) {
  5503. if (a[i + spos] != b[i]) { return false; }
  5504. }
  5505. return true;
  5506. }
  5507. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  5508. const char *buf_data() const { return &buf_[buf_spos_]; }
  5509. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  5510. bool buf_start_with(const std::string &s) const {
  5511. return start_with(buf_, buf_spos_, buf_epos_, s);
  5512. }
  5513. size_t buf_find(const std::string &s) const {
  5514. auto c = s.front();
  5515. size_t off = buf_spos_;
  5516. while (off < buf_epos_) {
  5517. auto pos = off;
  5518. while (true) {
  5519. if (pos == buf_epos_) { return buf_size(); }
  5520. if (buf_[pos] == c) { break; }
  5521. pos++;
  5522. }
  5523. auto remaining_size = buf_epos_ - pos;
  5524. if (s.size() > remaining_size) { return buf_size(); }
  5525. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  5526. off = pos + 1;
  5527. }
  5528. return buf_size();
  5529. }
  5530. void buf_append(const char *data, size_t n) {
  5531. auto remaining_size = buf_size();
  5532. if (remaining_size > 0 && buf_spos_ > 0) {
  5533. for (size_t i = 0; i < remaining_size; i++) {
  5534. buf_[i] = buf_[buf_spos_ + i];
  5535. }
  5536. }
  5537. buf_spos_ = 0;
  5538. buf_epos_ = remaining_size;
  5539. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  5540. for (size_t i = 0; i < n; i++) {
  5541. buf_[buf_epos_ + i] = data[i];
  5542. }
  5543. buf_epos_ += n;
  5544. }
  5545. void buf_erase(size_t size) { buf_spos_ += size; }
  5546. std::string buf_;
  5547. size_t buf_spos_ = 0;
  5548. size_t buf_epos_ = 0;
  5549. };
  5550. inline std::string random_string(size_t length) {
  5551. constexpr const char data[] =
  5552. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  5553. thread_local auto engine([]() {
  5554. // std::random_device might actually be deterministic on some
  5555. // platforms, but due to lack of support in the c++ standard library,
  5556. // doing better requires either some ugly hacks or breaking portability.
  5557. std::random_device seed_gen;
  5558. // Request 128 bits of entropy for initialization
  5559. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  5560. return std::mt19937(seed_sequence);
  5561. }());
  5562. std::string result;
  5563. for (size_t i = 0; i < length; i++) {
  5564. result += data[engine() % (sizeof(data) - 1)];
  5565. }
  5566. return result;
  5567. }
  5568. inline std::string make_multipart_data_boundary() {
  5569. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  5570. }
  5571. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  5572. auto valid = true;
  5573. for (size_t i = 0; i < boundary.size(); i++) {
  5574. auto c = boundary[i];
  5575. if (!std::isalnum(c) && c != '-' && c != '_') {
  5576. valid = false;
  5577. break;
  5578. }
  5579. }
  5580. return valid;
  5581. }
  5582. template <typename T>
  5583. inline std::string
  5584. serialize_multipart_formdata_item_begin(const T &item,
  5585. const std::string &boundary) {
  5586. std::string body = "--" + boundary + "\r\n";
  5587. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5588. if (!item.filename.empty()) {
  5589. body += "; filename=\"" + item.filename + "\"";
  5590. }
  5591. body += "\r\n";
  5592. if (!item.content_type.empty()) {
  5593. body += "Content-Type: " + item.content_type + "\r\n";
  5594. }
  5595. body += "\r\n";
  5596. return body;
  5597. }
  5598. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  5599. inline std::string
  5600. serialize_multipart_formdata_finish(const std::string &boundary) {
  5601. return "--" + boundary + "--\r\n";
  5602. }
  5603. inline std::string
  5604. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  5605. return "multipart/form-data; boundary=" + boundary;
  5606. }
  5607. inline std::string
  5608. serialize_multipart_formdata(const UploadFormDataItems &items,
  5609. const std::string &boundary, bool finish = true) {
  5610. std::string body;
  5611. for (const auto &item : items) {
  5612. body += serialize_multipart_formdata_item_begin(item, boundary);
  5613. body += item.content + serialize_multipart_formdata_item_end();
  5614. }
  5615. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  5616. return body;
  5617. }
  5618. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  5619. if (ranges.size() <= 1) return;
  5620. // Sort ranges by start position
  5621. std::sort(ranges.begin(), ranges.end(),
  5622. [](const Range &a, const Range &b) { return a.first < b.first; });
  5623. Ranges coalesced;
  5624. coalesced.reserve(ranges.size());
  5625. for (auto &r : ranges) {
  5626. auto first_pos = r.first;
  5627. auto last_pos = r.second;
  5628. // Handle special cases like in range_error
  5629. if (first_pos == -1 && last_pos == -1) {
  5630. first_pos = 0;
  5631. last_pos = static_cast<ssize_t>(content_length);
  5632. }
  5633. if (first_pos == -1) {
  5634. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  5635. last_pos = static_cast<ssize_t>(content_length) - 1;
  5636. }
  5637. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  5638. last_pos = static_cast<ssize_t>(content_length) - 1;
  5639. }
  5640. // Skip invalid ranges
  5641. if (!(0 <= first_pos && first_pos <= last_pos &&
  5642. last_pos < static_cast<ssize_t>(content_length))) {
  5643. continue;
  5644. }
  5645. // Coalesce with previous range if overlapping or adjacent (but not
  5646. // identical)
  5647. if (!coalesced.empty()) {
  5648. auto &prev = coalesced.back();
  5649. // Check if current range overlaps or is adjacent to previous range
  5650. // but don't coalesce identical ranges (allow duplicates)
  5651. if (first_pos <= prev.second + 1 &&
  5652. !(first_pos == prev.first && last_pos == prev.second)) {
  5653. // Extend the previous range
  5654. prev.second = (std::max)(prev.second, last_pos);
  5655. continue;
  5656. }
  5657. }
  5658. // Add new range
  5659. coalesced.emplace_back(first_pos, last_pos);
  5660. }
  5661. ranges = std::move(coalesced);
  5662. }
  5663. inline bool range_error(Request &req, Response &res) {
  5664. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  5665. ssize_t content_len = static_cast<ssize_t>(
  5666. res.content_length_ ? res.content_length_ : res.body.size());
  5667. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  5668. size_t overwrapping_count = 0;
  5669. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  5670. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  5671. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  5672. // Too many ranges
  5673. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  5674. for (auto &r : req.ranges) {
  5675. auto &first_pos = r.first;
  5676. auto &last_pos = r.second;
  5677. if (first_pos == -1 && last_pos == -1) {
  5678. first_pos = 0;
  5679. last_pos = content_len;
  5680. }
  5681. if (first_pos == -1) {
  5682. first_pos = content_len - last_pos;
  5683. last_pos = content_len - 1;
  5684. }
  5685. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  5686. // A client can limit the number of bytes requested without knowing the
  5687. // size of the selected representation. If the last-pos value is absent,
  5688. // or if the value is greater than or equal to the current length of the
  5689. // representation data, the byte range is interpreted as the remainder of
  5690. // the representation (i.e., the server replaces the value of last-pos
  5691. // with a value that is one less than the current length of the selected
  5692. // representation).
  5693. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  5694. if (last_pos == -1 || last_pos >= content_len) {
  5695. last_pos = content_len - 1;
  5696. }
  5697. // Range must be within content length
  5698. if (!(0 <= first_pos && first_pos <= last_pos &&
  5699. last_pos <= content_len - 1)) {
  5700. return true;
  5701. }
  5702. // Request must not have more than two overlapping ranges
  5703. for (const auto &processed_range : processed_ranges) {
  5704. if (!(last_pos < processed_range.first ||
  5705. first_pos > processed_range.second)) {
  5706. overwrapping_count++;
  5707. if (overwrapping_count > 2) { return true; }
  5708. break; // Only count once per range
  5709. }
  5710. }
  5711. processed_ranges.emplace_back(first_pos, last_pos);
  5712. }
  5713. // After validation, coalesce overlapping ranges as per RFC 9110
  5714. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  5715. }
  5716. return false;
  5717. }
  5718. inline std::pair<size_t, size_t>
  5719. get_range_offset_and_length(Range r, size_t content_length) {
  5720. assert(r.first != -1 && r.second != -1);
  5721. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  5722. assert(r.first <= r.second &&
  5723. r.second < static_cast<ssize_t>(content_length));
  5724. (void)(content_length);
  5725. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  5726. }
  5727. inline std::string make_content_range_header_field(
  5728. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  5729. auto st = offset_and_length.first;
  5730. auto ed = st + offset_and_length.second - 1;
  5731. std::string field = "bytes ";
  5732. field += std::to_string(st);
  5733. field += '-';
  5734. field += std::to_string(ed);
  5735. field += '/';
  5736. field += std::to_string(content_length);
  5737. return field;
  5738. }
  5739. template <typename SToken, typename CToken, typename Content>
  5740. bool process_multipart_ranges_data(const Request &req,
  5741. const std::string &boundary,
  5742. const std::string &content_type,
  5743. size_t content_length, SToken stoken,
  5744. CToken ctoken, Content content) {
  5745. for (size_t i = 0; i < req.ranges.size(); i++) {
  5746. ctoken("--");
  5747. stoken(boundary);
  5748. ctoken("\r\n");
  5749. if (!content_type.empty()) {
  5750. ctoken("Content-Type: ");
  5751. stoken(content_type);
  5752. ctoken("\r\n");
  5753. }
  5754. auto offset_and_length =
  5755. get_range_offset_and_length(req.ranges[i], content_length);
  5756. ctoken("Content-Range: ");
  5757. stoken(make_content_range_header_field(offset_and_length, content_length));
  5758. ctoken("\r\n");
  5759. ctoken("\r\n");
  5760. if (!content(offset_and_length.first, offset_and_length.second)) {
  5761. return false;
  5762. }
  5763. ctoken("\r\n");
  5764. }
  5765. ctoken("--");
  5766. stoken(boundary);
  5767. ctoken("--");
  5768. return true;
  5769. }
  5770. inline void make_multipart_ranges_data(const Request &req, Response &res,
  5771. const std::string &boundary,
  5772. const std::string &content_type,
  5773. size_t content_length,
  5774. std::string &data) {
  5775. process_multipart_ranges_data(
  5776. req, boundary, content_type, content_length,
  5777. [&](const std::string &token) { data += token; },
  5778. [&](const std::string &token) { data += token; },
  5779. [&](size_t offset, size_t length) {
  5780. assert(offset + length <= content_length);
  5781. data += res.body.substr(offset, length);
  5782. return true;
  5783. });
  5784. }
  5785. inline size_t get_multipart_ranges_data_length(const Request &req,
  5786. const std::string &boundary,
  5787. const std::string &content_type,
  5788. size_t content_length) {
  5789. size_t data_length = 0;
  5790. process_multipart_ranges_data(
  5791. req, boundary, content_type, content_length,
  5792. [&](const std::string &token) { data_length += token.size(); },
  5793. [&](const std::string &token) { data_length += token.size(); },
  5794. [&](size_t /*offset*/, size_t length) {
  5795. data_length += length;
  5796. return true;
  5797. });
  5798. return data_length;
  5799. }
  5800. template <typename T>
  5801. inline bool
  5802. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  5803. const std::string &boundary,
  5804. const std::string &content_type,
  5805. size_t content_length, const T &is_shutting_down) {
  5806. return process_multipart_ranges_data(
  5807. req, boundary, content_type, content_length,
  5808. [&](const std::string &token) { strm.write(token); },
  5809. [&](const std::string &token) { strm.write(token); },
  5810. [&](size_t offset, size_t length) {
  5811. return write_content(strm, res.content_provider_, offset, length,
  5812. is_shutting_down);
  5813. });
  5814. }
  5815. inline bool expect_content(const Request &req) {
  5816. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  5817. req.method == "DELETE") {
  5818. return true;
  5819. }
  5820. if (req.has_header("Content-Length") &&
  5821. req.get_header_value_u64("Content-Length") > 0) {
  5822. return true;
  5823. }
  5824. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  5825. return false;
  5826. }
  5827. inline bool has_crlf(const std::string &s) {
  5828. auto p = s.c_str();
  5829. while (*p) {
  5830. if (*p == '\r' || *p == '\n') { return true; }
  5831. p++;
  5832. }
  5833. return false;
  5834. }
  5835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5836. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  5837. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  5838. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  5839. unsigned int hash_length = 0;
  5840. unsigned char hash[EVP_MAX_MD_SIZE];
  5841. EVP_DigestInit_ex(context.get(), algo, nullptr);
  5842. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  5843. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  5844. std::stringstream ss;
  5845. for (auto i = 0u; i < hash_length; ++i) {
  5846. ss << std::hex << std::setw(2) << std::setfill('0')
  5847. << static_cast<unsigned int>(hash[i]);
  5848. }
  5849. return ss.str();
  5850. }
  5851. inline std::string MD5(const std::string &s) {
  5852. return message_digest(s, EVP_md5());
  5853. }
  5854. inline std::string SHA_256(const std::string &s) {
  5855. return message_digest(s, EVP_sha256());
  5856. }
  5857. inline std::string SHA_512(const std::string &s) {
  5858. return message_digest(s, EVP_sha512());
  5859. }
  5860. inline std::pair<std::string, std::string> make_digest_authentication_header(
  5861. const Request &req, const std::map<std::string, std::string> &auth,
  5862. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  5863. const std::string &password, bool is_proxy = false) {
  5864. std::string nc;
  5865. {
  5866. std::stringstream ss;
  5867. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  5868. nc = ss.str();
  5869. }
  5870. std::string qop;
  5871. if (auth.find("qop") != auth.end()) {
  5872. qop = auth.at("qop");
  5873. if (qop.find("auth-int") != std::string::npos) {
  5874. qop = "auth-int";
  5875. } else if (qop.find("auth") != std::string::npos) {
  5876. qop = "auth";
  5877. } else {
  5878. qop.clear();
  5879. }
  5880. }
  5881. std::string algo = "MD5";
  5882. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  5883. std::string response;
  5884. {
  5885. auto H = algo == "SHA-256" ? detail::SHA_256
  5886. : algo == "SHA-512" ? detail::SHA_512
  5887. : detail::MD5;
  5888. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  5889. auto A2 = req.method + ":" + req.path;
  5890. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  5891. if (qop.empty()) {
  5892. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  5893. } else {
  5894. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  5895. ":" + qop + ":" + H(A2));
  5896. }
  5897. }
  5898. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  5899. auto field = "Digest username=\"" + username + "\", realm=\"" +
  5900. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  5901. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  5902. (qop.empty() ? ", response=\""
  5903. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  5904. cnonce + "\", response=\"") +
  5905. response + "\"" +
  5906. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  5907. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5908. return std::make_pair(key, field);
  5909. }
  5910. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  5911. detail::set_nonblocking(sock, true);
  5912. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  5913. char buf[1];
  5914. return !SSL_peek(ssl, buf, 1) &&
  5915. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  5916. }
  5917. #ifdef _WIN32
  5918. // NOTE: This code came up with the following stackoverflow post:
  5919. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  5920. inline bool load_system_certs_on_windows(X509_STORE *store) {
  5921. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  5922. if (!hStore) { return false; }
  5923. auto result = false;
  5924. PCCERT_CONTEXT pContext = NULL;
  5925. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  5926. nullptr) {
  5927. auto encoded_cert =
  5928. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  5929. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  5930. if (x509) {
  5931. X509_STORE_add_cert(store, x509);
  5932. X509_free(x509);
  5933. result = true;
  5934. }
  5935. }
  5936. CertFreeCertificateContext(pContext);
  5937. CertCloseStore(hStore, 0);
  5938. return result;
  5939. }
  5940. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  5941. template <typename T>
  5942. using CFObjectPtr =
  5943. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  5944. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  5945. if (obj) { CFRelease(obj); }
  5946. }
  5947. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5948. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  5949. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  5950. kCFBooleanTrue};
  5951. CFObjectPtr<CFDictionaryRef> query(
  5952. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  5953. sizeof(keys) / sizeof(keys[0]),
  5954. &kCFTypeDictionaryKeyCallBacks,
  5955. &kCFTypeDictionaryValueCallBacks),
  5956. cf_object_ptr_deleter);
  5957. if (!query) { return false; }
  5958. CFTypeRef security_items = nullptr;
  5959. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  5960. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  5961. return false;
  5962. }
  5963. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  5964. return true;
  5965. }
  5966. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5967. CFArrayRef root_security_items = nullptr;
  5968. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  5969. return false;
  5970. }
  5971. certs.reset(root_security_items);
  5972. return true;
  5973. }
  5974. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  5975. auto result = false;
  5976. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  5977. const auto cert = reinterpret_cast<const __SecCertificate *>(
  5978. CFArrayGetValueAtIndex(certs, i));
  5979. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  5980. CFDataRef cert_data = nullptr;
  5981. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  5982. errSecSuccess) {
  5983. continue;
  5984. }
  5985. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  5986. auto encoded_cert = static_cast<const unsigned char *>(
  5987. CFDataGetBytePtr(cert_data_ptr.get()));
  5988. auto x509 =
  5989. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  5990. if (x509) {
  5991. X509_STORE_add_cert(store, x509);
  5992. X509_free(x509);
  5993. result = true;
  5994. }
  5995. }
  5996. return result;
  5997. }
  5998. inline bool load_system_certs_on_macos(X509_STORE *store) {
  5999. auto result = false;
  6000. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  6001. if (retrieve_certs_from_keychain(certs) && certs) {
  6002. result = add_certs_to_x509_store(certs.get(), store);
  6003. }
  6004. if (retrieve_root_certs_from_keychain(certs) && certs) {
  6005. result = add_certs_to_x509_store(certs.get(), store) || result;
  6006. }
  6007. return result;
  6008. }
  6009. #endif // _WIN32
  6010. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  6011. #ifdef _WIN32
  6012. class WSInit {
  6013. public:
  6014. WSInit() {
  6015. WSADATA wsaData;
  6016. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  6017. }
  6018. ~WSInit() {
  6019. if (is_valid_) WSACleanup();
  6020. }
  6021. bool is_valid_ = false;
  6022. };
  6023. static WSInit wsinit_;
  6024. #endif
  6025. inline bool parse_www_authenticate(const Response &res,
  6026. std::map<std::string, std::string> &auth,
  6027. bool is_proxy) {
  6028. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  6029. if (res.has_header(auth_key)) {
  6030. thread_local auto re =
  6031. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  6032. auto s = res.get_header_value(auth_key);
  6033. auto pos = s.find(' ');
  6034. if (pos != std::string::npos) {
  6035. auto type = s.substr(0, pos);
  6036. if (type == "Basic") {
  6037. return false;
  6038. } else if (type == "Digest") {
  6039. s = s.substr(pos + 1);
  6040. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  6041. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  6042. const auto &m = *i;
  6043. auto key = s.substr(static_cast<size_t>(m.position(1)),
  6044. static_cast<size_t>(m.length(1)));
  6045. auto val = m.length(2) > 0
  6046. ? s.substr(static_cast<size_t>(m.position(2)),
  6047. static_cast<size_t>(m.length(2)))
  6048. : s.substr(static_cast<size_t>(m.position(3)),
  6049. static_cast<size_t>(m.length(3)));
  6050. auth[std::move(key)] = std::move(val);
  6051. }
  6052. return true;
  6053. }
  6054. }
  6055. }
  6056. return false;
  6057. }
  6058. class ContentProviderAdapter {
  6059. public:
  6060. explicit ContentProviderAdapter(
  6061. ContentProviderWithoutLength &&content_provider)
  6062. : content_provider_(std::move(content_provider)) {}
  6063. bool operator()(size_t offset, size_t, DataSink &sink) {
  6064. return content_provider_(offset, sink);
  6065. }
  6066. private:
  6067. ContentProviderWithoutLength content_provider_;
  6068. };
  6069. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  6070. namespace fields {
  6071. inline bool is_token_char(char c) {
  6072. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  6073. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  6074. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  6075. }
  6076. inline bool is_token(const std::string &s) {
  6077. if (s.empty()) { return false; }
  6078. for (auto c : s) {
  6079. if (!is_token_char(c)) { return false; }
  6080. }
  6081. return true;
  6082. }
  6083. inline bool is_field_name(const std::string &s) { return is_token(s); }
  6084. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  6085. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  6086. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  6087. inline bool is_field_content(const std::string &s) {
  6088. if (s.empty()) { return true; }
  6089. if (s.size() == 1) {
  6090. return is_field_vchar(s[0]);
  6091. } else if (s.size() == 2) {
  6092. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  6093. } else {
  6094. size_t i = 0;
  6095. if (!is_field_vchar(s[i])) { return false; }
  6096. i++;
  6097. while (i < s.size() - 1) {
  6098. auto c = s[i++];
  6099. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  6100. } else {
  6101. return false;
  6102. }
  6103. }
  6104. return is_field_vchar(s[i]);
  6105. }
  6106. }
  6107. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  6108. } // namespace fields
  6109. } // namespace detail
  6110. inline const char *status_message(int status) {
  6111. switch (status) {
  6112. case StatusCode::Continue_100: return "Continue";
  6113. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  6114. case StatusCode::Processing_102: return "Processing";
  6115. case StatusCode::EarlyHints_103: return "Early Hints";
  6116. case StatusCode::OK_200: return "OK";
  6117. case StatusCode::Created_201: return "Created";
  6118. case StatusCode::Accepted_202: return "Accepted";
  6119. case StatusCode::NonAuthoritativeInformation_203:
  6120. return "Non-Authoritative Information";
  6121. case StatusCode::NoContent_204: return "No Content";
  6122. case StatusCode::ResetContent_205: return "Reset Content";
  6123. case StatusCode::PartialContent_206: return "Partial Content";
  6124. case StatusCode::MultiStatus_207: return "Multi-Status";
  6125. case StatusCode::AlreadyReported_208: return "Already Reported";
  6126. case StatusCode::IMUsed_226: return "IM Used";
  6127. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  6128. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  6129. case StatusCode::Found_302: return "Found";
  6130. case StatusCode::SeeOther_303: return "See Other";
  6131. case StatusCode::NotModified_304: return "Not Modified";
  6132. case StatusCode::UseProxy_305: return "Use Proxy";
  6133. case StatusCode::unused_306: return "unused";
  6134. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  6135. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  6136. case StatusCode::BadRequest_400: return "Bad Request";
  6137. case StatusCode::Unauthorized_401: return "Unauthorized";
  6138. case StatusCode::PaymentRequired_402: return "Payment Required";
  6139. case StatusCode::Forbidden_403: return "Forbidden";
  6140. case StatusCode::NotFound_404: return "Not Found";
  6141. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  6142. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  6143. case StatusCode::ProxyAuthenticationRequired_407:
  6144. return "Proxy Authentication Required";
  6145. case StatusCode::RequestTimeout_408: return "Request Timeout";
  6146. case StatusCode::Conflict_409: return "Conflict";
  6147. case StatusCode::Gone_410: return "Gone";
  6148. case StatusCode::LengthRequired_411: return "Length Required";
  6149. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  6150. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  6151. case StatusCode::UriTooLong_414: return "URI Too Long";
  6152. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  6153. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  6154. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  6155. case StatusCode::ImATeapot_418: return "I'm a teapot";
  6156. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  6157. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  6158. case StatusCode::Locked_423: return "Locked";
  6159. case StatusCode::FailedDependency_424: return "Failed Dependency";
  6160. case StatusCode::TooEarly_425: return "Too Early";
  6161. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  6162. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  6163. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  6164. case StatusCode::RequestHeaderFieldsTooLarge_431:
  6165. return "Request Header Fields Too Large";
  6166. case StatusCode::UnavailableForLegalReasons_451:
  6167. return "Unavailable For Legal Reasons";
  6168. case StatusCode::NotImplemented_501: return "Not Implemented";
  6169. case StatusCode::BadGateway_502: return "Bad Gateway";
  6170. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  6171. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  6172. case StatusCode::HttpVersionNotSupported_505:
  6173. return "HTTP Version Not Supported";
  6174. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  6175. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  6176. case StatusCode::LoopDetected_508: return "Loop Detected";
  6177. case StatusCode::NotExtended_510: return "Not Extended";
  6178. case StatusCode::NetworkAuthenticationRequired_511:
  6179. return "Network Authentication Required";
  6180. default:
  6181. case StatusCode::InternalServerError_500: return "Internal Server Error";
  6182. }
  6183. }
  6184. inline std::string to_string(const Error error) {
  6185. switch (error) {
  6186. case Error::Success: return "Success (no error)";
  6187. case Error::Unknown: return "Unknown";
  6188. case Error::Connection: return "Could not establish connection";
  6189. case Error::BindIPAddress: return "Failed to bind IP address";
  6190. case Error::Read: return "Failed to read connection";
  6191. case Error::Write: return "Failed to write connection";
  6192. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  6193. case Error::Canceled: return "Connection handling canceled";
  6194. case Error::SSLConnection: return "SSL connection failed";
  6195. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  6196. case Error::SSLServerVerification: return "SSL server verification failed";
  6197. case Error::SSLServerHostnameVerification:
  6198. return "SSL server hostname verification failed";
  6199. case Error::UnsupportedMultipartBoundaryChars:
  6200. return "Unsupported HTTP multipart boundary characters";
  6201. case Error::Compression: return "Compression failed";
  6202. case Error::ConnectionTimeout: return "Connection timed out";
  6203. case Error::ProxyConnection: return "Proxy connection failed";
  6204. case Error::ConnectionClosed: return "Connection closed by server";
  6205. case Error::Timeout: return "Read timeout";
  6206. case Error::ResourceExhaustion: return "Resource exhaustion";
  6207. case Error::TooManyFormDataFiles: return "Too many form data files";
  6208. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  6209. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  6210. case Error::ExceedMaxSocketDescriptorCount:
  6211. return "Exceeded maximum socket descriptor count";
  6212. case Error::InvalidRequestLine: return "Invalid request line";
  6213. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  6214. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  6215. case Error::InvalidHeaders: return "Invalid headers";
  6216. case Error::MultipartParsing: return "Multipart parsing failed";
  6217. case Error::OpenFile: return "Failed to open file";
  6218. case Error::Listen: return "Failed to listen on socket";
  6219. case Error::GetSockName: return "Failed to get socket name";
  6220. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  6221. case Error::HTTPParsing: return "HTTP parsing failed";
  6222. case Error::InvalidRangeHeader: return "Invalid Range header";
  6223. default: break;
  6224. }
  6225. return "Invalid";
  6226. }
  6227. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  6228. os << to_string(obj);
  6229. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  6230. return os;
  6231. }
  6232. inline std::string hosted_at(const std::string &hostname) {
  6233. std::vector<std::string> addrs;
  6234. hosted_at(hostname, addrs);
  6235. if (addrs.empty()) { return std::string(); }
  6236. return addrs[0];
  6237. }
  6238. inline void hosted_at(const std::string &hostname,
  6239. std::vector<std::string> &addrs) {
  6240. struct addrinfo hints;
  6241. struct addrinfo *result;
  6242. memset(&hints, 0, sizeof(struct addrinfo));
  6243. hints.ai_family = AF_UNSPEC;
  6244. hints.ai_socktype = SOCK_STREAM;
  6245. hints.ai_protocol = 0;
  6246. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  6247. &result, 0)) {
  6248. #if defined __linux__ && !defined __ANDROID__
  6249. res_init();
  6250. #endif
  6251. return;
  6252. }
  6253. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  6254. for (auto rp = result; rp; rp = rp->ai_next) {
  6255. const auto &addr =
  6256. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  6257. std::string ip;
  6258. auto dummy = -1;
  6259. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  6260. dummy)) {
  6261. addrs.emplace_back(std::move(ip));
  6262. }
  6263. }
  6264. }
  6265. inline std::string encode_uri_component(const std::string &value) {
  6266. std::ostringstream escaped;
  6267. escaped.fill('0');
  6268. escaped << std::hex;
  6269. for (auto c : value) {
  6270. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6271. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6272. c == ')') {
  6273. escaped << c;
  6274. } else {
  6275. escaped << std::uppercase;
  6276. escaped << '%' << std::setw(2)
  6277. << static_cast<int>(static_cast<unsigned char>(c));
  6278. escaped << std::nouppercase;
  6279. }
  6280. }
  6281. return escaped.str();
  6282. }
  6283. inline std::string encode_uri(const std::string &value) {
  6284. std::ostringstream escaped;
  6285. escaped.fill('0');
  6286. escaped << std::hex;
  6287. for (auto c : value) {
  6288. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  6289. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  6290. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  6291. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  6292. escaped << c;
  6293. } else {
  6294. escaped << std::uppercase;
  6295. escaped << '%' << std::setw(2)
  6296. << static_cast<int>(static_cast<unsigned char>(c));
  6297. escaped << std::nouppercase;
  6298. }
  6299. }
  6300. return escaped.str();
  6301. }
  6302. inline std::string decode_uri_component(const std::string &value) {
  6303. std::string result;
  6304. for (size_t i = 0; i < value.size(); i++) {
  6305. if (value[i] == '%' && i + 2 < value.size()) {
  6306. auto val = 0;
  6307. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6308. result += static_cast<char>(val);
  6309. i += 2;
  6310. } else {
  6311. result += value[i];
  6312. }
  6313. } else {
  6314. result += value[i];
  6315. }
  6316. }
  6317. return result;
  6318. }
  6319. inline std::string decode_uri(const std::string &value) {
  6320. std::string result;
  6321. for (size_t i = 0; i < value.size(); i++) {
  6322. if (value[i] == '%' && i + 2 < value.size()) {
  6323. auto val = 0;
  6324. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  6325. result += static_cast<char>(val);
  6326. i += 2;
  6327. } else {
  6328. result += value[i];
  6329. }
  6330. } else {
  6331. result += value[i];
  6332. }
  6333. }
  6334. return result;
  6335. }
  6336. inline std::string encode_path_component(const std::string &component) {
  6337. std::string result;
  6338. result.reserve(component.size() * 3);
  6339. for (size_t i = 0; i < component.size(); i++) {
  6340. auto c = static_cast<unsigned char>(component[i]);
  6341. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  6342. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6343. result += static_cast<char>(c);
  6344. }
  6345. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  6346. // "," / ";" / "="
  6347. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  6348. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  6349. c == '=') {
  6350. result += static_cast<char>(c);
  6351. }
  6352. // Colon is allowed in path segments except first segment
  6353. else if (c == ':') {
  6354. result += static_cast<char>(c);
  6355. }
  6356. // @ is allowed in path
  6357. else if (c == '@') {
  6358. result += static_cast<char>(c);
  6359. } else {
  6360. result += '%';
  6361. char hex[3];
  6362. snprintf(hex, sizeof(hex), "%02X", c);
  6363. result.append(hex, 2);
  6364. }
  6365. }
  6366. return result;
  6367. }
  6368. inline std::string decode_path_component(const std::string &component) {
  6369. std::string result;
  6370. result.reserve(component.size());
  6371. for (size_t i = 0; i < component.size(); i++) {
  6372. if (component[i] == '%' && i + 1 < component.size()) {
  6373. if (component[i + 1] == 'u') {
  6374. // Unicode %uXXXX encoding
  6375. auto val = 0;
  6376. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  6377. // 4 digits Unicode codes
  6378. char buff[4];
  6379. size_t len = detail::to_utf8(val, buff);
  6380. if (len > 0) { result.append(buff, len); }
  6381. i += 5; // 'u0000'
  6382. } else {
  6383. result += component[i];
  6384. }
  6385. } else {
  6386. // Standard %XX encoding
  6387. auto val = 0;
  6388. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  6389. // 2 digits hex codes
  6390. result += static_cast<char>(val);
  6391. i += 2; // 'XX'
  6392. } else {
  6393. result += component[i];
  6394. }
  6395. }
  6396. } else {
  6397. result += component[i];
  6398. }
  6399. }
  6400. return result;
  6401. }
  6402. inline std::string encode_query_component(const std::string &component,
  6403. bool space_as_plus) {
  6404. std::string result;
  6405. result.reserve(component.size() * 3);
  6406. for (size_t i = 0; i < component.size(); i++) {
  6407. auto c = static_cast<unsigned char>(component[i]);
  6408. // Unreserved characters per RFC 3986
  6409. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  6410. result += static_cast<char>(c);
  6411. }
  6412. // Space handling
  6413. else if (c == ' ') {
  6414. if (space_as_plus) {
  6415. result += '+';
  6416. } else {
  6417. result += "%20";
  6418. }
  6419. }
  6420. // Plus sign handling
  6421. else if (c == '+') {
  6422. if (space_as_plus) {
  6423. result += "%2B";
  6424. } else {
  6425. result += static_cast<char>(c);
  6426. }
  6427. }
  6428. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  6429. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  6430. c == '*' || c == ',' || c == ';') {
  6431. result += static_cast<char>(c);
  6432. }
  6433. // Colon and @ are allowed in query
  6434. else if (c == ':' || c == '@') {
  6435. result += static_cast<char>(c);
  6436. }
  6437. // Forward slash is allowed in query values
  6438. else if (c == '/') {
  6439. result += static_cast<char>(c);
  6440. }
  6441. // Question mark is allowed in query values (after first ?)
  6442. else if (c == '?') {
  6443. result += static_cast<char>(c);
  6444. } else {
  6445. result += '%';
  6446. char hex[3];
  6447. snprintf(hex, sizeof(hex), "%02X", c);
  6448. result.append(hex, 2);
  6449. }
  6450. }
  6451. return result;
  6452. }
  6453. inline std::string decode_query_component(const std::string &component,
  6454. bool plus_as_space) {
  6455. std::string result;
  6456. result.reserve(component.size());
  6457. for (size_t i = 0; i < component.size(); i++) {
  6458. if (component[i] == '%' && i + 2 < component.size()) {
  6459. std::string hex = component.substr(i + 1, 2);
  6460. char *end;
  6461. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  6462. if (end == hex.c_str() + 2) {
  6463. result += static_cast<char>(value);
  6464. i += 2;
  6465. } else {
  6466. result += component[i];
  6467. }
  6468. } else if (component[i] == '+' && plus_as_space) {
  6469. result += ' '; // + becomes space in form-urlencoded
  6470. } else {
  6471. result += component[i];
  6472. }
  6473. }
  6474. return result;
  6475. }
  6476. inline std::string append_query_params(const std::string &path,
  6477. const Params &params) {
  6478. std::string path_with_query = path;
  6479. thread_local const std::regex re("[^?]+\\?.*");
  6480. auto delm = std::regex_match(path, re) ? '&' : '?';
  6481. path_with_query += delm + detail::params_to_query_str(params);
  6482. return path_with_query;
  6483. }
  6484. // Header utilities
  6485. inline std::pair<std::string, std::string>
  6486. make_range_header(const Ranges &ranges) {
  6487. std::string field = "bytes=";
  6488. auto i = 0;
  6489. for (const auto &r : ranges) {
  6490. if (i != 0) { field += ", "; }
  6491. if (r.first != -1) { field += std::to_string(r.first); }
  6492. field += '-';
  6493. if (r.second != -1) { field += std::to_string(r.second); }
  6494. i++;
  6495. }
  6496. return std::make_pair("Range", std::move(field));
  6497. }
  6498. inline std::pair<std::string, std::string>
  6499. make_basic_authentication_header(const std::string &username,
  6500. const std::string &password, bool is_proxy) {
  6501. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  6502. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6503. return std::make_pair(key, std::move(field));
  6504. }
  6505. inline std::pair<std::string, std::string>
  6506. make_bearer_token_authentication_header(const std::string &token,
  6507. bool is_proxy = false) {
  6508. auto field = "Bearer " + token;
  6509. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  6510. return std::make_pair(key, std::move(field));
  6511. }
  6512. // Request implementation
  6513. inline bool Request::has_header(const std::string &key) const {
  6514. return detail::has_header(headers, key);
  6515. }
  6516. inline std::string Request::get_header_value(const std::string &key,
  6517. const char *def, size_t id) const {
  6518. return detail::get_header_value(headers, key, def, id);
  6519. }
  6520. inline size_t Request::get_header_value_count(const std::string &key) const {
  6521. auto r = headers.equal_range(key);
  6522. return static_cast<size_t>(std::distance(r.first, r.second));
  6523. }
  6524. inline void Request::set_header(const std::string &key,
  6525. const std::string &val) {
  6526. if (detail::fields::is_field_name(key) &&
  6527. detail::fields::is_field_value(val)) {
  6528. headers.emplace(key, val);
  6529. }
  6530. }
  6531. inline bool Request::has_trailer(const std::string &key) const {
  6532. return trailers.find(key) != trailers.end();
  6533. }
  6534. inline std::string Request::get_trailer_value(const std::string &key,
  6535. size_t id) const {
  6536. auto rng = trailers.equal_range(key);
  6537. auto it = rng.first;
  6538. std::advance(it, static_cast<ssize_t>(id));
  6539. if (it != rng.second) { return it->second; }
  6540. return std::string();
  6541. }
  6542. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  6543. auto r = trailers.equal_range(key);
  6544. return static_cast<size_t>(std::distance(r.first, r.second));
  6545. }
  6546. inline bool Request::has_param(const std::string &key) const {
  6547. return params.find(key) != params.end();
  6548. }
  6549. inline std::string Request::get_param_value(const std::string &key,
  6550. size_t id) const {
  6551. auto rng = params.equal_range(key);
  6552. auto it = rng.first;
  6553. std::advance(it, static_cast<ssize_t>(id));
  6554. if (it != rng.second) { return it->second; }
  6555. return std::string();
  6556. }
  6557. inline size_t Request::get_param_value_count(const std::string &key) const {
  6558. auto r = params.equal_range(key);
  6559. return static_cast<size_t>(std::distance(r.first, r.second));
  6560. }
  6561. inline bool Request::is_multipart_form_data() const {
  6562. const auto &content_type = get_header_value("Content-Type");
  6563. return !content_type.rfind("multipart/form-data", 0);
  6564. }
  6565. // Multipart FormData implementation
  6566. inline std::string MultipartFormData::get_field(const std::string &key,
  6567. size_t id) const {
  6568. auto rng = fields.equal_range(key);
  6569. auto it = rng.first;
  6570. std::advance(it, static_cast<ssize_t>(id));
  6571. if (it != rng.second) { return it->second.content; }
  6572. return std::string();
  6573. }
  6574. inline std::vector<std::string>
  6575. MultipartFormData::get_fields(const std::string &key) const {
  6576. std::vector<std::string> values;
  6577. auto rng = fields.equal_range(key);
  6578. for (auto it = rng.first; it != rng.second; it++) {
  6579. values.push_back(it->second.content);
  6580. }
  6581. return values;
  6582. }
  6583. inline bool MultipartFormData::has_field(const std::string &key) const {
  6584. return fields.find(key) != fields.end();
  6585. }
  6586. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  6587. auto r = fields.equal_range(key);
  6588. return static_cast<size_t>(std::distance(r.first, r.second));
  6589. }
  6590. inline FormData MultipartFormData::get_file(const std::string &key,
  6591. size_t id) const {
  6592. auto rng = files.equal_range(key);
  6593. auto it = rng.first;
  6594. std::advance(it, static_cast<ssize_t>(id));
  6595. if (it != rng.second) { return it->second; }
  6596. return FormData();
  6597. }
  6598. inline std::vector<FormData>
  6599. MultipartFormData::get_files(const std::string &key) const {
  6600. std::vector<FormData> values;
  6601. auto rng = files.equal_range(key);
  6602. for (auto it = rng.first; it != rng.second; it++) {
  6603. values.push_back(it->second);
  6604. }
  6605. return values;
  6606. }
  6607. inline bool MultipartFormData::has_file(const std::string &key) const {
  6608. return files.find(key) != files.end();
  6609. }
  6610. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  6611. auto r = files.equal_range(key);
  6612. return static_cast<size_t>(std::distance(r.first, r.second));
  6613. }
  6614. // Response implementation
  6615. inline bool Response::has_header(const std::string &key) const {
  6616. return headers.find(key) != headers.end();
  6617. }
  6618. inline std::string Response::get_header_value(const std::string &key,
  6619. const char *def,
  6620. size_t id) const {
  6621. return detail::get_header_value(headers, key, def, id);
  6622. }
  6623. inline size_t Response::get_header_value_count(const std::string &key) const {
  6624. auto r = headers.equal_range(key);
  6625. return static_cast<size_t>(std::distance(r.first, r.second));
  6626. }
  6627. inline void Response::set_header(const std::string &key,
  6628. const std::string &val) {
  6629. if (detail::fields::is_field_name(key) &&
  6630. detail::fields::is_field_value(val)) {
  6631. headers.emplace(key, val);
  6632. }
  6633. }
  6634. inline bool Response::has_trailer(const std::string &key) const {
  6635. return trailers.find(key) != trailers.end();
  6636. }
  6637. inline std::string Response::get_trailer_value(const std::string &key,
  6638. size_t id) const {
  6639. auto rng = trailers.equal_range(key);
  6640. auto it = rng.first;
  6641. std::advance(it, static_cast<ssize_t>(id));
  6642. if (it != rng.second) { return it->second; }
  6643. return std::string();
  6644. }
  6645. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  6646. auto r = trailers.equal_range(key);
  6647. return static_cast<size_t>(std::distance(r.first, r.second));
  6648. }
  6649. inline void Response::set_redirect(const std::string &url, int stat) {
  6650. if (detail::fields::is_field_value(url)) {
  6651. set_header("Location", url);
  6652. if (300 <= stat && stat < 400) {
  6653. this->status = stat;
  6654. } else {
  6655. this->status = StatusCode::Found_302;
  6656. }
  6657. }
  6658. }
  6659. inline void Response::set_content(const char *s, size_t n,
  6660. const std::string &content_type) {
  6661. body.assign(s, n);
  6662. auto rng = headers.equal_range("Content-Type");
  6663. headers.erase(rng.first, rng.second);
  6664. set_header("Content-Type", content_type);
  6665. }
  6666. inline void Response::set_content(const std::string &s,
  6667. const std::string &content_type) {
  6668. set_content(s.data(), s.size(), content_type);
  6669. }
  6670. inline void Response::set_content(std::string &&s,
  6671. const std::string &content_type) {
  6672. body = std::move(s);
  6673. auto rng = headers.equal_range("Content-Type");
  6674. headers.erase(rng.first, rng.second);
  6675. set_header("Content-Type", content_type);
  6676. }
  6677. inline void Response::set_content_provider(
  6678. size_t in_length, const std::string &content_type, ContentProvider provider,
  6679. ContentProviderResourceReleaser resource_releaser) {
  6680. set_header("Content-Type", content_type);
  6681. content_length_ = in_length;
  6682. if (in_length > 0) { content_provider_ = std::move(provider); }
  6683. content_provider_resource_releaser_ = std::move(resource_releaser);
  6684. is_chunked_content_provider_ = false;
  6685. }
  6686. inline void Response::set_content_provider(
  6687. const std::string &content_type, ContentProviderWithoutLength provider,
  6688. ContentProviderResourceReleaser resource_releaser) {
  6689. set_header("Content-Type", content_type);
  6690. content_length_ = 0;
  6691. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6692. content_provider_resource_releaser_ = std::move(resource_releaser);
  6693. is_chunked_content_provider_ = false;
  6694. }
  6695. inline void Response::set_chunked_content_provider(
  6696. const std::string &content_type, ContentProviderWithoutLength provider,
  6697. ContentProviderResourceReleaser resource_releaser) {
  6698. set_header("Content-Type", content_type);
  6699. content_length_ = 0;
  6700. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  6701. content_provider_resource_releaser_ = std::move(resource_releaser);
  6702. is_chunked_content_provider_ = true;
  6703. }
  6704. inline void Response::set_file_content(const std::string &path,
  6705. const std::string &content_type) {
  6706. file_content_path_ = path;
  6707. file_content_content_type_ = content_type;
  6708. }
  6709. inline void Response::set_file_content(const std::string &path) {
  6710. file_content_path_ = path;
  6711. }
  6712. // Result implementation
  6713. inline bool Result::has_request_header(const std::string &key) const {
  6714. return request_headers_.find(key) != request_headers_.end();
  6715. }
  6716. inline std::string Result::get_request_header_value(const std::string &key,
  6717. const char *def,
  6718. size_t id) const {
  6719. return detail::get_header_value(request_headers_, key, def, id);
  6720. }
  6721. inline size_t
  6722. Result::get_request_header_value_count(const std::string &key) const {
  6723. auto r = request_headers_.equal_range(key);
  6724. return static_cast<size_t>(std::distance(r.first, r.second));
  6725. }
  6726. // Stream implementation
  6727. inline ssize_t Stream::write(const char *ptr) {
  6728. return write(ptr, strlen(ptr));
  6729. }
  6730. inline ssize_t Stream::write(const std::string &s) {
  6731. return write(s.data(), s.size());
  6732. }
  6733. // BodyReader implementation
  6734. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  6735. if (!stream) {
  6736. last_error = Error::Connection;
  6737. return -1;
  6738. }
  6739. if (eof) { return 0; }
  6740. if (!chunked) {
  6741. // Content-Length based reading
  6742. if (bytes_read >= content_length) {
  6743. eof = true;
  6744. return 0;
  6745. }
  6746. auto remaining = content_length - bytes_read;
  6747. auto to_read = (std::min)(len, remaining);
  6748. auto n = stream->read(buf, to_read);
  6749. if (n < 0) {
  6750. last_error = stream->get_error();
  6751. if (last_error == Error::Success) { last_error = Error::Read; }
  6752. eof = true;
  6753. return n;
  6754. }
  6755. if (n == 0) {
  6756. // Unexpected EOF before content_length
  6757. last_error = stream->get_error();
  6758. if (last_error == Error::Success) { last_error = Error::Read; }
  6759. eof = true;
  6760. return 0;
  6761. }
  6762. bytes_read += static_cast<size_t>(n);
  6763. if (bytes_read >= content_length) { eof = true; }
  6764. return n;
  6765. }
  6766. // Chunked transfer encoding: delegate to shared decoder instance.
  6767. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  6768. size_t chunk_offset = 0;
  6769. size_t chunk_total = 0;
  6770. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  6771. if (n < 0) {
  6772. last_error = stream->get_error();
  6773. if (last_error == Error::Success) { last_error = Error::Read; }
  6774. eof = true;
  6775. return n;
  6776. }
  6777. if (n == 0) {
  6778. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  6779. eof = true;
  6780. return 0;
  6781. }
  6782. bytes_read += static_cast<size_t>(n);
  6783. return n;
  6784. }
  6785. namespace detail {
  6786. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  6787. time_t timeout_sec, time_t timeout_usec,
  6788. time_t &actual_timeout_sec,
  6789. time_t &actual_timeout_usec) {
  6790. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  6791. auto actual_timeout_msec =
  6792. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  6793. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  6794. actual_timeout_sec = actual_timeout_msec / 1000;
  6795. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  6796. }
  6797. // Socket stream implementation
  6798. inline SocketStream::SocketStream(
  6799. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6800. time_t write_timeout_sec, time_t write_timeout_usec,
  6801. time_t max_timeout_msec,
  6802. std::chrono::time_point<std::chrono::steady_clock> start_time)
  6803. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  6804. read_timeout_usec_(read_timeout_usec),
  6805. write_timeout_sec_(write_timeout_sec),
  6806. write_timeout_usec_(write_timeout_usec),
  6807. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  6808. read_buff_(read_buff_size_, 0) {}
  6809. inline SocketStream::~SocketStream() = default;
  6810. inline bool SocketStream::is_readable() const {
  6811. return read_buff_off_ < read_buff_content_size_;
  6812. }
  6813. inline bool SocketStream::wait_readable() const {
  6814. if (max_timeout_msec_ <= 0) {
  6815. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  6816. }
  6817. time_t read_timeout_sec;
  6818. time_t read_timeout_usec;
  6819. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  6820. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  6821. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  6822. }
  6823. inline bool SocketStream::wait_writable() const {
  6824. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  6825. is_socket_alive(sock_);
  6826. }
  6827. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  6828. #ifdef _WIN32
  6829. size =
  6830. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  6831. #else
  6832. size = (std::min)(size,
  6833. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  6834. #endif
  6835. if (read_buff_off_ < read_buff_content_size_) {
  6836. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  6837. if (size <= remaining_size) {
  6838. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  6839. read_buff_off_ += size;
  6840. return static_cast<ssize_t>(size);
  6841. } else {
  6842. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  6843. read_buff_off_ += remaining_size;
  6844. return static_cast<ssize_t>(remaining_size);
  6845. }
  6846. }
  6847. if (!wait_readable()) {
  6848. error_ = Error::Timeout;
  6849. return -1;
  6850. }
  6851. read_buff_off_ = 0;
  6852. read_buff_content_size_ = 0;
  6853. if (size < read_buff_size_) {
  6854. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  6855. CPPHTTPLIB_RECV_FLAGS);
  6856. if (n <= 0) {
  6857. if (n == 0) {
  6858. error_ = Error::ConnectionClosed;
  6859. } else {
  6860. error_ = Error::Read;
  6861. }
  6862. return n;
  6863. } else if (n <= static_cast<ssize_t>(size)) {
  6864. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  6865. return n;
  6866. } else {
  6867. memcpy(ptr, read_buff_.data(), size);
  6868. read_buff_off_ = size;
  6869. read_buff_content_size_ = static_cast<size_t>(n);
  6870. return static_cast<ssize_t>(size);
  6871. }
  6872. } else {
  6873. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  6874. if (n <= 0) {
  6875. if (n == 0) {
  6876. error_ = Error::ConnectionClosed;
  6877. } else {
  6878. error_ = Error::Read;
  6879. }
  6880. }
  6881. return n;
  6882. }
  6883. }
  6884. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  6885. if (!wait_writable()) { return -1; }
  6886. #if defined(_WIN32) && !defined(_WIN64)
  6887. size =
  6888. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  6889. #endif
  6890. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  6891. }
  6892. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  6893. int &port) const {
  6894. return detail::get_remote_ip_and_port(sock_, ip, port);
  6895. }
  6896. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  6897. int &port) const {
  6898. return detail::get_local_ip_and_port(sock_, ip, port);
  6899. }
  6900. inline socket_t SocketStream::socket() const { return sock_; }
  6901. inline time_t SocketStream::duration() const {
  6902. return std::chrono::duration_cast<std::chrono::milliseconds>(
  6903. std::chrono::steady_clock::now() - start_time_)
  6904. .count();
  6905. }
  6906. // Buffer stream implementation
  6907. inline bool BufferStream::is_readable() const { return true; }
  6908. inline bool BufferStream::wait_readable() const { return true; }
  6909. inline bool BufferStream::wait_writable() const { return true; }
  6910. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  6911. #if defined(_MSC_VER) && _MSC_VER < 1910
  6912. auto len_read = buffer._Copy_s(ptr, size, size, position);
  6913. #else
  6914. auto len_read = buffer.copy(ptr, size, position);
  6915. #endif
  6916. position += static_cast<size_t>(len_read);
  6917. return static_cast<ssize_t>(len_read);
  6918. }
  6919. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  6920. buffer.append(ptr, size);
  6921. return static_cast<ssize_t>(size);
  6922. }
  6923. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  6924. int & /*port*/) const {}
  6925. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  6926. int & /*port*/) const {}
  6927. inline socket_t BufferStream::socket() const { return 0; }
  6928. inline time_t BufferStream::duration() const { return 0; }
  6929. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  6930. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  6931. : MatcherBase(pattern) {
  6932. constexpr const char marker[] = "/:";
  6933. // One past the last ending position of a path param substring
  6934. std::size_t last_param_end = 0;
  6935. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6936. // Needed to ensure that parameter names are unique during matcher
  6937. // construction
  6938. // If exceptions are disabled, only last duplicate path
  6939. // parameter will be set
  6940. std::unordered_set<std::string> param_name_set;
  6941. #endif
  6942. while (true) {
  6943. const auto marker_pos = pattern.find(
  6944. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  6945. if (marker_pos == std::string::npos) { break; }
  6946. static_fragments_.push_back(
  6947. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  6948. const auto param_name_start = marker_pos + str_len(marker);
  6949. auto sep_pos = pattern.find(separator, param_name_start);
  6950. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  6951. auto param_name =
  6952. pattern.substr(param_name_start, sep_pos - param_name_start);
  6953. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6954. if (param_name_set.find(param_name) != param_name_set.cend()) {
  6955. std::string msg = "Encountered path parameter '" + param_name +
  6956. "' multiple times in route pattern '" + pattern + "'.";
  6957. throw std::invalid_argument(msg);
  6958. }
  6959. #endif
  6960. param_names_.push_back(std::move(param_name));
  6961. last_param_end = sep_pos + 1;
  6962. }
  6963. if (last_param_end < pattern.length()) {
  6964. static_fragments_.push_back(pattern.substr(last_param_end));
  6965. }
  6966. }
  6967. inline bool PathParamsMatcher::match(Request &request) const {
  6968. request.matches = std::smatch();
  6969. request.path_params.clear();
  6970. request.path_params.reserve(param_names_.size());
  6971. // One past the position at which the path matched the pattern last time
  6972. std::size_t starting_pos = 0;
  6973. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  6974. const auto &fragment = static_fragments_[i];
  6975. if (starting_pos + fragment.length() > request.path.length()) {
  6976. return false;
  6977. }
  6978. // Avoid unnecessary allocation by using strncmp instead of substr +
  6979. // comparison
  6980. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  6981. fragment.length()) != 0) {
  6982. return false;
  6983. }
  6984. starting_pos += fragment.length();
  6985. // Should only happen when we have a static fragment after a param
  6986. // Example: '/users/:id/subscriptions'
  6987. // The 'subscriptions' fragment here does not have a corresponding param
  6988. if (i >= param_names_.size()) { continue; }
  6989. auto sep_pos = request.path.find(separator, starting_pos);
  6990. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  6991. const auto &param_name = param_names_[i];
  6992. request.path_params.emplace(
  6993. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  6994. // Mark everything up to '/' as matched
  6995. starting_pos = sep_pos + 1;
  6996. }
  6997. // Returns false if the path is longer than the pattern
  6998. return starting_pos >= request.path.length();
  6999. }
  7000. inline bool RegexMatcher::match(Request &request) const {
  7001. request.path_params.clear();
  7002. return std::regex_match(request.path, request.matches, regex_);
  7003. }
  7004. // Enclose IPv6 address in brackets if needed
  7005. inline std::string prepare_host_string(const std::string &host) {
  7006. // Enclose IPv6 address in brackets (but not if already enclosed)
  7007. if (host.find(':') == std::string::npos ||
  7008. (!host.empty() && host[0] == '[')) {
  7009. // IPv4, hostname, or already bracketed IPv6
  7010. return host;
  7011. } else {
  7012. // IPv6 address without brackets
  7013. return "[" + host + "]";
  7014. }
  7015. }
  7016. inline std::string make_host_and_port_string(const std::string &host, int port,
  7017. bool is_ssl) {
  7018. auto result = prepare_host_string(host);
  7019. // Append port if not default
  7020. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  7021. ; // do nothing
  7022. } else {
  7023. result += ":" + std::to_string(port);
  7024. }
  7025. return result;
  7026. }
  7027. // Create "host:port" string always including port number (for CONNECT method)
  7028. inline std::string
  7029. make_host_and_port_string_always_port(const std::string &host, int port) {
  7030. return prepare_host_string(host) + ":" + std::to_string(port);
  7031. }
  7032. template <typename T>
  7033. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  7034. T header_writer, Error &error) {
  7035. for (const auto &h : headers) {
  7036. if (!detail::fields::is_field_name(h.first) ||
  7037. !detail::fields::is_field_value(h.second)) {
  7038. error = Error::InvalidHeaders;
  7039. return false;
  7040. }
  7041. }
  7042. if (header_writer(strm, headers) <= 0) {
  7043. error = Error::Write;
  7044. return false;
  7045. }
  7046. return true;
  7047. }
  7048. } // namespace detail
  7049. // HTTP server implementation
  7050. inline Server::Server()
  7051. : new_task_queue(
  7052. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  7053. #ifndef _WIN32
  7054. signal(SIGPIPE, SIG_IGN);
  7055. #endif
  7056. }
  7057. inline Server::~Server() = default;
  7058. inline std::unique_ptr<detail::MatcherBase>
  7059. Server::make_matcher(const std::string &pattern) {
  7060. if (pattern.find("/:") != std::string::npos) {
  7061. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  7062. } else {
  7063. return detail::make_unique<detail::RegexMatcher>(pattern);
  7064. }
  7065. }
  7066. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  7067. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7068. return *this;
  7069. }
  7070. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  7071. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7072. return *this;
  7073. }
  7074. inline Server &Server::Post(const std::string &pattern,
  7075. HandlerWithContentReader handler) {
  7076. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7077. std::move(handler));
  7078. return *this;
  7079. }
  7080. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  7081. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7082. return *this;
  7083. }
  7084. inline Server &Server::Put(const std::string &pattern,
  7085. HandlerWithContentReader handler) {
  7086. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7087. std::move(handler));
  7088. return *this;
  7089. }
  7090. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  7091. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7092. return *this;
  7093. }
  7094. inline Server &Server::Patch(const std::string &pattern,
  7095. HandlerWithContentReader handler) {
  7096. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7097. std::move(handler));
  7098. return *this;
  7099. }
  7100. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  7101. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7102. return *this;
  7103. }
  7104. inline Server &Server::Delete(const std::string &pattern,
  7105. HandlerWithContentReader handler) {
  7106. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  7107. std::move(handler));
  7108. return *this;
  7109. }
  7110. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  7111. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  7112. return *this;
  7113. }
  7114. inline bool Server::set_base_dir(const std::string &dir,
  7115. const std::string &mount_point) {
  7116. return set_mount_point(mount_point, dir);
  7117. }
  7118. inline bool Server::set_mount_point(const std::string &mount_point,
  7119. const std::string &dir, Headers headers) {
  7120. detail::FileStat stat(dir);
  7121. if (stat.is_dir()) {
  7122. std::string mnt = !mount_point.empty() ? mount_point : "/";
  7123. if (!mnt.empty() && mnt[0] == '/') {
  7124. base_dirs_.push_back({std::move(mnt), dir, std::move(headers)});
  7125. return true;
  7126. }
  7127. }
  7128. return false;
  7129. }
  7130. inline bool Server::remove_mount_point(const std::string &mount_point) {
  7131. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  7132. if (it->mount_point == mount_point) {
  7133. base_dirs_.erase(it);
  7134. return true;
  7135. }
  7136. }
  7137. return false;
  7138. }
  7139. inline Server &
  7140. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  7141. const std::string &mime) {
  7142. file_extension_and_mimetype_map_[ext] = mime;
  7143. return *this;
  7144. }
  7145. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  7146. default_file_mimetype_ = mime;
  7147. return *this;
  7148. }
  7149. inline Server &Server::set_file_request_handler(Handler handler) {
  7150. file_request_handler_ = std::move(handler);
  7151. return *this;
  7152. }
  7153. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  7154. std::true_type) {
  7155. error_handler_ = std::move(handler);
  7156. return *this;
  7157. }
  7158. inline Server &Server::set_error_handler_core(Handler handler,
  7159. std::false_type) {
  7160. error_handler_ = [handler](const Request &req, Response &res) {
  7161. handler(req, res);
  7162. return HandlerResponse::Handled;
  7163. };
  7164. return *this;
  7165. }
  7166. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  7167. exception_handler_ = std::move(handler);
  7168. return *this;
  7169. }
  7170. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  7171. pre_routing_handler_ = std::move(handler);
  7172. return *this;
  7173. }
  7174. inline Server &Server::set_post_routing_handler(Handler handler) {
  7175. post_routing_handler_ = std::move(handler);
  7176. return *this;
  7177. }
  7178. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  7179. pre_request_handler_ = std::move(handler);
  7180. return *this;
  7181. }
  7182. inline Server &Server::set_logger(Logger logger) {
  7183. logger_ = std::move(logger);
  7184. return *this;
  7185. }
  7186. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  7187. error_logger_ = std::move(error_logger);
  7188. return *this;
  7189. }
  7190. inline Server &Server::set_pre_compression_logger(Logger logger) {
  7191. pre_compression_logger_ = std::move(logger);
  7192. return *this;
  7193. }
  7194. inline Server &
  7195. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  7196. expect_100_continue_handler_ = std::move(handler);
  7197. return *this;
  7198. }
  7199. inline Server &Server::set_address_family(int family) {
  7200. address_family_ = family;
  7201. return *this;
  7202. }
  7203. inline Server &Server::set_tcp_nodelay(bool on) {
  7204. tcp_nodelay_ = on;
  7205. return *this;
  7206. }
  7207. inline Server &Server::set_ipv6_v6only(bool on) {
  7208. ipv6_v6only_ = on;
  7209. return *this;
  7210. }
  7211. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  7212. socket_options_ = std::move(socket_options);
  7213. return *this;
  7214. }
  7215. inline Server &Server::set_default_headers(Headers headers) {
  7216. default_headers_ = std::move(headers);
  7217. return *this;
  7218. }
  7219. inline Server &Server::set_header_writer(
  7220. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7221. header_writer_ = writer;
  7222. return *this;
  7223. }
  7224. inline Server &
  7225. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  7226. trusted_proxies_ = proxies;
  7227. return *this;
  7228. }
  7229. inline Server &Server::set_keep_alive_max_count(size_t count) {
  7230. keep_alive_max_count_ = count;
  7231. return *this;
  7232. }
  7233. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  7234. keep_alive_timeout_sec_ = sec;
  7235. return *this;
  7236. }
  7237. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  7238. read_timeout_sec_ = sec;
  7239. read_timeout_usec_ = usec;
  7240. return *this;
  7241. }
  7242. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  7243. write_timeout_sec_ = sec;
  7244. write_timeout_usec_ = usec;
  7245. return *this;
  7246. }
  7247. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  7248. idle_interval_sec_ = sec;
  7249. idle_interval_usec_ = usec;
  7250. return *this;
  7251. }
  7252. inline Server &Server::set_payload_max_length(size_t length) {
  7253. payload_max_length_ = length;
  7254. return *this;
  7255. }
  7256. inline bool Server::bind_to_port(const std::string &host, int port,
  7257. int socket_flags) {
  7258. auto ret = bind_internal(host, port, socket_flags);
  7259. if (ret == -1) { is_decommissioned = true; }
  7260. return ret >= 0;
  7261. }
  7262. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  7263. auto ret = bind_internal(host, 0, socket_flags);
  7264. if (ret == -1) { is_decommissioned = true; }
  7265. return ret;
  7266. }
  7267. inline bool Server::listen_after_bind() { return listen_internal(); }
  7268. inline bool Server::listen(const std::string &host, int port,
  7269. int socket_flags) {
  7270. return bind_to_port(host, port, socket_flags) && listen_internal();
  7271. }
  7272. inline bool Server::is_running() const { return is_running_; }
  7273. inline void Server::wait_until_ready() const {
  7274. while (!is_running_ && !is_decommissioned) {
  7275. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7276. }
  7277. }
  7278. inline void Server::stop() {
  7279. if (is_running_) {
  7280. assert(svr_sock_ != INVALID_SOCKET);
  7281. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  7282. detail::shutdown_socket(sock);
  7283. detail::close_socket(sock);
  7284. }
  7285. is_decommissioned = false;
  7286. }
  7287. inline void Server::decommission() { is_decommissioned = true; }
  7288. inline bool Server::parse_request_line(const char *s, Request &req) const {
  7289. auto len = strlen(s);
  7290. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  7291. len -= 2;
  7292. {
  7293. size_t count = 0;
  7294. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  7295. switch (count) {
  7296. case 0: req.method = std::string(b, e); break;
  7297. case 1: req.target = std::string(b, e); break;
  7298. case 2: req.version = std::string(b, e); break;
  7299. default: break;
  7300. }
  7301. count++;
  7302. });
  7303. if (count != 3) { return false; }
  7304. }
  7305. thread_local const std::set<std::string> methods{
  7306. "GET", "HEAD", "POST", "PUT", "DELETE",
  7307. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  7308. if (methods.find(req.method) == methods.end()) {
  7309. output_error_log(Error::InvalidHTTPMethod, &req);
  7310. return false;
  7311. }
  7312. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  7313. output_error_log(Error::InvalidHTTPVersion, &req);
  7314. return false;
  7315. }
  7316. {
  7317. // Skip URL fragment
  7318. for (size_t i = 0; i < req.target.size(); i++) {
  7319. if (req.target[i] == '#') {
  7320. req.target.erase(i);
  7321. break;
  7322. }
  7323. }
  7324. detail::divide(req.target, '?',
  7325. [&](const char *lhs_data, std::size_t lhs_size,
  7326. const char *rhs_data, std::size_t rhs_size) {
  7327. req.path =
  7328. decode_path_component(std::string(lhs_data, lhs_size));
  7329. detail::parse_query_text(rhs_data, rhs_size, req.params);
  7330. });
  7331. }
  7332. return true;
  7333. }
  7334. inline bool Server::write_response(Stream &strm, bool close_connection,
  7335. Request &req, Response &res) {
  7336. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  7337. // incorrectly to the error content.
  7338. req.ranges.clear();
  7339. return write_response_core(strm, close_connection, req, res, false);
  7340. }
  7341. inline bool Server::write_response_with_content(Stream &strm,
  7342. bool close_connection,
  7343. const Request &req,
  7344. Response &res) {
  7345. return write_response_core(strm, close_connection, req, res, true);
  7346. }
  7347. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  7348. const Request &req, Response &res,
  7349. bool need_apply_ranges) {
  7350. assert(res.status != -1);
  7351. if (400 <= res.status && error_handler_ &&
  7352. error_handler_(req, res) == HandlerResponse::Handled) {
  7353. need_apply_ranges = true;
  7354. }
  7355. std::string content_type;
  7356. std::string boundary;
  7357. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  7358. // Prepare additional headers
  7359. if (close_connection || req.get_header_value("Connection") == "close" ||
  7360. 400 <= res.status) { // Don't leave connections open after errors
  7361. res.set_header("Connection", "close");
  7362. } else {
  7363. std::string s = "timeout=";
  7364. s += std::to_string(keep_alive_timeout_sec_);
  7365. s += ", max=";
  7366. s += std::to_string(keep_alive_max_count_);
  7367. res.set_header("Keep-Alive", s);
  7368. }
  7369. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  7370. !res.has_header("Content-Type")) {
  7371. res.set_header("Content-Type", "text/plain");
  7372. }
  7373. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  7374. !res.has_header("Content-Length")) {
  7375. res.set_header("Content-Length", "0");
  7376. }
  7377. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  7378. res.set_header("Accept-Ranges", "bytes");
  7379. }
  7380. if (post_routing_handler_) { post_routing_handler_(req, res); }
  7381. // Response line and headers
  7382. {
  7383. detail::BufferStream bstrm;
  7384. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  7385. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  7386. // Flush buffer
  7387. auto &data = bstrm.get_buffer();
  7388. detail::write_data(strm, data.data(), data.size());
  7389. }
  7390. // Body
  7391. auto ret = true;
  7392. if (req.method != "HEAD") {
  7393. if (!res.body.empty()) {
  7394. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  7395. ret = false;
  7396. }
  7397. } else if (res.content_provider_) {
  7398. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  7399. res.content_provider_success_ = true;
  7400. } else {
  7401. ret = false;
  7402. }
  7403. }
  7404. }
  7405. // Log
  7406. output_log(req, res);
  7407. return ret;
  7408. }
  7409. inline bool
  7410. Server::write_content_with_provider(Stream &strm, const Request &req,
  7411. Response &res, const std::string &boundary,
  7412. const std::string &content_type) {
  7413. auto is_shutting_down = [this]() {
  7414. return this->svr_sock_ == INVALID_SOCKET;
  7415. };
  7416. if (res.content_length_ > 0) {
  7417. if (req.ranges.empty()) {
  7418. return detail::write_content(strm, res.content_provider_, 0,
  7419. res.content_length_, is_shutting_down);
  7420. } else if (req.ranges.size() == 1) {
  7421. auto offset_and_length = detail::get_range_offset_and_length(
  7422. req.ranges[0], res.content_length_);
  7423. return detail::write_content(strm, res.content_provider_,
  7424. offset_and_length.first,
  7425. offset_and_length.second, is_shutting_down);
  7426. } else {
  7427. return detail::write_multipart_ranges_data(
  7428. strm, req, res, boundary, content_type, res.content_length_,
  7429. is_shutting_down);
  7430. }
  7431. } else {
  7432. if (res.is_chunked_content_provider_) {
  7433. auto type = detail::encoding_type(req, res);
  7434. std::unique_ptr<detail::compressor> compressor;
  7435. if (type == detail::EncodingType::Gzip) {
  7436. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7437. compressor = detail::make_unique<detail::gzip_compressor>();
  7438. #endif
  7439. } else if (type == detail::EncodingType::Brotli) {
  7440. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7441. compressor = detail::make_unique<detail::brotli_compressor>();
  7442. #endif
  7443. } else if (type == detail::EncodingType::Zstd) {
  7444. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7445. compressor = detail::make_unique<detail::zstd_compressor>();
  7446. #endif
  7447. } else {
  7448. compressor = detail::make_unique<detail::nocompressor>();
  7449. }
  7450. assert(compressor != nullptr);
  7451. return detail::write_content_chunked(strm, res.content_provider_,
  7452. is_shutting_down, *compressor);
  7453. } else {
  7454. return detail::write_content_without_length(strm, res.content_provider_,
  7455. is_shutting_down);
  7456. }
  7457. }
  7458. }
  7459. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  7460. FormFields::iterator cur_field;
  7461. FormFiles::iterator cur_file;
  7462. auto is_text_field = false;
  7463. size_t count = 0;
  7464. if (read_content_core(
  7465. strm, req, res,
  7466. // Regular
  7467. [&](const char *buf, size_t n) {
  7468. // Prevent arithmetic overflow when checking sizes.
  7469. // Avoid computing (req.body.size() + n) directly because
  7470. // adding two unsigned `size_t` values can wrap around and
  7471. // produce a small result instead of indicating overflow.
  7472. // Instead, check using subtraction: ensure `n` does not
  7473. // exceed the remaining capacity `max_size() - size()`.
  7474. if (req.body.size() >= req.body.max_size() ||
  7475. n > req.body.max_size() - req.body.size()) {
  7476. return false;
  7477. }
  7478. // Limit decompressed body size to payload_max_length_ to protect
  7479. // against "zip bomb" attacks where a small compressed payload
  7480. // decompresses to a massive size.
  7481. if (payload_max_length_ > 0 &&
  7482. (req.body.size() >= payload_max_length_ ||
  7483. n > payload_max_length_ - req.body.size())) {
  7484. return false;
  7485. }
  7486. req.body.append(buf, n);
  7487. return true;
  7488. },
  7489. // Multipart FormData
  7490. [&](const FormData &file) {
  7491. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  7492. output_error_log(Error::TooManyFormDataFiles, &req);
  7493. return false;
  7494. }
  7495. if (file.filename.empty()) {
  7496. cur_field = req.form.fields.emplace(
  7497. file.name, FormField{file.name, file.content, file.headers});
  7498. is_text_field = true;
  7499. } else {
  7500. cur_file = req.form.files.emplace(file.name, file);
  7501. is_text_field = false;
  7502. }
  7503. return true;
  7504. },
  7505. [&](const char *buf, size_t n) {
  7506. if (is_text_field) {
  7507. auto &content = cur_field->second.content;
  7508. if (content.size() + n > content.max_size()) { return false; }
  7509. content.append(buf, n);
  7510. } else {
  7511. auto &content = cur_file->second.content;
  7512. if (content.size() + n > content.max_size()) { return false; }
  7513. content.append(buf, n);
  7514. }
  7515. return true;
  7516. })) {
  7517. const auto &content_type = req.get_header_value("Content-Type");
  7518. if (!content_type.find("application/x-www-form-urlencoded")) {
  7519. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  7520. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  7521. output_error_log(Error::ExceedMaxPayloadSize, &req);
  7522. return false;
  7523. }
  7524. detail::parse_query_text(req.body, req.params);
  7525. }
  7526. return true;
  7527. }
  7528. return false;
  7529. }
  7530. inline bool Server::read_content_with_content_receiver(
  7531. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7532. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  7533. return read_content_core(strm, req, res, std::move(receiver),
  7534. std::move(multipart_header),
  7535. std::move(multipart_receiver));
  7536. }
  7537. inline bool Server::read_content_core(
  7538. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  7539. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  7540. detail::FormDataParser multipart_form_data_parser;
  7541. ContentReceiverWithProgress out;
  7542. if (req.is_multipart_form_data()) {
  7543. const auto &content_type = req.get_header_value("Content-Type");
  7544. std::string boundary;
  7545. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  7546. res.status = StatusCode::BadRequest_400;
  7547. output_error_log(Error::MultipartParsing, &req);
  7548. return false;
  7549. }
  7550. multipart_form_data_parser.set_boundary(std::move(boundary));
  7551. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  7552. return multipart_form_data_parser.parse(buf, n, multipart_header,
  7553. multipart_receiver);
  7554. };
  7555. } else {
  7556. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  7557. size_t /*len*/) { return receiver(buf, n); };
  7558. }
  7559. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  7560. // are true (no Transfer-Encoding and no Content-Length), then the message
  7561. // body length is zero (no message body is present).
  7562. //
  7563. // For non-SSL builds, peek into the socket to detect clients that send a
  7564. // body without a Content-Length header (raw HTTP over TCP). If there is
  7565. // pending data that exceeds the configured payload limit, treat this as an
  7566. // oversized request and fail early (causing connection close). For SSL
  7567. // builds we cannot reliably peek the decrypted application bytes, so keep
  7568. // the original behaviour.
  7569. #if !defined(CPPHTTPLIB_OPENSSL_SUPPORT)
  7570. if (!req.has_header("Content-Length") &&
  7571. !detail::is_chunked_transfer_encoding(req.headers)) {
  7572. // Only peek if payload_max_length is set to a finite value
  7573. if (payload_max_length_ > 0 &&
  7574. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  7575. socket_t s = strm.socket();
  7576. if (s != INVALID_SOCKET) {
  7577. // Peek to check if there is any pending data
  7578. char peekbuf[1];
  7579. ssize_t n = ::recv(s, peekbuf, 1, MSG_PEEK);
  7580. if (n > 0) {
  7581. // There is data, so read it with payload limit enforcement
  7582. auto result = detail::read_content_without_length(
  7583. strm, payload_max_length_, out);
  7584. if (result == detail::ReadContentResult::PayloadTooLarge) {
  7585. res.status = StatusCode::PayloadTooLarge_413;
  7586. return false;
  7587. } else if (result != detail::ReadContentResult::Success) {
  7588. return false;
  7589. }
  7590. return true;
  7591. }
  7592. }
  7593. }
  7594. return true;
  7595. }
  7596. #else
  7597. if (!req.has_header("Content-Length") &&
  7598. !detail::is_chunked_transfer_encoding(req.headers)) {
  7599. return true;
  7600. }
  7601. #endif
  7602. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  7603. out, true)) {
  7604. return false;
  7605. }
  7606. if (req.is_multipart_form_data()) {
  7607. if (!multipart_form_data_parser.is_valid()) {
  7608. res.status = StatusCode::BadRequest_400;
  7609. output_error_log(Error::MultipartParsing, &req);
  7610. return false;
  7611. }
  7612. }
  7613. return true;
  7614. }
  7615. inline bool Server::handle_file_request(Request &req, Response &res) {
  7616. for (const auto &entry : base_dirs_) {
  7617. // Prefix match
  7618. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  7619. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  7620. if (detail::is_valid_path(sub_path)) {
  7621. auto path = entry.base_dir + sub_path;
  7622. if (path.back() == '/') { path += "index.html"; }
  7623. detail::FileStat stat(path);
  7624. if (stat.is_dir()) {
  7625. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  7626. return true;
  7627. }
  7628. if (stat.is_file()) {
  7629. for (const auto &kv : entry.headers) {
  7630. res.set_header(kv.first, kv.second);
  7631. }
  7632. auto etag = detail::compute_etag(stat);
  7633. if (!etag.empty()) { res.set_header("ETag", etag); }
  7634. auto mtime = stat.mtime();
  7635. auto last_modified = detail::file_mtime_to_http_date(mtime);
  7636. if (!last_modified.empty()) {
  7637. res.set_header("Last-Modified", last_modified);
  7638. }
  7639. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  7640. check_if_range(req, etag, mtime);
  7641. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7642. if (!mm->is_open()) {
  7643. output_error_log(Error::OpenFile, &req);
  7644. return false;
  7645. }
  7646. res.set_content_provider(
  7647. mm->size(),
  7648. detail::find_content_type(path, file_extension_and_mimetype_map_,
  7649. default_file_mimetype_),
  7650. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7651. sink.write(mm->data() + offset, length);
  7652. return true;
  7653. });
  7654. if (req.method != "HEAD" && file_request_handler_) {
  7655. file_request_handler_(req, res);
  7656. }
  7657. return true;
  7658. } else {
  7659. output_error_log(Error::OpenFile, &req);
  7660. }
  7661. }
  7662. }
  7663. }
  7664. return false;
  7665. }
  7666. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  7667. const std::string &etag,
  7668. time_t mtime) const {
  7669. // Handle conditional GET:
  7670. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  7671. // 2. If-Modified-Since is checked only when If-None-Match is absent
  7672. if (req.has_header("If-None-Match")) {
  7673. if (!etag.empty()) {
  7674. auto val = req.get_header_value("If-None-Match");
  7675. // NOTE: We use exact string matching here. This works correctly
  7676. // because our server always generates weak ETags (W/"..."), and
  7677. // clients typically send back the same ETag they received.
  7678. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  7679. // If-None-Match, where W/"x" and "x" would match, but this
  7680. // simplified implementation requires exact matches.
  7681. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  7682. [&](const char *b, const char *e) {
  7683. return std::equal(b, e, "*") ||
  7684. std::equal(b, e, etag.begin());
  7685. });
  7686. if (ret) {
  7687. res.status = StatusCode::NotModified_304;
  7688. return true;
  7689. }
  7690. }
  7691. } else if (req.has_header("If-Modified-Since")) {
  7692. auto val = req.get_header_value("If-Modified-Since");
  7693. auto t = detail::parse_http_date(val);
  7694. if (t != static_cast<time_t>(-1) && mtime <= t) {
  7695. res.status = StatusCode::NotModified_304;
  7696. return true;
  7697. }
  7698. }
  7699. return false;
  7700. }
  7701. inline bool Server::check_if_range(Request &req, const std::string &etag,
  7702. time_t mtime) const {
  7703. // Handle If-Range for partial content requests (RFC 9110
  7704. // Section 13.1.5). If-Range is only evaluated when Range header is
  7705. // present. If the validator matches, serve partial content; otherwise
  7706. // serve full content.
  7707. if (!req.ranges.empty() && req.has_header("If-Range")) {
  7708. auto val = req.get_header_value("If-Range");
  7709. auto is_valid_range = [&]() {
  7710. if (detail::is_strong_etag(val)) {
  7711. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  7712. // comparison.
  7713. return (!etag.empty() && val == etag);
  7714. } else if (detail::is_weak_etag(val)) {
  7715. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  7716. return false;
  7717. } else {
  7718. // HTTP-date comparison
  7719. auto t = detail::parse_http_date(val);
  7720. return (t != static_cast<time_t>(-1) && mtime <= t);
  7721. }
  7722. };
  7723. if (!is_valid_range()) {
  7724. // Validator doesn't match: ignore Range and serve full content
  7725. req.ranges.clear();
  7726. return false;
  7727. }
  7728. }
  7729. return true;
  7730. }
  7731. inline socket_t
  7732. Server::create_server_socket(const std::string &host, int port,
  7733. int socket_flags,
  7734. SocketOptions socket_options) const {
  7735. return detail::create_socket(
  7736. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  7737. ipv6_v6only_, std::move(socket_options),
  7738. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  7739. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  7740. output_error_log(Error::BindIPAddress, nullptr);
  7741. return false;
  7742. }
  7743. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  7744. output_error_log(Error::Listen, nullptr);
  7745. return false;
  7746. }
  7747. return true;
  7748. });
  7749. }
  7750. inline int Server::bind_internal(const std::string &host, int port,
  7751. int socket_flags) {
  7752. if (is_decommissioned) { return -1; }
  7753. if (!is_valid()) { return -1; }
  7754. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  7755. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  7756. if (port == 0) {
  7757. struct sockaddr_storage addr;
  7758. socklen_t addr_len = sizeof(addr);
  7759. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  7760. &addr_len) == -1) {
  7761. output_error_log(Error::GetSockName, nullptr);
  7762. return -1;
  7763. }
  7764. if (addr.ss_family == AF_INET) {
  7765. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  7766. } else if (addr.ss_family == AF_INET6) {
  7767. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  7768. } else {
  7769. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  7770. return -1;
  7771. }
  7772. } else {
  7773. return port;
  7774. }
  7775. }
  7776. inline bool Server::listen_internal() {
  7777. if (is_decommissioned) { return false; }
  7778. auto ret = true;
  7779. is_running_ = true;
  7780. auto se = detail::scope_exit([&]() { is_running_ = false; });
  7781. {
  7782. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  7783. while (svr_sock_ != INVALID_SOCKET) {
  7784. #ifndef _WIN32
  7785. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  7786. #endif
  7787. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  7788. idle_interval_usec_);
  7789. if (val == 0) { // Timeout
  7790. task_queue->on_idle();
  7791. continue;
  7792. }
  7793. #ifndef _WIN32
  7794. }
  7795. #endif
  7796. #if defined _WIN32
  7797. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  7798. // OVERLAPPED
  7799. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  7800. #elif defined SOCK_CLOEXEC
  7801. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  7802. #else
  7803. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  7804. #endif
  7805. if (sock == INVALID_SOCKET) {
  7806. if (errno == EMFILE) {
  7807. // The per-process limit of open file descriptors has been reached.
  7808. // Try to accept new connections after a short sleep.
  7809. std::this_thread::sleep_for(std::chrono::microseconds{1});
  7810. continue;
  7811. } else if (errno == EINTR || errno == EAGAIN) {
  7812. continue;
  7813. }
  7814. if (svr_sock_ != INVALID_SOCKET) {
  7815. detail::close_socket(svr_sock_);
  7816. ret = false;
  7817. output_error_log(Error::Connection, nullptr);
  7818. } else {
  7819. ; // The server socket was closed by user.
  7820. }
  7821. break;
  7822. }
  7823. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  7824. read_timeout_sec_, read_timeout_usec_);
  7825. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  7826. write_timeout_sec_, write_timeout_usec_);
  7827. if (!task_queue->enqueue(
  7828. [this, sock]() { process_and_close_socket(sock); })) {
  7829. output_error_log(Error::ResourceExhaustion, nullptr);
  7830. detail::shutdown_socket(sock);
  7831. detail::close_socket(sock);
  7832. }
  7833. }
  7834. task_queue->shutdown();
  7835. }
  7836. is_decommissioned = !ret;
  7837. return ret;
  7838. }
  7839. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  7840. if (pre_routing_handler_ &&
  7841. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  7842. return true;
  7843. }
  7844. // File handler
  7845. if ((req.method == "GET" || req.method == "HEAD") &&
  7846. handle_file_request(req, res)) {
  7847. return true;
  7848. }
  7849. if (detail::expect_content(req)) {
  7850. // Content reader handler
  7851. {
  7852. ContentReader reader(
  7853. [&](ContentReceiver receiver) {
  7854. auto result = read_content_with_content_receiver(
  7855. strm, req, res, std::move(receiver), nullptr, nullptr);
  7856. if (!result) { output_error_log(Error::Read, &req); }
  7857. return result;
  7858. },
  7859. [&](FormDataHeader header, ContentReceiver receiver) {
  7860. auto result = read_content_with_content_receiver(
  7861. strm, req, res, nullptr, std::move(header),
  7862. std::move(receiver));
  7863. if (!result) { output_error_log(Error::Read, &req); }
  7864. return result;
  7865. });
  7866. if (req.method == "POST") {
  7867. if (dispatch_request_for_content_reader(
  7868. req, res, std::move(reader),
  7869. post_handlers_for_content_reader_)) {
  7870. return true;
  7871. }
  7872. } else if (req.method == "PUT") {
  7873. if (dispatch_request_for_content_reader(
  7874. req, res, std::move(reader),
  7875. put_handlers_for_content_reader_)) {
  7876. return true;
  7877. }
  7878. } else if (req.method == "PATCH") {
  7879. if (dispatch_request_for_content_reader(
  7880. req, res, std::move(reader),
  7881. patch_handlers_for_content_reader_)) {
  7882. return true;
  7883. }
  7884. } else if (req.method == "DELETE") {
  7885. if (dispatch_request_for_content_reader(
  7886. req, res, std::move(reader),
  7887. delete_handlers_for_content_reader_)) {
  7888. return true;
  7889. }
  7890. }
  7891. }
  7892. // Read content into `req.body`
  7893. if (!read_content(strm, req, res)) {
  7894. output_error_log(Error::Read, &req);
  7895. return false;
  7896. }
  7897. }
  7898. // Regular handler
  7899. if (req.method == "GET" || req.method == "HEAD") {
  7900. return dispatch_request(req, res, get_handlers_);
  7901. } else if (req.method == "POST") {
  7902. return dispatch_request(req, res, post_handlers_);
  7903. } else if (req.method == "PUT") {
  7904. return dispatch_request(req, res, put_handlers_);
  7905. } else if (req.method == "DELETE") {
  7906. return dispatch_request(req, res, delete_handlers_);
  7907. } else if (req.method == "OPTIONS") {
  7908. return dispatch_request(req, res, options_handlers_);
  7909. } else if (req.method == "PATCH") {
  7910. return dispatch_request(req, res, patch_handlers_);
  7911. }
  7912. res.status = StatusCode::BadRequest_400;
  7913. return false;
  7914. }
  7915. inline bool Server::dispatch_request(Request &req, Response &res,
  7916. const Handlers &handlers) const {
  7917. for (const auto &x : handlers) {
  7918. const auto &matcher = x.first;
  7919. const auto &handler = x.second;
  7920. if (matcher->match(req)) {
  7921. req.matched_route = matcher->pattern();
  7922. if (!pre_request_handler_ ||
  7923. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  7924. handler(req, res);
  7925. }
  7926. return true;
  7927. }
  7928. }
  7929. return false;
  7930. }
  7931. inline void Server::apply_ranges(const Request &req, Response &res,
  7932. std::string &content_type,
  7933. std::string &boundary) const {
  7934. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  7935. auto it = res.headers.find("Content-Type");
  7936. if (it != res.headers.end()) {
  7937. content_type = it->second;
  7938. res.headers.erase(it);
  7939. }
  7940. boundary = detail::make_multipart_data_boundary();
  7941. res.set_header("Content-Type",
  7942. "multipart/byteranges; boundary=" + boundary);
  7943. }
  7944. auto type = detail::encoding_type(req, res);
  7945. if (res.body.empty()) {
  7946. if (res.content_length_ > 0) {
  7947. size_t length = 0;
  7948. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  7949. length = res.content_length_;
  7950. } else if (req.ranges.size() == 1) {
  7951. auto offset_and_length = detail::get_range_offset_and_length(
  7952. req.ranges[0], res.content_length_);
  7953. length = offset_and_length.second;
  7954. auto content_range = detail::make_content_range_header_field(
  7955. offset_and_length, res.content_length_);
  7956. res.set_header("Content-Range", content_range);
  7957. } else {
  7958. length = detail::get_multipart_ranges_data_length(
  7959. req, boundary, content_type, res.content_length_);
  7960. }
  7961. res.set_header("Content-Length", std::to_string(length));
  7962. } else {
  7963. if (res.content_provider_) {
  7964. if (res.is_chunked_content_provider_) {
  7965. res.set_header("Transfer-Encoding", "chunked");
  7966. if (type == detail::EncodingType::Gzip) {
  7967. res.set_header("Content-Encoding", "gzip");
  7968. res.set_header("Vary", "Accept-Encoding");
  7969. } else if (type == detail::EncodingType::Brotli) {
  7970. res.set_header("Content-Encoding", "br");
  7971. res.set_header("Vary", "Accept-Encoding");
  7972. } else if (type == detail::EncodingType::Zstd) {
  7973. res.set_header("Content-Encoding", "zstd");
  7974. res.set_header("Vary", "Accept-Encoding");
  7975. }
  7976. }
  7977. }
  7978. }
  7979. } else {
  7980. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  7981. ;
  7982. } else if (req.ranges.size() == 1) {
  7983. auto offset_and_length =
  7984. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  7985. auto offset = offset_and_length.first;
  7986. auto length = offset_and_length.second;
  7987. auto content_range = detail::make_content_range_header_field(
  7988. offset_and_length, res.body.size());
  7989. res.set_header("Content-Range", content_range);
  7990. assert(offset + length <= res.body.size());
  7991. res.body = res.body.substr(offset, length);
  7992. } else {
  7993. std::string data;
  7994. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  7995. res.body.size(), data);
  7996. res.body.swap(data);
  7997. }
  7998. if (type != detail::EncodingType::None) {
  7999. output_pre_compression_log(req, res);
  8000. std::unique_ptr<detail::compressor> compressor;
  8001. std::string content_encoding;
  8002. if (type == detail::EncodingType::Gzip) {
  8003. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8004. compressor = detail::make_unique<detail::gzip_compressor>();
  8005. content_encoding = "gzip";
  8006. #endif
  8007. } else if (type == detail::EncodingType::Brotli) {
  8008. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8009. compressor = detail::make_unique<detail::brotli_compressor>();
  8010. content_encoding = "br";
  8011. #endif
  8012. } else if (type == detail::EncodingType::Zstd) {
  8013. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8014. compressor = detail::make_unique<detail::zstd_compressor>();
  8015. content_encoding = "zstd";
  8016. #endif
  8017. }
  8018. if (compressor) {
  8019. std::string compressed;
  8020. if (compressor->compress(res.body.data(), res.body.size(), true,
  8021. [&](const char *data, size_t data_len) {
  8022. compressed.append(data, data_len);
  8023. return true;
  8024. })) {
  8025. res.body.swap(compressed);
  8026. res.set_header("Content-Encoding", content_encoding);
  8027. res.set_header("Vary", "Accept-Encoding");
  8028. }
  8029. }
  8030. }
  8031. auto length = std::to_string(res.body.size());
  8032. res.set_header("Content-Length", length);
  8033. }
  8034. }
  8035. inline bool Server::dispatch_request_for_content_reader(
  8036. Request &req, Response &res, ContentReader content_reader,
  8037. const HandlersForContentReader &handlers) const {
  8038. for (const auto &x : handlers) {
  8039. const auto &matcher = x.first;
  8040. const auto &handler = x.second;
  8041. if (matcher->match(req)) {
  8042. req.matched_route = matcher->pattern();
  8043. if (!pre_request_handler_ ||
  8044. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  8045. handler(req, res, content_reader);
  8046. }
  8047. return true;
  8048. }
  8049. }
  8050. return false;
  8051. }
  8052. inline std::string
  8053. get_client_ip(const std::string &x_forwarded_for,
  8054. const std::vector<std::string> &trusted_proxies) {
  8055. // X-Forwarded-For is a comma-separated list per RFC 7239
  8056. std::vector<std::string> ip_list;
  8057. detail::split(x_forwarded_for.data(),
  8058. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  8059. [&](const char *b, const char *e) {
  8060. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  8061. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  8062. });
  8063. for (size_t i = 0; i < ip_list.size(); ++i) {
  8064. auto ip = ip_list[i];
  8065. auto is_trusted_proxy =
  8066. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  8067. [&](const std::string &proxy) { return ip == proxy; });
  8068. if (is_trusted_proxy) {
  8069. if (i == 0) {
  8070. // If the trusted proxy is the first IP, there's no preceding client IP
  8071. return ip;
  8072. } else {
  8073. // Return the IP immediately before the trusted proxy
  8074. return ip_list[i - 1];
  8075. }
  8076. }
  8077. }
  8078. // If no trusted proxy is found, return the first IP in the list
  8079. return ip_list.front();
  8080. }
  8081. inline bool
  8082. Server::process_request(Stream &strm, const std::string &remote_addr,
  8083. int remote_port, const std::string &local_addr,
  8084. int local_port, bool close_connection,
  8085. bool &connection_closed,
  8086. const std::function<void(Request &)> &setup_request) {
  8087. std::array<char, 2048> buf{};
  8088. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8089. // Connection has been closed on client
  8090. if (!line_reader.getline()) { return false; }
  8091. Request req;
  8092. req.start_time_ = std::chrono::steady_clock::now();
  8093. req.remote_addr = remote_addr;
  8094. req.remote_port = remote_port;
  8095. req.local_addr = local_addr;
  8096. req.local_port = local_port;
  8097. Response res;
  8098. res.version = "HTTP/1.1";
  8099. res.headers = default_headers_;
  8100. #ifdef __APPLE__
  8101. // Socket file descriptor exceeded FD_SETSIZE...
  8102. if (strm.socket() >= FD_SETSIZE) {
  8103. Headers dummy;
  8104. detail::read_headers(strm, dummy);
  8105. res.status = StatusCode::InternalServerError_500;
  8106. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  8107. return write_response(strm, close_connection, req, res);
  8108. }
  8109. #endif
  8110. // Request line and headers
  8111. if (!parse_request_line(line_reader.ptr(), req)) {
  8112. res.status = StatusCode::BadRequest_400;
  8113. output_error_log(Error::InvalidRequestLine, &req);
  8114. return write_response(strm, close_connection, req, res);
  8115. }
  8116. // Request headers
  8117. if (!detail::read_headers(strm, req.headers)) {
  8118. res.status = StatusCode::BadRequest_400;
  8119. output_error_log(Error::InvalidHeaders, &req);
  8120. return write_response(strm, close_connection, req, res);
  8121. }
  8122. // Check if the request URI doesn't exceed the limit
  8123. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  8124. res.status = StatusCode::UriTooLong_414;
  8125. output_error_log(Error::ExceedUriMaxLength, &req);
  8126. return write_response(strm, close_connection, req, res);
  8127. }
  8128. if (req.get_header_value("Connection") == "close") {
  8129. connection_closed = true;
  8130. }
  8131. if (req.version == "HTTP/1.0" &&
  8132. req.get_header_value("Connection") != "Keep-Alive") {
  8133. connection_closed = true;
  8134. }
  8135. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  8136. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  8137. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  8138. } else {
  8139. req.remote_addr = remote_addr;
  8140. }
  8141. req.remote_port = remote_port;
  8142. req.local_addr = local_addr;
  8143. req.local_port = local_port;
  8144. if (req.has_header("Accept")) {
  8145. const auto &accept_header = req.get_header_value("Accept");
  8146. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  8147. res.status = StatusCode::BadRequest_400;
  8148. output_error_log(Error::HTTPParsing, &req);
  8149. return write_response(strm, close_connection, req, res);
  8150. }
  8151. }
  8152. if (req.has_header("Range")) {
  8153. const auto &range_header_value = req.get_header_value("Range");
  8154. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  8155. res.status = StatusCode::RangeNotSatisfiable_416;
  8156. output_error_log(Error::InvalidRangeHeader, &req);
  8157. return write_response(strm, close_connection, req, res);
  8158. }
  8159. }
  8160. if (setup_request) { setup_request(req); }
  8161. if (req.get_header_value("Expect") == "100-continue") {
  8162. int status = StatusCode::Continue_100;
  8163. if (expect_100_continue_handler_) {
  8164. status = expect_100_continue_handler_(req, res);
  8165. }
  8166. switch (status) {
  8167. case StatusCode::Continue_100:
  8168. case StatusCode::ExpectationFailed_417:
  8169. detail::write_response_line(strm, status);
  8170. strm.write("\r\n");
  8171. break;
  8172. default:
  8173. connection_closed = true;
  8174. return write_response(strm, true, req, res);
  8175. }
  8176. }
  8177. // Setup `is_connection_closed` method
  8178. auto sock = strm.socket();
  8179. req.is_connection_closed = [sock]() {
  8180. return !detail::is_socket_alive(sock);
  8181. };
  8182. // Routing
  8183. auto routed = false;
  8184. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  8185. routed = routing(req, res, strm);
  8186. #else
  8187. try {
  8188. routed = routing(req, res, strm);
  8189. } catch (std::exception &e) {
  8190. if (exception_handler_) {
  8191. auto ep = std::current_exception();
  8192. exception_handler_(req, res, ep);
  8193. routed = true;
  8194. } else {
  8195. res.status = StatusCode::InternalServerError_500;
  8196. std::string val;
  8197. auto s = e.what();
  8198. for (size_t i = 0; s[i]; i++) {
  8199. switch (s[i]) {
  8200. case '\r': val += "\\r"; break;
  8201. case '\n': val += "\\n"; break;
  8202. default: val += s[i]; break;
  8203. }
  8204. }
  8205. res.set_header("EXCEPTION_WHAT", val);
  8206. }
  8207. } catch (...) {
  8208. if (exception_handler_) {
  8209. auto ep = std::current_exception();
  8210. exception_handler_(req, res, ep);
  8211. routed = true;
  8212. } else {
  8213. res.status = StatusCode::InternalServerError_500;
  8214. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  8215. }
  8216. }
  8217. #endif
  8218. if (routed) {
  8219. if (res.status == -1) {
  8220. res.status = req.ranges.empty() ? StatusCode::OK_200
  8221. : StatusCode::PartialContent_206;
  8222. }
  8223. // Serve file content by using a content provider
  8224. if (!res.file_content_path_.empty()) {
  8225. const auto &path = res.file_content_path_;
  8226. auto mm = std::make_shared<detail::mmap>(path.c_str());
  8227. if (!mm->is_open()) {
  8228. res.body.clear();
  8229. res.content_length_ = 0;
  8230. res.content_provider_ = nullptr;
  8231. res.status = StatusCode::NotFound_404;
  8232. output_error_log(Error::OpenFile, &req);
  8233. return write_response(strm, close_connection, req, res);
  8234. }
  8235. auto content_type = res.file_content_content_type_;
  8236. if (content_type.empty()) {
  8237. content_type = detail::find_content_type(
  8238. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  8239. }
  8240. res.set_content_provider(
  8241. mm->size(), content_type,
  8242. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  8243. sink.write(mm->data() + offset, length);
  8244. return true;
  8245. });
  8246. }
  8247. if (detail::range_error(req, res)) {
  8248. res.body.clear();
  8249. res.content_length_ = 0;
  8250. res.content_provider_ = nullptr;
  8251. res.status = StatusCode::RangeNotSatisfiable_416;
  8252. return write_response(strm, close_connection, req, res);
  8253. }
  8254. return write_response_with_content(strm, close_connection, req, res);
  8255. } else {
  8256. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  8257. return write_response(strm, close_connection, req, res);
  8258. }
  8259. }
  8260. inline bool Server::is_valid() const { return true; }
  8261. inline bool Server::process_and_close_socket(socket_t sock) {
  8262. std::string remote_addr;
  8263. int remote_port = 0;
  8264. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8265. std::string local_addr;
  8266. int local_port = 0;
  8267. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8268. auto ret = detail::process_server_socket(
  8269. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8270. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8271. write_timeout_usec_,
  8272. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8273. return process_request(strm, remote_addr, remote_port, local_addr,
  8274. local_port, close_connection, connection_closed,
  8275. nullptr);
  8276. });
  8277. detail::shutdown_socket(sock);
  8278. detail::close_socket(sock);
  8279. return ret;
  8280. }
  8281. inline void Server::output_log(const Request &req, const Response &res) const {
  8282. if (logger_) {
  8283. std::lock_guard<std::mutex> guard(logger_mutex_);
  8284. logger_(req, res);
  8285. }
  8286. }
  8287. inline void Server::output_pre_compression_log(const Request &req,
  8288. const Response &res) const {
  8289. if (pre_compression_logger_) {
  8290. std::lock_guard<std::mutex> guard(logger_mutex_);
  8291. pre_compression_logger_(req, res);
  8292. }
  8293. }
  8294. inline void Server::output_error_log(const Error &err,
  8295. const Request *req) const {
  8296. if (error_logger_) {
  8297. std::lock_guard<std::mutex> guard(logger_mutex_);
  8298. error_logger_(err, req);
  8299. }
  8300. }
  8301. // HTTP client implementation
  8302. inline ClientImpl::ClientImpl(const std::string &host)
  8303. : ClientImpl(host, 80, std::string(), std::string()) {}
  8304. inline ClientImpl::ClientImpl(const std::string &host, int port)
  8305. : ClientImpl(host, port, std::string(), std::string()) {}
  8306. inline ClientImpl::ClientImpl(const std::string &host, int port,
  8307. const std::string &client_cert_path,
  8308. const std::string &client_key_path)
  8309. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  8310. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  8311. inline ClientImpl::~ClientImpl() {
  8312. // Wait until all the requests in flight are handled.
  8313. size_t retry_count = 10;
  8314. while (retry_count-- > 0) {
  8315. {
  8316. std::lock_guard<std::mutex> guard(socket_mutex_);
  8317. if (socket_requests_in_flight_ == 0) { break; }
  8318. }
  8319. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  8320. }
  8321. std::lock_guard<std::mutex> guard(socket_mutex_);
  8322. shutdown_socket(socket_);
  8323. close_socket(socket_);
  8324. }
  8325. inline bool ClientImpl::is_valid() const { return true; }
  8326. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  8327. client_cert_path_ = rhs.client_cert_path_;
  8328. client_key_path_ = rhs.client_key_path_;
  8329. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  8330. read_timeout_sec_ = rhs.read_timeout_sec_;
  8331. read_timeout_usec_ = rhs.read_timeout_usec_;
  8332. write_timeout_sec_ = rhs.write_timeout_sec_;
  8333. write_timeout_usec_ = rhs.write_timeout_usec_;
  8334. max_timeout_msec_ = rhs.max_timeout_msec_;
  8335. basic_auth_username_ = rhs.basic_auth_username_;
  8336. basic_auth_password_ = rhs.basic_auth_password_;
  8337. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  8338. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8339. digest_auth_username_ = rhs.digest_auth_username_;
  8340. digest_auth_password_ = rhs.digest_auth_password_;
  8341. #endif
  8342. keep_alive_ = rhs.keep_alive_;
  8343. follow_location_ = rhs.follow_location_;
  8344. path_encode_ = rhs.path_encode_;
  8345. address_family_ = rhs.address_family_;
  8346. tcp_nodelay_ = rhs.tcp_nodelay_;
  8347. ipv6_v6only_ = rhs.ipv6_v6only_;
  8348. socket_options_ = rhs.socket_options_;
  8349. compress_ = rhs.compress_;
  8350. decompress_ = rhs.decompress_;
  8351. interface_ = rhs.interface_;
  8352. proxy_host_ = rhs.proxy_host_;
  8353. proxy_port_ = rhs.proxy_port_;
  8354. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  8355. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  8356. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  8357. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8358. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  8359. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  8360. #endif
  8361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8362. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  8363. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  8364. ca_cert_store_ = rhs.ca_cert_store_;
  8365. #endif
  8366. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8367. server_certificate_verification_ = rhs.server_certificate_verification_;
  8368. server_hostname_verification_ = rhs.server_hostname_verification_;
  8369. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  8370. #endif
  8371. logger_ = rhs.logger_;
  8372. error_logger_ = rhs.error_logger_;
  8373. }
  8374. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  8375. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8376. return detail::create_client_socket(
  8377. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  8378. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  8379. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  8380. write_timeout_sec_, write_timeout_usec_, interface_, error);
  8381. }
  8382. // Check is custom IP specified for host_
  8383. std::string ip;
  8384. auto it = addr_map_.find(host_);
  8385. if (it != addr_map_.end()) { ip = it->second; }
  8386. return detail::create_client_socket(
  8387. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  8388. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  8389. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8390. write_timeout_usec_, interface_, error);
  8391. }
  8392. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  8393. Error &error) {
  8394. auto sock = create_client_socket(error);
  8395. if (sock == INVALID_SOCKET) { return false; }
  8396. socket.sock = sock;
  8397. return true;
  8398. }
  8399. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  8400. return create_and_connect_socket(socket, error);
  8401. }
  8402. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8403. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  8404. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  8405. if (!proxy_host_.empty() && proxy_port_ != -1) { return true; }
  8406. if (!initialize_ssl(socket, error)) {
  8407. shutdown_socket(socket);
  8408. close_socket(socket);
  8409. return false;
  8410. }
  8411. return true;
  8412. }
  8413. #endif
  8414. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  8415. bool /*shutdown_gracefully*/) {
  8416. // If there are any requests in flight from threads other than us, then it's
  8417. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  8418. assert(socket_requests_in_flight_ == 0 ||
  8419. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8420. }
  8421. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  8422. if (socket.sock == INVALID_SOCKET) { return; }
  8423. detail::shutdown_socket(socket.sock);
  8424. }
  8425. inline void ClientImpl::close_socket(Socket &socket) {
  8426. // If there are requests in flight in another thread, usually closing
  8427. // the socket will be fine and they will simply receive an error when
  8428. // using the closed socket, but it is still a bug since rarely the OS
  8429. // may reassign the socket id to be used for a new socket, and then
  8430. // suddenly they will be operating on a live socket that is different
  8431. // than the one they intended!
  8432. assert(socket_requests_in_flight_ == 0 ||
  8433. socket_requests_are_from_thread_ == std::this_thread::get_id());
  8434. // It is also a bug if this happens while SSL is still active
  8435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8436. assert(socket.ssl == nullptr);
  8437. #endif
  8438. if (socket.sock == INVALID_SOCKET) { return; }
  8439. detail::close_socket(socket.sock);
  8440. socket.sock = INVALID_SOCKET;
  8441. }
  8442. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  8443. Response &res) const {
  8444. std::array<char, 2048> buf{};
  8445. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  8446. if (!line_reader.getline()) { return false; }
  8447. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  8448. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  8449. #else
  8450. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  8451. #endif
  8452. std::cmatch m;
  8453. if (!std::regex_match(line_reader.ptr(), m, re)) {
  8454. return req.method == "CONNECT";
  8455. }
  8456. res.version = std::string(m[1]);
  8457. res.status = std::stoi(std::string(m[2]));
  8458. res.reason = std::string(m[3]);
  8459. // Ignore '100 Continue'
  8460. while (res.status == StatusCode::Continue_100) {
  8461. if (!line_reader.getline()) { return false; } // CRLF
  8462. if (!line_reader.getline()) { return false; } // next response line
  8463. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  8464. res.version = std::string(m[1]);
  8465. res.status = std::stoi(std::string(m[2]));
  8466. res.reason = std::string(m[3]);
  8467. }
  8468. return true;
  8469. }
  8470. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  8471. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  8472. auto ret = send_(req, res, error);
  8473. if (error == Error::SSLPeerCouldBeClosed_) {
  8474. assert(!ret);
  8475. ret = send_(req, res, error);
  8476. }
  8477. return ret;
  8478. }
  8479. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  8480. {
  8481. std::lock_guard<std::mutex> guard(socket_mutex_);
  8482. // Set this to false immediately - if it ever gets set to true by the end
  8483. // of the request, we know another thread instructed us to close the
  8484. // socket.
  8485. socket_should_be_closed_when_request_is_done_ = false;
  8486. auto is_alive = false;
  8487. if (socket_.is_open()) {
  8488. is_alive = detail::is_socket_alive(socket_.sock);
  8489. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8490. if (is_alive && is_ssl()) {
  8491. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  8492. is_alive = false;
  8493. }
  8494. }
  8495. #endif
  8496. if (!is_alive) {
  8497. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  8498. // seems like the other side has already closed the connection Also,
  8499. // there cannot be any requests in flight from other threads since we
  8500. // locked request_mutex_, so safe to close everything immediately
  8501. const bool shutdown_gracefully = false;
  8502. shutdown_ssl(socket_, shutdown_gracefully);
  8503. shutdown_socket(socket_);
  8504. close_socket(socket_);
  8505. }
  8506. }
  8507. if (!is_alive) {
  8508. if (!ensure_socket_connection(socket_, error)) {
  8509. output_error_log(error, &req);
  8510. return false;
  8511. }
  8512. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8513. // TODO: refactoring
  8514. if (is_ssl()) {
  8515. auto &scli = static_cast<SSLClient &>(*this);
  8516. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8517. auto success = false;
  8518. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  8519. error)) {
  8520. if (!success) { output_error_log(error, &req); }
  8521. return success;
  8522. }
  8523. }
  8524. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8525. if (!scli.initialize_ssl(socket_, error)) {
  8526. output_error_log(error, &req);
  8527. return false;
  8528. }
  8529. }
  8530. }
  8531. #endif
  8532. }
  8533. // Mark the current socket as being in use so that it cannot be closed by
  8534. // anyone else while this request is ongoing, even though we will be
  8535. // releasing the mutex.
  8536. if (socket_requests_in_flight_ > 1) {
  8537. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  8538. }
  8539. socket_requests_in_flight_ += 1;
  8540. socket_requests_are_from_thread_ = std::this_thread::get_id();
  8541. }
  8542. for (const auto &header : default_headers_) {
  8543. if (req.headers.find(header.first) == req.headers.end()) {
  8544. req.headers.insert(header);
  8545. }
  8546. }
  8547. auto ret = false;
  8548. auto close_connection = !keep_alive_;
  8549. auto se = detail::scope_exit([&]() {
  8550. // Briefly lock mutex in order to mark that a request is no longer ongoing
  8551. std::lock_guard<std::mutex> guard(socket_mutex_);
  8552. socket_requests_in_flight_ -= 1;
  8553. if (socket_requests_in_flight_ <= 0) {
  8554. assert(socket_requests_in_flight_ == 0);
  8555. socket_requests_are_from_thread_ = std::thread::id();
  8556. }
  8557. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  8558. !ret) {
  8559. shutdown_ssl(socket_, true);
  8560. shutdown_socket(socket_);
  8561. close_socket(socket_);
  8562. }
  8563. });
  8564. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  8565. return handle_request(strm, req, res, close_connection, error);
  8566. });
  8567. if (!ret) {
  8568. if (error == Error::Success) {
  8569. error = Error::Unknown;
  8570. output_error_log(error, &req);
  8571. }
  8572. }
  8573. return ret;
  8574. }
  8575. inline Result ClientImpl::send(const Request &req) {
  8576. auto req2 = req;
  8577. return send_(std::move(req2));
  8578. }
  8579. inline Result ClientImpl::send_(Request &&req) {
  8580. auto res = detail::make_unique<Response>();
  8581. auto error = Error::Success;
  8582. auto ret = send(req, *res, error);
  8583. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8584. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  8585. last_ssl_error_, last_openssl_error_};
  8586. #else
  8587. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  8588. #endif
  8589. }
  8590. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  8591. const std::string &ct) {
  8592. (void)for_stream;
  8593. for (const auto &header : default_headers_) {
  8594. if (!r.has_header(header.first)) { r.headers.insert(header); }
  8595. }
  8596. if (!r.has_header("Host")) {
  8597. if (address_family_ == AF_UNIX) {
  8598. r.headers.emplace("Host", "localhost");
  8599. } else {
  8600. r.headers.emplace(
  8601. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  8602. }
  8603. }
  8604. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  8605. if (!r.content_receiver) {
  8606. if (!r.has_header("Accept-Encoding")) {
  8607. std::string accept_encoding;
  8608. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8609. accept_encoding = "br";
  8610. #endif
  8611. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8612. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8613. accept_encoding += "gzip, deflate";
  8614. #endif
  8615. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8616. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  8617. accept_encoding += "zstd";
  8618. #endif
  8619. r.set_header("Accept-Encoding", accept_encoding);
  8620. }
  8621. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  8622. if (!r.has_header("User-Agent")) {
  8623. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  8624. r.set_header("User-Agent", agent);
  8625. }
  8626. #endif
  8627. }
  8628. if (!r.body.empty()) {
  8629. if (!ct.empty() && !r.has_header("Content-Type")) {
  8630. r.headers.emplace("Content-Type", ct);
  8631. }
  8632. if (!r.has_header("Content-Length")) {
  8633. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  8634. }
  8635. }
  8636. }
  8637. inline ClientImpl::StreamHandle
  8638. ClientImpl::open_stream(const std::string &method, const std::string &path,
  8639. const Params &params, const Headers &headers,
  8640. const std::string &body,
  8641. const std::string &content_type) {
  8642. StreamHandle handle;
  8643. handle.response = detail::make_unique<Response>();
  8644. handle.error = Error::Success;
  8645. auto query_path = params.empty() ? path : append_query_params(path, params);
  8646. handle.connection_ = detail::make_unique<ClientConnection>();
  8647. {
  8648. std::lock_guard<std::mutex> guard(socket_mutex_);
  8649. auto is_alive = false;
  8650. if (socket_.is_open()) {
  8651. is_alive = detail::is_socket_alive(socket_.sock);
  8652. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8653. if (is_alive && is_ssl()) {
  8654. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  8655. is_alive = false;
  8656. }
  8657. }
  8658. #endif
  8659. if (!is_alive) {
  8660. shutdown_ssl(socket_, false);
  8661. shutdown_socket(socket_);
  8662. close_socket(socket_);
  8663. }
  8664. }
  8665. if (!is_alive) {
  8666. if (!ensure_socket_connection(socket_, handle.error)) {
  8667. handle.response.reset();
  8668. return handle;
  8669. }
  8670. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8671. if (is_ssl()) {
  8672. auto &scli = static_cast<SSLClient &>(*this);
  8673. if (!proxy_host_.empty() && proxy_port_ != -1) {
  8674. if (!scli.initialize_ssl(socket_, handle.error)) {
  8675. handle.response.reset();
  8676. return handle;
  8677. }
  8678. }
  8679. }
  8680. #endif
  8681. }
  8682. transfer_socket_ownership_to_handle(handle);
  8683. }
  8684. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8685. if (is_ssl() && handle.connection_->ssl) {
  8686. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  8687. handle.connection_->sock, handle.connection_->ssl, read_timeout_sec_,
  8688. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_);
  8689. } else {
  8690. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8691. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8692. write_timeout_sec_, write_timeout_usec_);
  8693. }
  8694. #else
  8695. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  8696. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  8697. write_timeout_sec_, write_timeout_usec_);
  8698. #endif
  8699. handle.stream_ = handle.socket_stream_.get();
  8700. Request req;
  8701. req.method = method;
  8702. req.path = query_path;
  8703. req.headers = headers;
  8704. req.body = body;
  8705. prepare_default_headers(req, true, content_type);
  8706. auto &strm = *handle.stream_;
  8707. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  8708. handle.error = Error::Write;
  8709. handle.response.reset();
  8710. return handle;
  8711. }
  8712. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  8713. handle.error)) {
  8714. handle.response.reset();
  8715. return handle;
  8716. }
  8717. if (!body.empty()) {
  8718. if (strm.write(body.data(), body.size()) < 0) {
  8719. handle.error = Error::Write;
  8720. handle.response.reset();
  8721. return handle;
  8722. }
  8723. }
  8724. if (!read_response_line(strm, req, *handle.response) ||
  8725. !detail::read_headers(strm, handle.response->headers)) {
  8726. handle.error = Error::Read;
  8727. handle.response.reset();
  8728. return handle;
  8729. }
  8730. handle.body_reader_.stream = handle.stream_;
  8731. auto content_length_str = handle.response->get_header_value("Content-Length");
  8732. if (!content_length_str.empty()) {
  8733. handle.body_reader_.content_length =
  8734. static_cast<size_t>(std::stoull(content_length_str));
  8735. }
  8736. auto transfer_encoding =
  8737. handle.response->get_header_value("Transfer-Encoding");
  8738. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  8739. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  8740. if (!content_encoding.empty()) {
  8741. handle.decompressor_ = detail::create_decompressor(content_encoding);
  8742. }
  8743. return handle;
  8744. }
  8745. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  8746. if (!is_valid() || !response) { return -1; }
  8747. if (decompressor_) { return read_with_decompression(buf, len); }
  8748. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  8749. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  8750. trailers_parsed_ = true;
  8751. if (body_reader_.chunked_decoder) {
  8752. if (!body_reader_.chunked_decoder->parse_trailers_into(
  8753. response->trailers, response->headers)) {
  8754. return n;
  8755. }
  8756. } else {
  8757. detail::ChunkedDecoder dec(*stream_);
  8758. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  8759. return n;
  8760. }
  8761. }
  8762. }
  8763. return n;
  8764. }
  8765. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  8766. size_t len) {
  8767. if (decompress_offset_ < decompress_buffer_.size()) {
  8768. auto available = decompress_buffer_.size() - decompress_offset_;
  8769. auto to_copy = (std::min)(len, available);
  8770. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  8771. decompress_offset_ += to_copy;
  8772. return static_cast<ssize_t>(to_copy);
  8773. }
  8774. decompress_buffer_.clear();
  8775. decompress_offset_ = 0;
  8776. constexpr size_t kDecompressionBufferSize = 8192;
  8777. char compressed_buf[kDecompressionBufferSize];
  8778. while (true) {
  8779. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  8780. sizeof(compressed_buf));
  8781. if (n <= 0) { return n; }
  8782. bool decompress_ok =
  8783. decompressor_->decompress(compressed_buf, static_cast<size_t>(n),
  8784. [this](const char *data, size_t data_len) {
  8785. decompress_buffer_.append(data, data_len);
  8786. return true;
  8787. });
  8788. if (!decompress_ok) {
  8789. body_reader_.last_error = Error::Read;
  8790. return -1;
  8791. }
  8792. if (!decompress_buffer_.empty()) { break; }
  8793. }
  8794. auto to_copy = (std::min)(len, decompress_buffer_.size());
  8795. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  8796. decompress_offset_ = to_copy;
  8797. return static_cast<ssize_t>(to_copy);
  8798. }
  8799. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  8800. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  8801. return;
  8802. }
  8803. trailers_parsed_ = true;
  8804. const auto bufsiz = 128;
  8805. char line_buf[bufsiz];
  8806. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  8807. if (!line_reader.getline()) { return; }
  8808. if (!detail::parse_trailers(line_reader, response->trailers,
  8809. response->headers)) {
  8810. return;
  8811. }
  8812. }
  8813. // Inline method implementations for `ChunkedDecoder`.
  8814. namespace detail {
  8815. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  8816. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  8817. size_t &out_chunk_offset,
  8818. size_t &out_chunk_total) {
  8819. if (finished) { return 0; }
  8820. if (chunk_remaining == 0) {
  8821. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8822. if (!lr.getline()) { return -1; }
  8823. char *endptr = nullptr;
  8824. unsigned long chunk_len = std::strtoul(lr.ptr(), &endptr, 16);
  8825. if (endptr == lr.ptr()) { return -1; }
  8826. if (chunk_len == ULONG_MAX) { return -1; }
  8827. if (chunk_len == 0) {
  8828. chunk_remaining = 0;
  8829. finished = true;
  8830. out_chunk_offset = 0;
  8831. out_chunk_total = 0;
  8832. return 0;
  8833. }
  8834. chunk_remaining = static_cast<size_t>(chunk_len);
  8835. last_chunk_total = chunk_remaining;
  8836. last_chunk_offset = 0;
  8837. }
  8838. auto to_read = (std::min)(chunk_remaining, len);
  8839. auto n = strm.read(buf, to_read);
  8840. if (n <= 0) { return -1; }
  8841. auto offset_before = last_chunk_offset;
  8842. last_chunk_offset += static_cast<size_t>(n);
  8843. chunk_remaining -= static_cast<size_t>(n);
  8844. out_chunk_offset = offset_before;
  8845. out_chunk_total = last_chunk_total;
  8846. if (chunk_remaining == 0) {
  8847. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8848. if (!lr.getline()) { return -1; }
  8849. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  8850. }
  8851. return n;
  8852. }
  8853. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  8854. const Headers &src_headers) {
  8855. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  8856. if (!lr.getline()) { return false; }
  8857. return parse_trailers(lr, dest, src_headers);
  8858. }
  8859. } // namespace detail
  8860. inline void
  8861. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  8862. handle.connection_->sock = socket_.sock;
  8863. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8864. handle.connection_->ssl = socket_.ssl;
  8865. socket_.ssl = nullptr;
  8866. #endif
  8867. socket_.sock = INVALID_SOCKET;
  8868. }
  8869. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  8870. Response &res, bool close_connection,
  8871. Error &error) {
  8872. if (req.path.empty()) {
  8873. error = Error::Connection;
  8874. output_error_log(error, &req);
  8875. return false;
  8876. }
  8877. auto req_save = req;
  8878. bool ret;
  8879. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  8880. auto req2 = req;
  8881. req2.path = "http://" +
  8882. detail::make_host_and_port_string(host_, port_, false) +
  8883. req.path;
  8884. ret = process_request(strm, req2, res, close_connection, error);
  8885. req = std::move(req2);
  8886. req.path = req_save.path;
  8887. } else {
  8888. ret = process_request(strm, req, res, close_connection, error);
  8889. }
  8890. if (!ret) { return false; }
  8891. if (res.get_header_value("Connection") == "close" ||
  8892. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  8893. // TODO this requires a not-entirely-obvious chain of calls to be correct
  8894. // for this to be safe.
  8895. // This is safe to call because handle_request is only called by send_
  8896. // which locks the request mutex during the process. It would be a bug
  8897. // to call it from a different thread since it's a thread-safety issue
  8898. // to do these things to the socket if another thread is using the socket.
  8899. std::lock_guard<std::mutex> guard(socket_mutex_);
  8900. shutdown_ssl(socket_, true);
  8901. shutdown_socket(socket_);
  8902. close_socket(socket_);
  8903. }
  8904. if (300 < res.status && res.status < 400 && follow_location_) {
  8905. req = std::move(req_save);
  8906. ret = redirect(req, res, error);
  8907. }
  8908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8909. if ((res.status == StatusCode::Unauthorized_401 ||
  8910. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  8911. req.authorization_count_ < 5) {
  8912. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  8913. const auto &username =
  8914. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  8915. const auto &password =
  8916. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  8917. if (!username.empty() && !password.empty()) {
  8918. std::map<std::string, std::string> auth;
  8919. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  8920. Request new_req = req;
  8921. new_req.authorization_count_ += 1;
  8922. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  8923. : "Authorization");
  8924. new_req.headers.insert(detail::make_digest_authentication_header(
  8925. req, auth, new_req.authorization_count_, detail::random_string(10),
  8926. username, password, is_proxy));
  8927. Response new_res;
  8928. ret = send(new_req, new_res, error);
  8929. if (ret) { res = std::move(new_res); }
  8930. }
  8931. }
  8932. }
  8933. #endif
  8934. return ret;
  8935. }
  8936. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  8937. if (req.redirect_count_ == 0) {
  8938. error = Error::ExceedRedirectCount;
  8939. output_error_log(error, &req);
  8940. return false;
  8941. }
  8942. auto location = res.get_header_value("location");
  8943. if (location.empty()) { return false; }
  8944. thread_local const std::regex re(
  8945. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  8946. std::smatch m;
  8947. if (!std::regex_match(location, m, re)) { return false; }
  8948. auto scheme = is_ssl() ? "https" : "http";
  8949. auto next_scheme = m[1].str();
  8950. auto next_host = m[2].str();
  8951. if (next_host.empty()) { next_host = m[3].str(); }
  8952. auto port_str = m[4].str();
  8953. auto next_path = m[5].str();
  8954. auto next_query = m[6].str();
  8955. auto next_port = port_;
  8956. if (!port_str.empty()) {
  8957. next_port = std::stoi(port_str);
  8958. } else if (!next_scheme.empty()) {
  8959. next_port = next_scheme == "https" ? 443 : 80;
  8960. }
  8961. if (next_scheme.empty()) { next_scheme = scheme; }
  8962. if (next_host.empty()) { next_host = host_; }
  8963. if (next_path.empty()) { next_path = "/"; }
  8964. auto path = decode_query_component(next_path, true) + next_query;
  8965. // Same host redirect - use current client
  8966. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  8967. return detail::redirect(*this, req, res, path, location, error);
  8968. }
  8969. // Cross-host/scheme redirect - create new client with robust setup
  8970. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  8971. path, location, error);
  8972. }
  8973. // New method for robust redirect client creation
  8974. inline bool ClientImpl::create_redirect_client(
  8975. const std::string &scheme, const std::string &host, int port, Request &req,
  8976. Response &res, const std::string &path, const std::string &location,
  8977. Error &error) {
  8978. // Determine if we need SSL
  8979. auto need_ssl = (scheme == "https");
  8980. // Clean up request headers that are host/client specific
  8981. // Remove headers that should not be carried over to new host
  8982. auto headers_to_remove =
  8983. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  8984. for (const auto &header_name : headers_to_remove) {
  8985. auto it = req.headers.find(header_name);
  8986. while (it != req.headers.end()) {
  8987. it = req.headers.erase(it);
  8988. it = req.headers.find(header_name);
  8989. }
  8990. }
  8991. // Create appropriate client type and handle redirect
  8992. if (need_ssl) {
  8993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8994. // Create SSL client for HTTPS redirect
  8995. SSLClient redirect_client(host, port);
  8996. // Setup basic client configuration first
  8997. setup_redirect_client(redirect_client);
  8998. // SSL-specific configuration for proxy environments
  8999. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9000. // Critical: Disable SSL verification for proxy environments
  9001. redirect_client.enable_server_certificate_verification(false);
  9002. redirect_client.enable_server_hostname_verification(false);
  9003. } else {
  9004. // For direct SSL connections, copy SSL verification settings
  9005. redirect_client.enable_server_certificate_verification(
  9006. server_certificate_verification_);
  9007. redirect_client.enable_server_hostname_verification(
  9008. server_hostname_verification_);
  9009. }
  9010. // Handle CA certificate store and paths if available
  9011. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  9012. redirect_client.set_ca_cert_store(ca_cert_store_);
  9013. }
  9014. if (!ca_cert_file_path_.empty()) {
  9015. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  9016. }
  9017. // Client certificates are set through constructor for SSLClient
  9018. // NOTE: SSLClient constructor already takes client_cert_path and
  9019. // client_key_path so we need to create it properly if client certs are
  9020. // needed
  9021. // Execute the redirect
  9022. return detail::redirect(redirect_client, req, res, path, location, error);
  9023. #else
  9024. // SSL not supported - set appropriate error
  9025. error = Error::SSLConnection;
  9026. output_error_log(error, &req);
  9027. return false;
  9028. #endif
  9029. } else {
  9030. // HTTP redirect
  9031. ClientImpl redirect_client(host, port);
  9032. // Setup client with robust configuration
  9033. setup_redirect_client(redirect_client);
  9034. // Execute the redirect
  9035. return detail::redirect(redirect_client, req, res, path, location, error);
  9036. }
  9037. }
  9038. // New method for robust client setup (based on basic_manual_redirect.cpp
  9039. // logic)
  9040. template <typename ClientType>
  9041. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  9042. // Copy basic settings first
  9043. client.set_connection_timeout(connection_timeout_sec_);
  9044. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  9045. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  9046. client.set_keep_alive(keep_alive_);
  9047. client.set_follow_location(
  9048. true); // Enable redirects to handle multi-step redirects
  9049. client.set_path_encode(path_encode_);
  9050. client.set_compress(compress_);
  9051. client.set_decompress(decompress_);
  9052. // Copy authentication settings BEFORE proxy setup
  9053. if (!basic_auth_username_.empty()) {
  9054. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  9055. }
  9056. if (!bearer_token_auth_token_.empty()) {
  9057. client.set_bearer_token_auth(bearer_token_auth_token_);
  9058. }
  9059. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9060. if (!digest_auth_username_.empty()) {
  9061. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  9062. }
  9063. #endif
  9064. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  9065. // before proxy auth)
  9066. if (!proxy_host_.empty() && proxy_port_ != -1) {
  9067. // First set proxy host and port
  9068. client.set_proxy(proxy_host_, proxy_port_);
  9069. // Then set proxy authentication (order matters!)
  9070. if (!proxy_basic_auth_username_.empty()) {
  9071. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  9072. proxy_basic_auth_password_);
  9073. }
  9074. if (!proxy_bearer_token_auth_token_.empty()) {
  9075. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  9076. }
  9077. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9078. if (!proxy_digest_auth_username_.empty()) {
  9079. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  9080. proxy_digest_auth_password_);
  9081. }
  9082. #endif
  9083. }
  9084. // Copy network and socket settings
  9085. client.set_address_family(address_family_);
  9086. client.set_tcp_nodelay(tcp_nodelay_);
  9087. client.set_ipv6_v6only(ipv6_v6only_);
  9088. if (socket_options_) { client.set_socket_options(socket_options_); }
  9089. if (!interface_.empty()) { client.set_interface(interface_); }
  9090. // Copy logging and headers
  9091. if (logger_) { client.set_logger(logger_); }
  9092. if (error_logger_) { client.set_error_logger(error_logger_); }
  9093. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  9094. // Each new client should generate its own headers based on its target host
  9095. }
  9096. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  9097. const Request &req,
  9098. Error &error) const {
  9099. auto is_shutting_down = []() { return false; };
  9100. if (req.is_chunked_content_provider_) {
  9101. // TODO: Brotli support
  9102. std::unique_ptr<detail::compressor> compressor;
  9103. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9104. if (compress_) {
  9105. compressor = detail::make_unique<detail::gzip_compressor>();
  9106. } else
  9107. #endif
  9108. {
  9109. compressor = detail::make_unique<detail::nocompressor>();
  9110. }
  9111. return detail::write_content_chunked(strm, req.content_provider_,
  9112. is_shutting_down, *compressor, error);
  9113. } else {
  9114. return detail::write_content_with_progress(
  9115. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  9116. req.upload_progress, error);
  9117. }
  9118. }
  9119. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  9120. bool close_connection, Error &error) {
  9121. // Prepare additional headers
  9122. if (close_connection) {
  9123. if (!req.has_header("Connection")) {
  9124. req.set_header("Connection", "close");
  9125. }
  9126. }
  9127. std::string ct_for_defaults;
  9128. if (!req.has_header("Content-Type") && !req.body.empty()) {
  9129. ct_for_defaults = "text/plain";
  9130. }
  9131. prepare_default_headers(req, false, ct_for_defaults);
  9132. if (req.body.empty()) {
  9133. if (req.content_provider_) {
  9134. if (!req.is_chunked_content_provider_) {
  9135. if (!req.has_header("Content-Length")) {
  9136. auto length = std::to_string(req.content_length_);
  9137. req.set_header("Content-Length", length);
  9138. }
  9139. }
  9140. } else {
  9141. if (req.method == "POST" || req.method == "PUT" ||
  9142. req.method == "PATCH") {
  9143. req.set_header("Content-Length", "0");
  9144. }
  9145. }
  9146. }
  9147. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  9148. if (!req.has_header("Authorization")) {
  9149. req.headers.insert(make_basic_authentication_header(
  9150. basic_auth_username_, basic_auth_password_, false));
  9151. }
  9152. }
  9153. if (!proxy_basic_auth_username_.empty() &&
  9154. !proxy_basic_auth_password_.empty()) {
  9155. if (!req.has_header("Proxy-Authorization")) {
  9156. req.headers.insert(make_basic_authentication_header(
  9157. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  9158. }
  9159. }
  9160. if (!bearer_token_auth_token_.empty()) {
  9161. if (!req.has_header("Authorization")) {
  9162. req.headers.insert(make_bearer_token_authentication_header(
  9163. bearer_token_auth_token_, false));
  9164. }
  9165. }
  9166. if (!proxy_bearer_token_auth_token_.empty()) {
  9167. if (!req.has_header("Proxy-Authorization")) {
  9168. req.headers.insert(make_bearer_token_authentication_header(
  9169. proxy_bearer_token_auth_token_, true));
  9170. }
  9171. }
  9172. // Request line and headers
  9173. {
  9174. detail::BufferStream bstrm;
  9175. // Extract path and query from req.path
  9176. std::string path_part, query_part;
  9177. auto query_pos = req.path.find('?');
  9178. if (query_pos != std::string::npos) {
  9179. path_part = req.path.substr(0, query_pos);
  9180. query_part = req.path.substr(query_pos + 1);
  9181. } else {
  9182. path_part = req.path;
  9183. query_part = "";
  9184. }
  9185. // Encode path part. If the original `req.path` already contained a
  9186. // query component, preserve its raw query string (including parameter
  9187. // order) instead of reparsing and reassembling it which may reorder
  9188. // parameters due to container ordering (e.g. `Params` uses
  9189. // `std::multimap`). When there is no query in `req.path`, fall back to
  9190. // building a query from `req.params` so existing callers that pass
  9191. // `Params` continue to work.
  9192. auto path_with_query =
  9193. path_encode_ ? detail::encode_path(path_part) : path_part;
  9194. if (!query_part.empty()) {
  9195. // Normalize the query string (decode then re-encode) while preserving
  9196. // the original parameter order.
  9197. auto normalized = detail::normalize_query_string(query_part);
  9198. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  9199. // Still populate req.params for handlers/users who read them.
  9200. detail::parse_query_text(query_part, req.params);
  9201. } else {
  9202. // No query in path; parse any query_part (empty) and append params
  9203. // from `req.params` when present (preserves prior behavior for
  9204. // callers who provide Params separately).
  9205. detail::parse_query_text(query_part, req.params);
  9206. if (!req.params.empty()) {
  9207. path_with_query = append_query_params(path_with_query, req.params);
  9208. }
  9209. }
  9210. // Write request line and headers
  9211. detail::write_request_line(bstrm, req.method, path_with_query);
  9212. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  9213. error)) {
  9214. output_error_log(error, &req);
  9215. return false;
  9216. }
  9217. // Flush buffer
  9218. auto &data = bstrm.get_buffer();
  9219. if (!detail::write_data(strm, data.data(), data.size())) {
  9220. error = Error::Write;
  9221. output_error_log(error, &req);
  9222. return false;
  9223. }
  9224. }
  9225. // After sending request line and headers, wait briefly for an early server
  9226. // response (e.g. 4xx) and avoid sending a potentially large request body
  9227. // unnecessarily. This workaround is only enabled on Windows because Unix
  9228. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  9229. // buffering can accept large writes even when the peer already responded.
  9230. // Check the stream first (which covers SSL via `is_readable()`), then
  9231. // fall back to select on the socket. Only perform the wait for very large
  9232. // request bodies to avoid interfering with normal small requests and
  9233. // reduce side-effects. Poll briefly (up to 50ms) for an early response.
  9234. #if defined(_WIN32)
  9235. if (req.body.size() > (1u << 20) &&
  9236. req.path.size() >
  9237. CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) { // > 1MB && long URI
  9238. auto start = std::chrono::high_resolution_clock::now();
  9239. const auto max_wait_ms = 50;
  9240. for (;;) {
  9241. auto sock = strm.socket();
  9242. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  9243. // from SSL internals. If the underlying socket is readable, assume an
  9244. // early response may be present.
  9245. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  9246. return false;
  9247. }
  9248. // Fallback to stream-level check for non-socket streams or when the
  9249. // socket isn't reporting readable. Avoid using `is_readable()` for
  9250. // SSL, since `SSL_pending()` may report buffered records that do not
  9251. // indicate a complete application-level response yet.
  9252. if (!is_ssl() && strm.is_readable()) { return false; }
  9253. auto now = std::chrono::high_resolution_clock::now();
  9254. auto elapsed =
  9255. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  9256. .count();
  9257. if (elapsed >= max_wait_ms) { break; }
  9258. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  9259. }
  9260. }
  9261. #endif
  9262. // Body
  9263. if (req.body.empty()) {
  9264. return write_content_with_provider(strm, req, error);
  9265. }
  9266. if (req.upload_progress) {
  9267. auto body_size = req.body.size();
  9268. size_t written = 0;
  9269. auto data = req.body.data();
  9270. while (written < body_size) {
  9271. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  9272. if (!detail::write_data(strm, data + written, to_write)) {
  9273. error = Error::Write;
  9274. output_error_log(error, &req);
  9275. return false;
  9276. }
  9277. written += to_write;
  9278. if (!req.upload_progress(written, body_size)) {
  9279. error = Error::Canceled;
  9280. output_error_log(error, &req);
  9281. return false;
  9282. }
  9283. }
  9284. } else {
  9285. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  9286. error = Error::Write;
  9287. output_error_log(error, &req);
  9288. return false;
  9289. }
  9290. }
  9291. return true;
  9292. }
  9293. inline std::unique_ptr<Response>
  9294. ClientImpl::send_with_content_provider_and_receiver(
  9295. Request &req, const char *body, size_t content_length,
  9296. ContentProvider content_provider,
  9297. ContentProviderWithoutLength content_provider_without_length,
  9298. const std::string &content_type, ContentReceiver content_receiver,
  9299. Error &error) {
  9300. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9301. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9302. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  9303. #endif
  9304. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9305. if (compress_ && !content_provider_without_length) {
  9306. // TODO: Brotli support
  9307. detail::gzip_compressor compressor;
  9308. if (content_provider) {
  9309. auto ok = true;
  9310. size_t offset = 0;
  9311. DataSink data_sink;
  9312. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  9313. if (ok) {
  9314. auto last = offset + data_len == content_length;
  9315. auto ret = compressor.compress(
  9316. data, data_len, last,
  9317. [&](const char *compressed_data, size_t compressed_data_len) {
  9318. req.body.append(compressed_data, compressed_data_len);
  9319. return true;
  9320. });
  9321. if (ret) {
  9322. offset += data_len;
  9323. } else {
  9324. ok = false;
  9325. }
  9326. }
  9327. return ok;
  9328. };
  9329. while (ok && offset < content_length) {
  9330. if (!content_provider(offset, content_length - offset, data_sink)) {
  9331. error = Error::Canceled;
  9332. output_error_log(error, &req);
  9333. return nullptr;
  9334. }
  9335. }
  9336. } else {
  9337. if (!compressor.compress(body, content_length, true,
  9338. [&](const char *data, size_t data_len) {
  9339. req.body.append(data, data_len);
  9340. return true;
  9341. })) {
  9342. error = Error::Compression;
  9343. output_error_log(error, &req);
  9344. return nullptr;
  9345. }
  9346. }
  9347. } else
  9348. #endif
  9349. {
  9350. if (content_provider) {
  9351. req.content_length_ = content_length;
  9352. req.content_provider_ = std::move(content_provider);
  9353. req.is_chunked_content_provider_ = false;
  9354. } else if (content_provider_without_length) {
  9355. req.content_length_ = 0;
  9356. req.content_provider_ = detail::ContentProviderAdapter(
  9357. std::move(content_provider_without_length));
  9358. req.is_chunked_content_provider_ = true;
  9359. req.set_header("Transfer-Encoding", "chunked");
  9360. } else {
  9361. req.body.assign(body, content_length);
  9362. }
  9363. }
  9364. if (content_receiver) {
  9365. req.content_receiver =
  9366. [content_receiver](const char *data, size_t data_length,
  9367. size_t /*offset*/, size_t /*total_length*/) {
  9368. return content_receiver(data, data_length);
  9369. };
  9370. }
  9371. auto res = detail::make_unique<Response>();
  9372. return send(req, *res, error) ? std::move(res) : nullptr;
  9373. }
  9374. inline Result ClientImpl::send_with_content_provider_and_receiver(
  9375. const std::string &method, const std::string &path, const Headers &headers,
  9376. const char *body, size_t content_length, ContentProvider content_provider,
  9377. ContentProviderWithoutLength content_provider_without_length,
  9378. const std::string &content_type, ContentReceiver content_receiver,
  9379. UploadProgress progress) {
  9380. Request req;
  9381. req.method = method;
  9382. req.headers = headers;
  9383. req.path = path;
  9384. req.upload_progress = std::move(progress);
  9385. if (max_timeout_msec_ > 0) {
  9386. req.start_time_ = std::chrono::steady_clock::now();
  9387. }
  9388. auto error = Error::Success;
  9389. auto res = send_with_content_provider_and_receiver(
  9390. req, body, content_length, std::move(content_provider),
  9391. std::move(content_provider_without_length), content_type,
  9392. std::move(content_receiver), error);
  9393. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9394. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  9395. last_openssl_error_};
  9396. #else
  9397. return Result{std::move(res), error, std::move(req.headers)};
  9398. #endif
  9399. }
  9400. inline void ClientImpl::output_log(const Request &req,
  9401. const Response &res) const {
  9402. if (logger_) {
  9403. std::lock_guard<std::mutex> guard(logger_mutex_);
  9404. logger_(req, res);
  9405. }
  9406. }
  9407. inline void ClientImpl::output_error_log(const Error &err,
  9408. const Request *req) const {
  9409. if (error_logger_) {
  9410. std::lock_guard<std::mutex> guard(logger_mutex_);
  9411. error_logger_(err, req);
  9412. }
  9413. }
  9414. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  9415. Response &res, bool close_connection,
  9416. Error &error) {
  9417. // Send request
  9418. auto write_request_success =
  9419. write_request(strm, req, close_connection, error);
  9420. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9421. if (is_ssl()) {
  9422. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  9423. if (!is_proxy_enabled) {
  9424. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  9425. error = Error::SSLPeerCouldBeClosed_;
  9426. output_error_log(error, &req);
  9427. return false;
  9428. }
  9429. }
  9430. }
  9431. #endif
  9432. // Receive response and headers
  9433. if (!read_response_line(strm, req, res) ||
  9434. !detail::read_headers(strm, res.headers)) {
  9435. if (write_request_success) { error = Error::Read; }
  9436. output_error_log(error, &req);
  9437. return false;
  9438. }
  9439. if (!write_request_success) { return false; }
  9440. // Body
  9441. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  9442. req.method != "CONNECT") {
  9443. auto redirect = 300 < res.status && res.status < 400 &&
  9444. res.status != StatusCode::NotModified_304 &&
  9445. follow_location_;
  9446. if (req.response_handler && !redirect) {
  9447. if (!req.response_handler(res)) {
  9448. error = Error::Canceled;
  9449. output_error_log(error, &req);
  9450. return false;
  9451. }
  9452. }
  9453. auto out =
  9454. req.content_receiver
  9455. ? static_cast<ContentReceiverWithProgress>(
  9456. [&](const char *buf, size_t n, size_t off, size_t len) {
  9457. if (redirect) { return true; }
  9458. auto ret = req.content_receiver(buf, n, off, len);
  9459. if (!ret) {
  9460. error = Error::Canceled;
  9461. output_error_log(error, &req);
  9462. }
  9463. return ret;
  9464. })
  9465. : static_cast<ContentReceiverWithProgress>(
  9466. [&](const char *buf, size_t n, size_t /*off*/,
  9467. size_t /*len*/) {
  9468. assert(res.body.size() + n <= res.body.max_size());
  9469. res.body.append(buf, n);
  9470. return true;
  9471. });
  9472. auto progress = [&](size_t current, size_t total) {
  9473. if (!req.download_progress || redirect) { return true; }
  9474. auto ret = req.download_progress(current, total);
  9475. if (!ret) {
  9476. error = Error::Canceled;
  9477. output_error_log(error, &req);
  9478. }
  9479. return ret;
  9480. };
  9481. if (res.has_header("Content-Length")) {
  9482. if (!req.content_receiver) {
  9483. auto len = res.get_header_value_u64("Content-Length");
  9484. if (len > res.body.max_size()) {
  9485. error = Error::Read;
  9486. output_error_log(error, &req);
  9487. return false;
  9488. }
  9489. res.body.reserve(static_cast<size_t>(len));
  9490. }
  9491. }
  9492. if (res.status != StatusCode::NotModified_304) {
  9493. int dummy_status;
  9494. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  9495. dummy_status, std::move(progress),
  9496. std::move(out), decompress_)) {
  9497. if (error != Error::Canceled) { error = Error::Read; }
  9498. output_error_log(error, &req);
  9499. return false;
  9500. }
  9501. }
  9502. }
  9503. // Log
  9504. output_log(req, res);
  9505. return true;
  9506. }
  9507. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  9508. const std::string &boundary, const UploadFormDataItems &items,
  9509. const FormDataProviderItems &provider_items) const {
  9510. size_t cur_item = 0;
  9511. size_t cur_start = 0;
  9512. // cur_item and cur_start are copied to within the std::function and
  9513. // maintain state between successive calls
  9514. return [&, cur_item, cur_start](size_t offset,
  9515. DataSink &sink) mutable -> bool {
  9516. if (!offset && !items.empty()) {
  9517. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  9518. return true;
  9519. } else if (cur_item < provider_items.size()) {
  9520. if (!cur_start) {
  9521. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  9522. provider_items[cur_item], boundary);
  9523. offset += begin.size();
  9524. cur_start = offset;
  9525. sink.os << begin;
  9526. }
  9527. DataSink cur_sink;
  9528. auto has_data = true;
  9529. cur_sink.write = sink.write;
  9530. cur_sink.done = [&]() { has_data = false; };
  9531. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  9532. return false;
  9533. }
  9534. if (!has_data) {
  9535. sink.os << detail::serialize_multipart_formdata_item_end();
  9536. cur_item++;
  9537. cur_start = 0;
  9538. }
  9539. return true;
  9540. } else {
  9541. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  9542. sink.done();
  9543. return true;
  9544. }
  9545. };
  9546. }
  9547. inline bool ClientImpl::process_socket(
  9548. const Socket &socket,
  9549. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9550. std::function<bool(Stream &strm)> callback) {
  9551. return detail::process_client_socket(
  9552. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9553. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  9554. }
  9555. inline bool ClientImpl::is_ssl() const { return false; }
  9556. inline Result ClientImpl::Get(const std::string &path,
  9557. DownloadProgress progress) {
  9558. return Get(path, Headers(), std::move(progress));
  9559. }
  9560. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9561. const Headers &headers,
  9562. DownloadProgress progress) {
  9563. if (params.empty()) { return Get(path, headers); }
  9564. std::string path_with_query = append_query_params(path, params);
  9565. return Get(path_with_query, headers, std::move(progress));
  9566. }
  9567. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9568. DownloadProgress progress) {
  9569. Request req;
  9570. req.method = "GET";
  9571. req.path = path;
  9572. req.headers = headers;
  9573. req.download_progress = std::move(progress);
  9574. if (max_timeout_msec_ > 0) {
  9575. req.start_time_ = std::chrono::steady_clock::now();
  9576. }
  9577. return send_(std::move(req));
  9578. }
  9579. inline Result ClientImpl::Get(const std::string &path,
  9580. ContentReceiver content_receiver,
  9581. DownloadProgress progress) {
  9582. return Get(path, Headers(), nullptr, std::move(content_receiver),
  9583. std::move(progress));
  9584. }
  9585. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9586. ContentReceiver content_receiver,
  9587. DownloadProgress progress) {
  9588. return Get(path, headers, nullptr, std::move(content_receiver),
  9589. std::move(progress));
  9590. }
  9591. inline Result ClientImpl::Get(const std::string &path,
  9592. ResponseHandler response_handler,
  9593. ContentReceiver content_receiver,
  9594. DownloadProgress progress) {
  9595. return Get(path, Headers(), std::move(response_handler),
  9596. std::move(content_receiver), std::move(progress));
  9597. }
  9598. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  9599. ResponseHandler response_handler,
  9600. ContentReceiver content_receiver,
  9601. DownloadProgress progress) {
  9602. Request req;
  9603. req.method = "GET";
  9604. req.path = path;
  9605. req.headers = headers;
  9606. req.response_handler = std::move(response_handler);
  9607. req.content_receiver =
  9608. [content_receiver](const char *data, size_t data_length,
  9609. size_t /*offset*/, size_t /*total_length*/) {
  9610. return content_receiver(data, data_length);
  9611. };
  9612. req.download_progress = std::move(progress);
  9613. if (max_timeout_msec_ > 0) {
  9614. req.start_time_ = std::chrono::steady_clock::now();
  9615. }
  9616. return send_(std::move(req));
  9617. }
  9618. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9619. const Headers &headers,
  9620. ContentReceiver content_receiver,
  9621. DownloadProgress progress) {
  9622. return Get(path, params, headers, nullptr, std::move(content_receiver),
  9623. std::move(progress));
  9624. }
  9625. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  9626. const Headers &headers,
  9627. ResponseHandler response_handler,
  9628. ContentReceiver content_receiver,
  9629. DownloadProgress progress) {
  9630. if (params.empty()) {
  9631. return Get(path, headers, std::move(response_handler),
  9632. std::move(content_receiver), std::move(progress));
  9633. }
  9634. std::string path_with_query = append_query_params(path, params);
  9635. return Get(path_with_query, headers, std::move(response_handler),
  9636. std::move(content_receiver), std::move(progress));
  9637. }
  9638. inline Result ClientImpl::Head(const std::string &path) {
  9639. return Head(path, Headers());
  9640. }
  9641. inline Result ClientImpl::Head(const std::string &path,
  9642. const Headers &headers) {
  9643. Request req;
  9644. req.method = "HEAD";
  9645. req.headers = headers;
  9646. req.path = path;
  9647. if (max_timeout_msec_ > 0) {
  9648. req.start_time_ = std::chrono::steady_clock::now();
  9649. }
  9650. return send_(std::move(req));
  9651. }
  9652. inline Result ClientImpl::Post(const std::string &path) {
  9653. return Post(path, std::string(), std::string());
  9654. }
  9655. inline Result ClientImpl::Post(const std::string &path,
  9656. const Headers &headers) {
  9657. return Post(path, headers, nullptr, 0, std::string());
  9658. }
  9659. inline Result ClientImpl::Post(const std::string &path, const char *body,
  9660. size_t content_length,
  9661. const std::string &content_type,
  9662. UploadProgress progress) {
  9663. return Post(path, Headers(), body, content_length, content_type, progress);
  9664. }
  9665. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  9666. const std::string &content_type,
  9667. UploadProgress progress) {
  9668. return Post(path, Headers(), body, content_type, progress);
  9669. }
  9670. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  9671. return Post(path, Headers(), params);
  9672. }
  9673. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9674. ContentProvider content_provider,
  9675. const std::string &content_type,
  9676. UploadProgress progress) {
  9677. return Post(path, Headers(), content_length, std::move(content_provider),
  9678. content_type, progress);
  9679. }
  9680. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  9681. ContentProvider content_provider,
  9682. const std::string &content_type,
  9683. ContentReceiver content_receiver,
  9684. UploadProgress progress) {
  9685. return Post(path, Headers(), content_length, std::move(content_provider),
  9686. content_type, std::move(content_receiver), progress);
  9687. }
  9688. inline Result ClientImpl::Post(const std::string &path,
  9689. ContentProviderWithoutLength content_provider,
  9690. const std::string &content_type,
  9691. UploadProgress progress) {
  9692. return Post(path, Headers(), std::move(content_provider), content_type,
  9693. progress);
  9694. }
  9695. inline Result ClientImpl::Post(const std::string &path,
  9696. ContentProviderWithoutLength content_provider,
  9697. const std::string &content_type,
  9698. ContentReceiver content_receiver,
  9699. UploadProgress progress) {
  9700. return Post(path, Headers(), std::move(content_provider), content_type,
  9701. std::move(content_receiver), progress);
  9702. }
  9703. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9704. const Params &params) {
  9705. auto query = detail::params_to_query_str(params);
  9706. return Post(path, headers, query, "application/x-www-form-urlencoded");
  9707. }
  9708. inline Result ClientImpl::Post(const std::string &path,
  9709. const UploadFormDataItems &items,
  9710. UploadProgress progress) {
  9711. return Post(path, Headers(), items, progress);
  9712. }
  9713. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9714. const UploadFormDataItems &items,
  9715. UploadProgress progress) {
  9716. const auto &boundary = detail::make_multipart_data_boundary();
  9717. const auto &content_type =
  9718. detail::serialize_multipart_formdata_get_content_type(boundary);
  9719. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9720. return Post(path, headers, body, content_type, progress);
  9721. }
  9722. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9723. const UploadFormDataItems &items,
  9724. const std::string &boundary,
  9725. UploadProgress progress) {
  9726. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  9727. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  9728. }
  9729. const auto &content_type =
  9730. detail::serialize_multipart_formdata_get_content_type(boundary);
  9731. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9732. return Post(path, headers, body, content_type, progress);
  9733. }
  9734. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9735. const char *body, size_t content_length,
  9736. const std::string &content_type,
  9737. UploadProgress progress) {
  9738. return send_with_content_provider_and_receiver(
  9739. "POST", path, headers, body, content_length, nullptr, nullptr,
  9740. content_type, nullptr, progress);
  9741. }
  9742. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9743. const std::string &body,
  9744. const std::string &content_type,
  9745. UploadProgress progress) {
  9746. return send_with_content_provider_and_receiver(
  9747. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  9748. content_type, nullptr, progress);
  9749. }
  9750. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9751. size_t content_length,
  9752. ContentProvider content_provider,
  9753. const std::string &content_type,
  9754. UploadProgress progress) {
  9755. return send_with_content_provider_and_receiver(
  9756. "POST", path, headers, nullptr, content_length,
  9757. std::move(content_provider), nullptr, content_type, nullptr, progress);
  9758. }
  9759. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9760. size_t content_length,
  9761. ContentProvider content_provider,
  9762. const std::string &content_type,
  9763. ContentReceiver content_receiver,
  9764. DownloadProgress progress) {
  9765. return send_with_content_provider_and_receiver(
  9766. "POST", path, headers, nullptr, content_length,
  9767. std::move(content_provider), nullptr, content_type,
  9768. std::move(content_receiver), std::move(progress));
  9769. }
  9770. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9771. ContentProviderWithoutLength content_provider,
  9772. const std::string &content_type,
  9773. UploadProgress progress) {
  9774. return send_with_content_provider_and_receiver(
  9775. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9776. content_type, nullptr, progress);
  9777. }
  9778. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9779. ContentProviderWithoutLength content_provider,
  9780. const std::string &content_type,
  9781. ContentReceiver content_receiver,
  9782. DownloadProgress progress) {
  9783. return send_with_content_provider_and_receiver(
  9784. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9785. content_type, std::move(content_receiver), std::move(progress));
  9786. }
  9787. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9788. const UploadFormDataItems &items,
  9789. const FormDataProviderItems &provider_items,
  9790. UploadProgress progress) {
  9791. const auto &boundary = detail::make_multipart_data_boundary();
  9792. const auto &content_type =
  9793. detail::serialize_multipart_formdata_get_content_type(boundary);
  9794. return send_with_content_provider_and_receiver(
  9795. "POST", path, headers, nullptr, 0, nullptr,
  9796. get_multipart_content_provider(boundary, items, provider_items),
  9797. content_type, nullptr, progress);
  9798. }
  9799. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  9800. const std::string &body,
  9801. const std::string &content_type,
  9802. ContentReceiver content_receiver,
  9803. DownloadProgress progress) {
  9804. Request req;
  9805. req.method = "POST";
  9806. req.path = path;
  9807. req.headers = headers;
  9808. req.body = body;
  9809. req.content_receiver =
  9810. [content_receiver](const char *data, size_t data_length,
  9811. size_t /*offset*/, size_t /*total_length*/) {
  9812. return content_receiver(data, data_length);
  9813. };
  9814. req.download_progress = std::move(progress);
  9815. if (max_timeout_msec_ > 0) {
  9816. req.start_time_ = std::chrono::steady_clock::now();
  9817. }
  9818. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9819. return send_(std::move(req));
  9820. }
  9821. inline Result ClientImpl::Put(const std::string &path) {
  9822. return Put(path, std::string(), std::string());
  9823. }
  9824. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  9825. return Put(path, headers, nullptr, 0, std::string());
  9826. }
  9827. inline Result ClientImpl::Put(const std::string &path, const char *body,
  9828. size_t content_length,
  9829. const std::string &content_type,
  9830. UploadProgress progress) {
  9831. return Put(path, Headers(), body, content_length, content_type, progress);
  9832. }
  9833. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  9834. const std::string &content_type,
  9835. UploadProgress progress) {
  9836. return Put(path, Headers(), body, content_type, progress);
  9837. }
  9838. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  9839. return Put(path, Headers(), params);
  9840. }
  9841. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  9842. ContentProvider content_provider,
  9843. const std::string &content_type,
  9844. UploadProgress progress) {
  9845. return Put(path, Headers(), content_length, std::move(content_provider),
  9846. content_type, progress);
  9847. }
  9848. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  9849. ContentProvider content_provider,
  9850. const std::string &content_type,
  9851. ContentReceiver content_receiver,
  9852. UploadProgress progress) {
  9853. return Put(path, Headers(), content_length, std::move(content_provider),
  9854. content_type, std::move(content_receiver), progress);
  9855. }
  9856. inline Result ClientImpl::Put(const std::string &path,
  9857. ContentProviderWithoutLength content_provider,
  9858. const std::string &content_type,
  9859. UploadProgress progress) {
  9860. return Put(path, Headers(), std::move(content_provider), content_type,
  9861. progress);
  9862. }
  9863. inline Result ClientImpl::Put(const std::string &path,
  9864. ContentProviderWithoutLength content_provider,
  9865. const std::string &content_type,
  9866. ContentReceiver content_receiver,
  9867. UploadProgress progress) {
  9868. return Put(path, Headers(), std::move(content_provider), content_type,
  9869. std::move(content_receiver), progress);
  9870. }
  9871. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9872. const Params &params) {
  9873. auto query = detail::params_to_query_str(params);
  9874. return Put(path, headers, query, "application/x-www-form-urlencoded");
  9875. }
  9876. inline Result ClientImpl::Put(const std::string &path,
  9877. const UploadFormDataItems &items,
  9878. UploadProgress progress) {
  9879. return Put(path, Headers(), items, progress);
  9880. }
  9881. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9882. const UploadFormDataItems &items,
  9883. UploadProgress progress) {
  9884. const auto &boundary = detail::make_multipart_data_boundary();
  9885. const auto &content_type =
  9886. detail::serialize_multipart_formdata_get_content_type(boundary);
  9887. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9888. return Put(path, headers, body, content_type, progress);
  9889. }
  9890. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9891. const UploadFormDataItems &items,
  9892. const std::string &boundary,
  9893. UploadProgress progress) {
  9894. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  9895. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  9896. }
  9897. const auto &content_type =
  9898. detail::serialize_multipart_formdata_get_content_type(boundary);
  9899. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  9900. return Put(path, headers, body, content_type, progress);
  9901. }
  9902. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9903. const char *body, size_t content_length,
  9904. const std::string &content_type,
  9905. UploadProgress progress) {
  9906. return send_with_content_provider_and_receiver(
  9907. "PUT", path, headers, body, content_length, nullptr, nullptr,
  9908. content_type, nullptr, progress);
  9909. }
  9910. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9911. const std::string &body,
  9912. const std::string &content_type,
  9913. UploadProgress progress) {
  9914. return send_with_content_provider_and_receiver(
  9915. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  9916. content_type, nullptr, progress);
  9917. }
  9918. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9919. size_t content_length,
  9920. ContentProvider content_provider,
  9921. const std::string &content_type,
  9922. UploadProgress progress) {
  9923. return send_with_content_provider_and_receiver(
  9924. "PUT", path, headers, nullptr, content_length,
  9925. std::move(content_provider), nullptr, content_type, nullptr, progress);
  9926. }
  9927. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9928. size_t content_length,
  9929. ContentProvider content_provider,
  9930. const std::string &content_type,
  9931. ContentReceiver content_receiver,
  9932. UploadProgress progress) {
  9933. return send_with_content_provider_and_receiver(
  9934. "PUT", path, headers, nullptr, content_length,
  9935. std::move(content_provider), nullptr, content_type,
  9936. std::move(content_receiver), progress);
  9937. }
  9938. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9939. ContentProviderWithoutLength content_provider,
  9940. const std::string &content_type,
  9941. UploadProgress progress) {
  9942. return send_with_content_provider_and_receiver(
  9943. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9944. content_type, nullptr, progress);
  9945. }
  9946. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9947. ContentProviderWithoutLength content_provider,
  9948. const std::string &content_type,
  9949. ContentReceiver content_receiver,
  9950. UploadProgress progress) {
  9951. return send_with_content_provider_and_receiver(
  9952. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  9953. content_type, std::move(content_receiver), progress);
  9954. }
  9955. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9956. const UploadFormDataItems &items,
  9957. const FormDataProviderItems &provider_items,
  9958. UploadProgress progress) {
  9959. const auto &boundary = detail::make_multipart_data_boundary();
  9960. const auto &content_type =
  9961. detail::serialize_multipart_formdata_get_content_type(boundary);
  9962. return send_with_content_provider_and_receiver(
  9963. "PUT", path, headers, nullptr, 0, nullptr,
  9964. get_multipart_content_provider(boundary, items, provider_items),
  9965. content_type, nullptr, progress);
  9966. }
  9967. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  9968. const std::string &body,
  9969. const std::string &content_type,
  9970. ContentReceiver content_receiver,
  9971. DownloadProgress progress) {
  9972. Request req;
  9973. req.method = "PUT";
  9974. req.path = path;
  9975. req.headers = headers;
  9976. req.body = body;
  9977. req.content_receiver =
  9978. [content_receiver](const char *data, size_t data_length,
  9979. size_t /*offset*/, size_t /*total_length*/) {
  9980. return content_receiver(data, data_length);
  9981. };
  9982. req.download_progress = std::move(progress);
  9983. if (max_timeout_msec_ > 0) {
  9984. req.start_time_ = std::chrono::steady_clock::now();
  9985. }
  9986. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  9987. return send_(std::move(req));
  9988. }
  9989. inline Result ClientImpl::Patch(const std::string &path) {
  9990. return Patch(path, std::string(), std::string());
  9991. }
  9992. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  9993. UploadProgress progress) {
  9994. return Patch(path, headers, nullptr, 0, std::string(), progress);
  9995. }
  9996. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  9997. size_t content_length,
  9998. const std::string &content_type,
  9999. UploadProgress progress) {
  10000. return Patch(path, Headers(), body, content_length, content_type, progress);
  10001. }
  10002. inline Result ClientImpl::Patch(const std::string &path,
  10003. const std::string &body,
  10004. const std::string &content_type,
  10005. UploadProgress progress) {
  10006. return Patch(path, Headers(), body, content_type, progress);
  10007. }
  10008. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  10009. return Patch(path, Headers(), params);
  10010. }
  10011. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10012. ContentProvider content_provider,
  10013. const std::string &content_type,
  10014. UploadProgress progress) {
  10015. return Patch(path, Headers(), content_length, std::move(content_provider),
  10016. content_type, progress);
  10017. }
  10018. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  10019. ContentProvider content_provider,
  10020. const std::string &content_type,
  10021. ContentReceiver content_receiver,
  10022. UploadProgress progress) {
  10023. return Patch(path, Headers(), content_length, std::move(content_provider),
  10024. content_type, std::move(content_receiver), progress);
  10025. }
  10026. inline Result ClientImpl::Patch(const std::string &path,
  10027. ContentProviderWithoutLength content_provider,
  10028. const std::string &content_type,
  10029. UploadProgress progress) {
  10030. return Patch(path, Headers(), std::move(content_provider), content_type,
  10031. progress);
  10032. }
  10033. inline Result ClientImpl::Patch(const std::string &path,
  10034. ContentProviderWithoutLength content_provider,
  10035. const std::string &content_type,
  10036. ContentReceiver content_receiver,
  10037. UploadProgress progress) {
  10038. return Patch(path, Headers(), std::move(content_provider), content_type,
  10039. std::move(content_receiver), progress);
  10040. }
  10041. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10042. const Params &params) {
  10043. auto query = detail::params_to_query_str(params);
  10044. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  10045. }
  10046. inline Result ClientImpl::Patch(const std::string &path,
  10047. const UploadFormDataItems &items,
  10048. UploadProgress progress) {
  10049. return Patch(path, Headers(), items, progress);
  10050. }
  10051. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10052. const UploadFormDataItems &items,
  10053. UploadProgress progress) {
  10054. const auto &boundary = detail::make_multipart_data_boundary();
  10055. const auto &content_type =
  10056. detail::serialize_multipart_formdata_get_content_type(boundary);
  10057. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10058. return Patch(path, headers, body, content_type, progress);
  10059. }
  10060. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10061. const UploadFormDataItems &items,
  10062. const std::string &boundary,
  10063. UploadProgress progress) {
  10064. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  10065. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  10066. }
  10067. const auto &content_type =
  10068. detail::serialize_multipart_formdata_get_content_type(boundary);
  10069. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  10070. return Patch(path, headers, body, content_type, progress);
  10071. }
  10072. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10073. const char *body, size_t content_length,
  10074. const std::string &content_type,
  10075. UploadProgress progress) {
  10076. return send_with_content_provider_and_receiver(
  10077. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  10078. content_type, nullptr, progress);
  10079. }
  10080. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10081. const std::string &body,
  10082. const std::string &content_type,
  10083. UploadProgress progress) {
  10084. return send_with_content_provider_and_receiver(
  10085. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  10086. content_type, nullptr, progress);
  10087. }
  10088. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10089. size_t content_length,
  10090. ContentProvider content_provider,
  10091. const std::string &content_type,
  10092. UploadProgress progress) {
  10093. return send_with_content_provider_and_receiver(
  10094. "PATCH", path, headers, nullptr, content_length,
  10095. std::move(content_provider), nullptr, content_type, nullptr, progress);
  10096. }
  10097. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10098. size_t content_length,
  10099. ContentProvider content_provider,
  10100. const std::string &content_type,
  10101. ContentReceiver content_receiver,
  10102. UploadProgress progress) {
  10103. return send_with_content_provider_and_receiver(
  10104. "PATCH", path, headers, nullptr, content_length,
  10105. std::move(content_provider), nullptr, content_type,
  10106. std::move(content_receiver), progress);
  10107. }
  10108. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10109. ContentProviderWithoutLength content_provider,
  10110. const std::string &content_type,
  10111. UploadProgress progress) {
  10112. return send_with_content_provider_and_receiver(
  10113. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10114. content_type, nullptr, progress);
  10115. }
  10116. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10117. ContentProviderWithoutLength content_provider,
  10118. const std::string &content_type,
  10119. ContentReceiver content_receiver,
  10120. UploadProgress progress) {
  10121. return send_with_content_provider_and_receiver(
  10122. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  10123. content_type, std::move(content_receiver), progress);
  10124. }
  10125. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10126. const UploadFormDataItems &items,
  10127. const FormDataProviderItems &provider_items,
  10128. UploadProgress progress) {
  10129. const auto &boundary = detail::make_multipart_data_boundary();
  10130. const auto &content_type =
  10131. detail::serialize_multipart_formdata_get_content_type(boundary);
  10132. return send_with_content_provider_and_receiver(
  10133. "PATCH", path, headers, nullptr, 0, nullptr,
  10134. get_multipart_content_provider(boundary, items, provider_items),
  10135. content_type, nullptr, progress);
  10136. }
  10137. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  10138. const std::string &body,
  10139. const std::string &content_type,
  10140. ContentReceiver content_receiver,
  10141. DownloadProgress progress) {
  10142. Request req;
  10143. req.method = "PATCH";
  10144. req.path = path;
  10145. req.headers = headers;
  10146. req.body = body;
  10147. req.content_receiver =
  10148. [content_receiver](const char *data, size_t data_length,
  10149. size_t /*offset*/, size_t /*total_length*/) {
  10150. return content_receiver(data, data_length);
  10151. };
  10152. req.download_progress = std::move(progress);
  10153. if (max_timeout_msec_ > 0) {
  10154. req.start_time_ = std::chrono::steady_clock::now();
  10155. }
  10156. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10157. return send_(std::move(req));
  10158. }
  10159. inline Result ClientImpl::Delete(const std::string &path,
  10160. DownloadProgress progress) {
  10161. return Delete(path, Headers(), std::string(), std::string(), progress);
  10162. }
  10163. inline Result ClientImpl::Delete(const std::string &path,
  10164. const Headers &headers,
  10165. DownloadProgress progress) {
  10166. return Delete(path, headers, std::string(), std::string(), progress);
  10167. }
  10168. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  10169. size_t content_length,
  10170. const std::string &content_type,
  10171. DownloadProgress progress) {
  10172. return Delete(path, Headers(), body, content_length, content_type, progress);
  10173. }
  10174. inline Result ClientImpl::Delete(const std::string &path,
  10175. const std::string &body,
  10176. const std::string &content_type,
  10177. DownloadProgress progress) {
  10178. return Delete(path, Headers(), body.data(), body.size(), content_type,
  10179. progress);
  10180. }
  10181. inline Result ClientImpl::Delete(const std::string &path,
  10182. const Headers &headers,
  10183. const std::string &body,
  10184. const std::string &content_type,
  10185. DownloadProgress progress) {
  10186. return Delete(path, headers, body.data(), body.size(), content_type,
  10187. progress);
  10188. }
  10189. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  10190. DownloadProgress progress) {
  10191. return Delete(path, Headers(), params, progress);
  10192. }
  10193. inline Result ClientImpl::Delete(const std::string &path,
  10194. const Headers &headers, const Params &params,
  10195. DownloadProgress progress) {
  10196. auto query = detail::params_to_query_str(params);
  10197. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  10198. progress);
  10199. }
  10200. inline Result ClientImpl::Delete(const std::string &path,
  10201. const Headers &headers, const char *body,
  10202. size_t content_length,
  10203. const std::string &content_type,
  10204. DownloadProgress progress) {
  10205. Request req;
  10206. req.method = "DELETE";
  10207. req.headers = headers;
  10208. req.path = path;
  10209. req.download_progress = std::move(progress);
  10210. if (max_timeout_msec_ > 0) {
  10211. req.start_time_ = std::chrono::steady_clock::now();
  10212. }
  10213. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  10214. req.body.assign(body, content_length);
  10215. return send_(std::move(req));
  10216. }
  10217. inline Result ClientImpl::Options(const std::string &path) {
  10218. return Options(path, Headers());
  10219. }
  10220. inline Result ClientImpl::Options(const std::string &path,
  10221. const Headers &headers) {
  10222. Request req;
  10223. req.method = "OPTIONS";
  10224. req.headers = headers;
  10225. req.path = path;
  10226. if (max_timeout_msec_ > 0) {
  10227. req.start_time_ = std::chrono::steady_clock::now();
  10228. }
  10229. return send_(std::move(req));
  10230. }
  10231. inline void ClientImpl::stop() {
  10232. std::lock_guard<std::mutex> guard(socket_mutex_);
  10233. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  10234. // do is to shutdown_socket, so that threads using this socket suddenly
  10235. // discover they can't read/write any more and error out. Everything else
  10236. // (closing the socket, shutting ssl down) is unsafe because these actions
  10237. // are not thread-safe.
  10238. if (socket_requests_in_flight_ > 0) {
  10239. shutdown_socket(socket_);
  10240. // Aside from that, we set a flag for the socket to be closed when we're
  10241. // done.
  10242. socket_should_be_closed_when_request_is_done_ = true;
  10243. return;
  10244. }
  10245. // Otherwise, still holding the mutex, we can shut everything down ourselves
  10246. shutdown_ssl(socket_, true);
  10247. shutdown_socket(socket_);
  10248. close_socket(socket_);
  10249. }
  10250. inline std::string ClientImpl::host() const { return host_; }
  10251. inline int ClientImpl::port() const { return port_; }
  10252. inline size_t ClientImpl::is_socket_open() const {
  10253. std::lock_guard<std::mutex> guard(socket_mutex_);
  10254. return socket_.is_open();
  10255. }
  10256. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  10257. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  10258. connection_timeout_sec_ = sec;
  10259. connection_timeout_usec_ = usec;
  10260. }
  10261. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  10262. read_timeout_sec_ = sec;
  10263. read_timeout_usec_ = usec;
  10264. }
  10265. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  10266. write_timeout_sec_ = sec;
  10267. write_timeout_usec_ = usec;
  10268. }
  10269. inline void ClientImpl::set_max_timeout(time_t msec) {
  10270. max_timeout_msec_ = msec;
  10271. }
  10272. inline void ClientImpl::set_basic_auth(const std::string &username,
  10273. const std::string &password) {
  10274. basic_auth_username_ = username;
  10275. basic_auth_password_ = password;
  10276. }
  10277. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  10278. bearer_token_auth_token_ = token;
  10279. }
  10280. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10281. inline void ClientImpl::set_digest_auth(const std::string &username,
  10282. const std::string &password) {
  10283. digest_auth_username_ = username;
  10284. digest_auth_password_ = password;
  10285. }
  10286. #endif
  10287. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  10288. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  10289. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  10290. inline void
  10291. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  10292. addr_map_ = std::move(addr_map);
  10293. }
  10294. inline void ClientImpl::set_default_headers(Headers headers) {
  10295. default_headers_ = std::move(headers);
  10296. }
  10297. inline void ClientImpl::set_header_writer(
  10298. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  10299. header_writer_ = writer;
  10300. }
  10301. inline void ClientImpl::set_address_family(int family) {
  10302. address_family_ = family;
  10303. }
  10304. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  10305. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  10306. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  10307. socket_options_ = std::move(socket_options);
  10308. }
  10309. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  10310. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  10311. inline void ClientImpl::set_interface(const std::string &intf) {
  10312. interface_ = intf;
  10313. }
  10314. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  10315. proxy_host_ = host;
  10316. proxy_port_ = port;
  10317. }
  10318. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  10319. const std::string &password) {
  10320. proxy_basic_auth_username_ = username;
  10321. proxy_basic_auth_password_ = password;
  10322. }
  10323. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  10324. proxy_bearer_token_auth_token_ = token;
  10325. }
  10326. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10327. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  10328. const std::string &password) {
  10329. proxy_digest_auth_username_ = username;
  10330. proxy_digest_auth_password_ = password;
  10331. }
  10332. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  10333. const std::string &ca_cert_dir_path) {
  10334. ca_cert_file_path_ = ca_cert_file_path;
  10335. ca_cert_dir_path_ = ca_cert_dir_path;
  10336. }
  10337. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10338. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  10339. ca_cert_store_ = ca_cert_store;
  10340. }
  10341. }
  10342. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  10343. std::size_t size) const {
  10344. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  10345. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  10346. if (!mem) { return nullptr; }
  10347. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  10348. if (!inf) { return nullptr; }
  10349. auto cts = X509_STORE_new();
  10350. if (cts) {
  10351. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  10352. auto itmp = sk_X509_INFO_value(inf, i);
  10353. if (!itmp) { continue; }
  10354. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  10355. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  10356. }
  10357. }
  10358. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  10359. return cts;
  10360. }
  10361. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  10362. server_certificate_verification_ = enabled;
  10363. }
  10364. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  10365. server_hostname_verification_ = enabled;
  10366. }
  10367. inline void ClientImpl::set_server_certificate_verifier(
  10368. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10369. server_certificate_verifier_ = verifier;
  10370. }
  10371. #endif
  10372. inline void ClientImpl::set_logger(Logger logger) {
  10373. logger_ = std::move(logger);
  10374. }
  10375. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  10376. error_logger_ = std::move(error_logger);
  10377. }
  10378. /*
  10379. * SSL Implementation
  10380. */
  10381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10382. namespace detail {
  10383. inline bool is_ip_address(const std::string &host) {
  10384. struct in_addr addr4;
  10385. struct in6_addr addr6;
  10386. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  10387. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  10388. }
  10389. template <typename U, typename V>
  10390. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  10391. U SSL_connect_or_accept, V setup) {
  10392. SSL *ssl = nullptr;
  10393. {
  10394. std::lock_guard<std::mutex> guard(ctx_mutex);
  10395. ssl = SSL_new(ctx);
  10396. }
  10397. if (ssl) {
  10398. set_nonblocking(sock, true);
  10399. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  10400. BIO_set_nbio(bio, 1);
  10401. SSL_set_bio(ssl, bio, bio);
  10402. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  10403. SSL_shutdown(ssl);
  10404. {
  10405. std::lock_guard<std::mutex> guard(ctx_mutex);
  10406. SSL_free(ssl);
  10407. }
  10408. set_nonblocking(sock, false);
  10409. return nullptr;
  10410. }
  10411. BIO_set_nbio(bio, 0);
  10412. set_nonblocking(sock, false);
  10413. }
  10414. return ssl;
  10415. }
  10416. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  10417. bool shutdown_gracefully) {
  10418. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  10419. // the remote has closed the network connection
  10420. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  10421. // best-efforts.
  10422. if (shutdown_gracefully) {
  10423. (void)(sock);
  10424. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  10425. // sent) and 1 on subsequent call (indicating close_notify alert received)
  10426. if (SSL_shutdown(ssl) == 0) {
  10427. // Expected to return 1, but even if it doesn't, we free ssl
  10428. SSL_shutdown(ssl);
  10429. }
  10430. }
  10431. std::lock_guard<std::mutex> guard(ctx_mutex);
  10432. SSL_free(ssl);
  10433. }
  10434. template <typename U>
  10435. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  10436. U ssl_connect_or_accept,
  10437. time_t timeout_sec, time_t timeout_usec,
  10438. int *ssl_error) {
  10439. auto res = 0;
  10440. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  10441. auto err = SSL_get_error(ssl, res);
  10442. switch (err) {
  10443. case SSL_ERROR_WANT_READ:
  10444. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  10445. break;
  10446. case SSL_ERROR_WANT_WRITE:
  10447. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  10448. break;
  10449. default: break;
  10450. }
  10451. if (ssl_error) { *ssl_error = err; }
  10452. return false;
  10453. }
  10454. return true;
  10455. }
  10456. template <typename T>
  10457. inline bool process_server_socket_ssl(
  10458. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  10459. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  10460. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  10461. time_t write_timeout_usec, T callback) {
  10462. return process_server_socket_core(
  10463. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  10464. [&](bool close_connection, bool &connection_closed) {
  10465. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  10466. write_timeout_sec, write_timeout_usec);
  10467. return callback(strm, close_connection, connection_closed);
  10468. });
  10469. }
  10470. template <typename T>
  10471. inline bool process_client_socket_ssl(
  10472. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  10473. time_t write_timeout_sec, time_t write_timeout_usec,
  10474. time_t max_timeout_msec,
  10475. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  10476. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  10477. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  10478. start_time);
  10479. return callback(strm);
  10480. }
  10481. // SSL socket stream implementation
  10482. inline SSLSocketStream::SSLSocketStream(
  10483. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  10484. time_t write_timeout_sec, time_t write_timeout_usec,
  10485. time_t max_timeout_msec,
  10486. std::chrono::time_point<std::chrono::steady_clock> start_time)
  10487. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  10488. read_timeout_usec_(read_timeout_usec),
  10489. write_timeout_sec_(write_timeout_sec),
  10490. write_timeout_usec_(write_timeout_usec),
  10491. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  10492. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  10493. }
  10494. inline SSLSocketStream::~SSLSocketStream() = default;
  10495. inline bool SSLSocketStream::is_readable() const {
  10496. return SSL_pending(ssl_) > 0;
  10497. }
  10498. inline bool SSLSocketStream::wait_readable() const {
  10499. if (max_timeout_msec_ <= 0) {
  10500. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  10501. }
  10502. time_t read_timeout_sec;
  10503. time_t read_timeout_usec;
  10504. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  10505. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  10506. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  10507. }
  10508. inline bool SSLSocketStream::wait_writable() const {
  10509. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  10510. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  10511. }
  10512. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  10513. if (SSL_pending(ssl_) > 0) {
  10514. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10515. if (ret == 0) { error_ = Error::ConnectionClosed; }
  10516. return ret;
  10517. } else if (wait_readable()) {
  10518. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10519. if (ret < 0) {
  10520. auto err = SSL_get_error(ssl_, ret);
  10521. auto n = 1000;
  10522. #ifdef _WIN32
  10523. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  10524. (err == SSL_ERROR_SYSCALL &&
  10525. WSAGetLastError() == WSAETIMEDOUT))) {
  10526. #else
  10527. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  10528. #endif
  10529. if (SSL_pending(ssl_) > 0) {
  10530. return SSL_read(ssl_, ptr, static_cast<int>(size));
  10531. } else if (wait_readable()) {
  10532. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10533. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  10534. if (ret >= 0) { return ret; }
  10535. err = SSL_get_error(ssl_, ret);
  10536. } else {
  10537. break;
  10538. }
  10539. }
  10540. assert(ret < 0);
  10541. } else if (ret == 0) {
  10542. error_ = Error::ConnectionClosed;
  10543. }
  10544. return ret;
  10545. } else {
  10546. error_ = Error::Timeout;
  10547. return -1;
  10548. }
  10549. }
  10550. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  10551. if (wait_writable()) {
  10552. auto handle_size = static_cast<int>(
  10553. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  10554. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  10555. if (ret < 0) {
  10556. auto err = SSL_get_error(ssl_, ret);
  10557. auto n = 1000;
  10558. #ifdef _WIN32
  10559. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  10560. (err == SSL_ERROR_SYSCALL &&
  10561. WSAGetLastError() == WSAETIMEDOUT))) {
  10562. #else
  10563. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  10564. #endif
  10565. if (wait_writable()) {
  10566. std::this_thread::sleep_for(std::chrono::microseconds{10});
  10567. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  10568. if (ret >= 0) { return ret; }
  10569. err = SSL_get_error(ssl_, ret);
  10570. } else {
  10571. break;
  10572. }
  10573. }
  10574. assert(ret < 0);
  10575. }
  10576. return ret;
  10577. }
  10578. return -1;
  10579. }
  10580. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  10581. int &port) const {
  10582. detail::get_remote_ip_and_port(sock_, ip, port);
  10583. }
  10584. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  10585. int &port) const {
  10586. detail::get_local_ip_and_port(sock_, ip, port);
  10587. }
  10588. inline socket_t SSLSocketStream::socket() const { return sock_; }
  10589. inline time_t SSLSocketStream::duration() const {
  10590. return std::chrono::duration_cast<std::chrono::milliseconds>(
  10591. std::chrono::steady_clock::now() - start_time_)
  10592. .count();
  10593. }
  10594. } // namespace detail
  10595. // SSL HTTP server implementation
  10596. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  10597. const char *client_ca_cert_file_path,
  10598. const char *client_ca_cert_dir_path,
  10599. const char *private_key_password) {
  10600. ctx_ = SSL_CTX_new(TLS_server_method());
  10601. if (ctx_) {
  10602. SSL_CTX_set_options(ctx_,
  10603. SSL_OP_NO_COMPRESSION |
  10604. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10605. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10606. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  10607. SSL_CTX_set_default_passwd_cb_userdata(
  10608. ctx_,
  10609. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  10610. }
  10611. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  10612. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  10613. 1 ||
  10614. SSL_CTX_check_private_key(ctx_) != 1) {
  10615. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10616. SSL_CTX_free(ctx_);
  10617. ctx_ = nullptr;
  10618. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  10619. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  10620. client_ca_cert_dir_path);
  10621. // Set client CA list to be sent to clients during TLS handshake
  10622. if (client_ca_cert_file_path) {
  10623. auto ca_list = SSL_load_client_CA_file(client_ca_cert_file_path);
  10624. if (ca_list != nullptr) {
  10625. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  10626. } else {
  10627. // Failed to load client CA list, but we continue since
  10628. // SSL_CTX_load_verify_locations already succeeded and
  10629. // certificate verification will still work
  10630. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10631. }
  10632. }
  10633. SSL_CTX_set_verify(
  10634. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  10635. }
  10636. }
  10637. }
  10638. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  10639. X509_STORE *client_ca_cert_store) {
  10640. ctx_ = SSL_CTX_new(TLS_server_method());
  10641. if (ctx_) {
  10642. SSL_CTX_set_options(ctx_,
  10643. SSL_OP_NO_COMPRESSION |
  10644. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  10645. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10646. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  10647. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  10648. SSL_CTX_free(ctx_);
  10649. ctx_ = nullptr;
  10650. } else if (client_ca_cert_store) {
  10651. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  10652. // Extract CA names from the store and set them as the client CA list
  10653. auto ca_list = extract_ca_names_from_x509_store(client_ca_cert_store);
  10654. if (ca_list) {
  10655. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  10656. } else {
  10657. // Failed to extract CA names, record the error
  10658. last_ssl_error_ = static_cast<int>(ERR_get_error());
  10659. }
  10660. SSL_CTX_set_verify(
  10661. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  10662. }
  10663. }
  10664. }
  10665. inline SSLServer::SSLServer(
  10666. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  10667. ctx_ = SSL_CTX_new(TLS_method());
  10668. if (ctx_) {
  10669. if (!setup_ssl_ctx_callback(*ctx_)) {
  10670. SSL_CTX_free(ctx_);
  10671. ctx_ = nullptr;
  10672. }
  10673. }
  10674. }
  10675. inline SSLServer::~SSLServer() {
  10676. if (ctx_) { SSL_CTX_free(ctx_); }
  10677. }
  10678. inline bool SSLServer::is_valid() const { return ctx_; }
  10679. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  10680. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  10681. X509_STORE *client_ca_cert_store) {
  10682. std::lock_guard<std::mutex> guard(ctx_mutex_);
  10683. SSL_CTX_use_certificate(ctx_, cert);
  10684. SSL_CTX_use_PrivateKey(ctx_, private_key);
  10685. if (client_ca_cert_store != nullptr) {
  10686. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  10687. }
  10688. }
  10689. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  10690. auto ssl = detail::ssl_new(
  10691. sock, ctx_, ctx_mutex_,
  10692. [&](SSL *ssl2) {
  10693. return detail::ssl_connect_or_accept_nonblocking(
  10694. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  10695. &last_ssl_error_);
  10696. },
  10697. [](SSL * /*ssl2*/) { return true; });
  10698. auto ret = false;
  10699. if (ssl) {
  10700. std::string remote_addr;
  10701. int remote_port = 0;
  10702. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10703. std::string local_addr;
  10704. int local_port = 0;
  10705. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10706. ret = detail::process_server_socket_ssl(
  10707. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10708. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10709. write_timeout_usec_,
  10710. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10711. return process_request(strm, remote_addr, remote_port, local_addr,
  10712. local_port, close_connection,
  10713. connection_closed,
  10714. [&](Request &req) { req.ssl = ssl; });
  10715. });
  10716. // Shutdown gracefully if the result seemed successful, non-gracefully if
  10717. // the connection appeared to be closed.
  10718. const bool shutdown_gracefully = ret;
  10719. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  10720. }
  10721. detail::shutdown_socket(sock);
  10722. detail::close_socket(sock);
  10723. return ret;
  10724. }
  10725. inline STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(
  10726. X509_STORE *store) {
  10727. if (!store) { return nullptr; }
  10728. auto ca_list = sk_X509_NAME_new_null();
  10729. if (!ca_list) { return nullptr; }
  10730. // Get all objects from the store
  10731. auto objs = X509_STORE_get0_objects(store);
  10732. if (!objs) {
  10733. sk_X509_NAME_free(ca_list);
  10734. return nullptr;
  10735. }
  10736. // Iterate through objects and extract certificate subject names
  10737. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  10738. auto obj = sk_X509_OBJECT_value(objs, i);
  10739. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  10740. auto cert = X509_OBJECT_get0_X509(obj);
  10741. if (cert) {
  10742. auto subject = X509_get_subject_name(cert);
  10743. if (subject) {
  10744. auto name_dup = X509_NAME_dup(subject);
  10745. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  10746. }
  10747. }
  10748. }
  10749. }
  10750. // If no names were extracted, free the list and return nullptr
  10751. if (sk_X509_NAME_num(ca_list) == 0) {
  10752. sk_X509_NAME_free(ca_list);
  10753. return nullptr;
  10754. }
  10755. return ca_list;
  10756. }
  10757. // SSL HTTP client implementation
  10758. inline SSLClient::SSLClient(const std::string &host)
  10759. : SSLClient(host, 443, std::string(), std::string()) {}
  10760. inline SSLClient::SSLClient(const std::string &host, int port)
  10761. : SSLClient(host, port, std::string(), std::string()) {}
  10762. inline SSLClient::SSLClient(const std::string &host, int port,
  10763. const std::string &client_cert_path,
  10764. const std::string &client_key_path,
  10765. const std::string &private_key_password)
  10766. : ClientImpl(host, port, client_cert_path, client_key_path) {
  10767. ctx_ = SSL_CTX_new(TLS_client_method());
  10768. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  10769. detail::split(&host_[0], &host_[host_.size()], '.',
  10770. [&](const char *b, const char *e) {
  10771. host_components_.emplace_back(b, e);
  10772. });
  10773. if (!client_cert_path.empty() && !client_key_path.empty()) {
  10774. if (!private_key_password.empty()) {
  10775. SSL_CTX_set_default_passwd_cb_userdata(
  10776. ctx_, reinterpret_cast<void *>(
  10777. const_cast<char *>(private_key_password.c_str())));
  10778. }
  10779. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  10780. SSL_FILETYPE_PEM) != 1 ||
  10781. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  10782. SSL_FILETYPE_PEM) != 1) {
  10783. last_openssl_error_ = ERR_get_error();
  10784. SSL_CTX_free(ctx_);
  10785. ctx_ = nullptr;
  10786. }
  10787. }
  10788. }
  10789. inline SSLClient::SSLClient(const std::string &host, int port,
  10790. X509 *client_cert, EVP_PKEY *client_key,
  10791. const std::string &private_key_password)
  10792. : ClientImpl(host, port) {
  10793. ctx_ = SSL_CTX_new(TLS_client_method());
  10794. detail::split(&host_[0], &host_[host_.size()], '.',
  10795. [&](const char *b, const char *e) {
  10796. host_components_.emplace_back(b, e);
  10797. });
  10798. if (client_cert != nullptr && client_key != nullptr) {
  10799. if (!private_key_password.empty()) {
  10800. SSL_CTX_set_default_passwd_cb_userdata(
  10801. ctx_, reinterpret_cast<void *>(
  10802. const_cast<char *>(private_key_password.c_str())));
  10803. }
  10804. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  10805. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  10806. last_openssl_error_ = ERR_get_error();
  10807. SSL_CTX_free(ctx_);
  10808. ctx_ = nullptr;
  10809. }
  10810. }
  10811. }
  10812. inline SSLClient::~SSLClient() {
  10813. if (ctx_) { SSL_CTX_free(ctx_); }
  10814. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  10815. // base function rather than the derived function once we get to the
  10816. // base class destructor, and won't free the SSL (causing a leak).
  10817. shutdown_ssl_impl(socket_, true);
  10818. }
  10819. inline bool SSLClient::is_valid() const { return ctx_; }
  10820. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10821. if (ca_cert_store) {
  10822. if (ctx_) {
  10823. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  10824. // Free memory allocated for old cert and use new store
  10825. // `ca_cert_store`
  10826. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  10827. ca_cert_store_ = ca_cert_store;
  10828. }
  10829. } else {
  10830. X509_STORE_free(ca_cert_store);
  10831. }
  10832. }
  10833. }
  10834. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  10835. std::size_t size) {
  10836. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  10837. }
  10838. inline long SSLClient::get_openssl_verify_result() const {
  10839. return verify_result_;
  10840. }
  10841. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  10842. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  10843. if (!is_valid()) {
  10844. error = Error::SSLConnection;
  10845. return false;
  10846. }
  10847. return ClientImpl::create_and_connect_socket(socket, error);
  10848. }
  10849. // Assumes that socket_mutex_ is locked and that there are no requests in
  10850. // flight
  10851. inline bool SSLClient::connect_with_proxy(
  10852. Socket &socket,
  10853. std::chrono::time_point<std::chrono::steady_clock> start_time,
  10854. Response &res, bool &success, Error &error) {
  10855. success = true;
  10856. Response proxy_res;
  10857. if (!detail::process_client_socket(
  10858. socket.sock, read_timeout_sec_, read_timeout_usec_,
  10859. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  10860. start_time, [&](Stream &strm) {
  10861. Request req2;
  10862. req2.method = "CONNECT";
  10863. req2.path =
  10864. detail::make_host_and_port_string_always_port(host_, port_);
  10865. if (max_timeout_msec_ > 0) {
  10866. req2.start_time_ = std::chrono::steady_clock::now();
  10867. }
  10868. return process_request(strm, req2, proxy_res, false, error);
  10869. })) {
  10870. // Thread-safe to close everything because we are assuming there are no
  10871. // requests in flight
  10872. shutdown_ssl(socket, true);
  10873. shutdown_socket(socket);
  10874. close_socket(socket);
  10875. success = false;
  10876. return false;
  10877. }
  10878. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  10879. if (!proxy_digest_auth_username_.empty() &&
  10880. !proxy_digest_auth_password_.empty()) {
  10881. std::map<std::string, std::string> auth;
  10882. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  10883. // Close the current socket and create a new one for the authenticated
  10884. // request
  10885. shutdown_ssl(socket, true);
  10886. shutdown_socket(socket);
  10887. close_socket(socket);
  10888. // Create a new socket for the authenticated CONNECT request
  10889. if (!ensure_socket_connection(socket, error)) {
  10890. success = false;
  10891. output_error_log(error, nullptr);
  10892. return false;
  10893. }
  10894. proxy_res = Response();
  10895. if (!detail::process_client_socket(
  10896. socket.sock, read_timeout_sec_, read_timeout_usec_,
  10897. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  10898. start_time, [&](Stream &strm) {
  10899. Request req3;
  10900. req3.method = "CONNECT";
  10901. req3.path = detail::make_host_and_port_string_always_port(
  10902. host_, port_);
  10903. req3.headers.insert(detail::make_digest_authentication_header(
  10904. req3, auth, 1, detail::random_string(10),
  10905. proxy_digest_auth_username_, proxy_digest_auth_password_,
  10906. true));
  10907. if (max_timeout_msec_ > 0) {
  10908. req3.start_time_ = std::chrono::steady_clock::now();
  10909. }
  10910. return process_request(strm, req3, proxy_res, false, error);
  10911. })) {
  10912. // Thread-safe to close everything because we are assuming there are
  10913. // no requests in flight
  10914. shutdown_ssl(socket, true);
  10915. shutdown_socket(socket);
  10916. close_socket(socket);
  10917. success = false;
  10918. return false;
  10919. }
  10920. }
  10921. }
  10922. }
  10923. // If status code is not 200, proxy request is failed.
  10924. // Set error to ProxyConnection and return proxy response
  10925. // as the response of the request
  10926. if (proxy_res.status != StatusCode::OK_200) {
  10927. error = Error::ProxyConnection;
  10928. output_error_log(error, nullptr);
  10929. res = std::move(proxy_res);
  10930. // Thread-safe to close everything because we are assuming there are
  10931. // no requests in flight
  10932. shutdown_ssl(socket, true);
  10933. shutdown_socket(socket);
  10934. close_socket(socket);
  10935. return false;
  10936. }
  10937. return true;
  10938. }
  10939. inline bool SSLClient::load_certs() {
  10940. auto ret = true;
  10941. std::call_once(initialize_cert_, [&]() {
  10942. std::lock_guard<std::mutex> guard(ctx_mutex_);
  10943. if (!ca_cert_file_path_.empty()) {
  10944. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  10945. nullptr)) {
  10946. last_openssl_error_ = ERR_get_error();
  10947. ret = false;
  10948. }
  10949. } else if (!ca_cert_dir_path_.empty()) {
  10950. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  10951. ca_cert_dir_path_.c_str())) {
  10952. last_openssl_error_ = ERR_get_error();
  10953. ret = false;
  10954. }
  10955. } else {
  10956. auto loaded = false;
  10957. #ifdef _WIN32
  10958. loaded =
  10959. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  10960. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  10961. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  10962. #endif // _WIN32
  10963. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  10964. }
  10965. });
  10966. return ret;
  10967. }
  10968. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  10969. auto ssl = detail::ssl_new(
  10970. socket.sock, ctx_, ctx_mutex_,
  10971. [&](SSL *ssl2) {
  10972. if (server_certificate_verification_) {
  10973. if (!load_certs()) {
  10974. error = Error::SSLLoadingCerts;
  10975. output_error_log(error, nullptr);
  10976. return false;
  10977. }
  10978. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  10979. }
  10980. if (!detail::ssl_connect_or_accept_nonblocking(
  10981. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  10982. connection_timeout_usec_, &last_ssl_error_)) {
  10983. error = Error::SSLConnection;
  10984. output_error_log(error, nullptr);
  10985. return false;
  10986. }
  10987. if (server_certificate_verification_) {
  10988. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  10989. if (server_certificate_verifier_) {
  10990. verification_status = server_certificate_verifier_(ssl2);
  10991. }
  10992. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  10993. last_openssl_error_ = ERR_get_error();
  10994. error = Error::SSLServerVerification;
  10995. output_error_log(error, nullptr);
  10996. return false;
  10997. }
  10998. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  10999. verify_result_ = SSL_get_verify_result(ssl2);
  11000. if (verify_result_ != X509_V_OK) {
  11001. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  11002. error = Error::SSLServerVerification;
  11003. output_error_log(error, nullptr);
  11004. return false;
  11005. }
  11006. auto server_cert = SSL_get1_peer_certificate(ssl2);
  11007. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  11008. if (server_cert == nullptr) {
  11009. last_openssl_error_ = ERR_get_error();
  11010. error = Error::SSLServerVerification;
  11011. output_error_log(error, nullptr);
  11012. return false;
  11013. }
  11014. if (server_hostname_verification_) {
  11015. if (!verify_host(server_cert)) {
  11016. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  11017. error = Error::SSLServerHostnameVerification;
  11018. output_error_log(error, nullptr);
  11019. return false;
  11020. }
  11021. }
  11022. }
  11023. }
  11024. return true;
  11025. },
  11026. [&](SSL *ssl2) {
  11027. // Set SNI only if host is not IP address
  11028. if (!detail::is_ip_address(host_)) {
  11029. #if defined(OPENSSL_IS_BORINGSSL)
  11030. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  11031. #else
  11032. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  11033. // -Wold-style-cast warning
  11034. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME,
  11035. TLSEXT_NAMETYPE_host_name,
  11036. static_cast<void *>(const_cast<char *>(host_.c_str())));
  11037. #endif
  11038. }
  11039. return true;
  11040. });
  11041. if (ssl) {
  11042. socket.ssl = ssl;
  11043. return true;
  11044. }
  11045. if (ctx_ == nullptr) {
  11046. error = Error::SSLConnection;
  11047. last_openssl_error_ = ERR_get_error();
  11048. }
  11049. shutdown_socket(socket);
  11050. close_socket(socket);
  11051. return false;
  11052. }
  11053. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  11054. shutdown_ssl_impl(socket, shutdown_gracefully);
  11055. }
  11056. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  11057. bool shutdown_gracefully) {
  11058. if (socket.sock == INVALID_SOCKET) {
  11059. assert(socket.ssl == nullptr);
  11060. return;
  11061. }
  11062. if (socket.ssl) {
  11063. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  11064. shutdown_gracefully);
  11065. socket.ssl = nullptr;
  11066. }
  11067. assert(socket.ssl == nullptr);
  11068. }
  11069. inline bool SSLClient::process_socket(
  11070. const Socket &socket,
  11071. std::chrono::time_point<std::chrono::steady_clock> start_time,
  11072. std::function<bool(Stream &strm)> callback) {
  11073. assert(socket.ssl);
  11074. return detail::process_client_socket_ssl(
  11075. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  11076. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  11077. std::move(callback));
  11078. }
  11079. inline bool SSLClient::is_ssl() const { return true; }
  11080. inline bool SSLClient::verify_host(X509 *server_cert) const {
  11081. /* Quote from RFC2818 section 3.1 "Server Identity"
  11082. If a subjectAltName extension of type dNSName is present, that MUST
  11083. be used as the identity. Otherwise, the (most specific) Common Name
  11084. field in the Subject field of the certificate MUST be used. Although
  11085. the use of the Common Name is existing practice, it is deprecated and
  11086. Certification Authorities are encouraged to use the dNSName instead.
  11087. Matching is performed using the matching rules specified by
  11088. [RFC2459]. If more than one identity of a given type is present in
  11089. the certificate (e.g., more than one dNSName name, a match in any one
  11090. of the set is considered acceptable.) Names may contain the wildcard
  11091. character * which is considered to match any single domain name
  11092. component or component fragment. E.g., *.a.com matches foo.a.com but
  11093. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  11094. In some cases, the URI is specified as an IP address rather than a
  11095. hostname. In this case, the iPAddress subjectAltName must be present
  11096. in the certificate and must exactly match the IP in the URI.
  11097. */
  11098. return verify_host_with_subject_alt_name(server_cert) ||
  11099. verify_host_with_common_name(server_cert);
  11100. }
  11101. inline bool
  11102. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  11103. auto ret = false;
  11104. auto type = GEN_DNS;
  11105. struct in6_addr addr6 = {};
  11106. struct in_addr addr = {};
  11107. size_t addr_len = 0;
  11108. #ifndef __MINGW32__
  11109. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  11110. type = GEN_IPADD;
  11111. addr_len = sizeof(struct in6_addr);
  11112. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  11113. type = GEN_IPADD;
  11114. addr_len = sizeof(struct in_addr);
  11115. }
  11116. #endif
  11117. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  11118. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  11119. if (alt_names) {
  11120. auto dsn_matched = false;
  11121. auto ip_matched = false;
  11122. auto count = sk_GENERAL_NAME_num(alt_names);
  11123. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  11124. auto val = sk_GENERAL_NAME_value(alt_names, i);
  11125. if (!val || val->type != type) { continue; }
  11126. auto name =
  11127. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  11128. if (name == nullptr) { continue; }
  11129. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  11130. switch (type) {
  11131. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  11132. case GEN_IPADD:
  11133. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  11134. ip_matched = true;
  11135. }
  11136. break;
  11137. }
  11138. }
  11139. if (dsn_matched || ip_matched) { ret = true; }
  11140. }
  11141. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  11142. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  11143. return ret;
  11144. }
  11145. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  11146. const auto subject_name = X509_get_subject_name(server_cert);
  11147. if (subject_name != nullptr) {
  11148. char name[BUFSIZ];
  11149. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  11150. name, sizeof(name));
  11151. if (name_len != -1) {
  11152. return check_host_name(name, static_cast<size_t>(name_len));
  11153. }
  11154. }
  11155. return false;
  11156. }
  11157. inline bool SSLClient::check_host_name(const char *pattern,
  11158. size_t pattern_len) const {
  11159. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  11160. // Wildcard match
  11161. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  11162. std::vector<std::string> pattern_components;
  11163. detail::split(&pattern[0], &pattern[pattern_len], '.',
  11164. [&](const char *b, const char *e) {
  11165. pattern_components.emplace_back(b, e);
  11166. });
  11167. if (host_components_.size() != pattern_components.size()) { return false; }
  11168. auto itr = pattern_components.begin();
  11169. for (const auto &h : host_components_) {
  11170. auto &p = *itr;
  11171. if (p != h && p != "*") {
  11172. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  11173. !p.compare(0, p.size() - 1, h));
  11174. if (!partial_match) { return false; }
  11175. }
  11176. ++itr;
  11177. }
  11178. return true;
  11179. }
  11180. #endif
  11181. // Universal client implementation
  11182. inline Client::Client(const std::string &scheme_host_port)
  11183. : Client(scheme_host_port, std::string(), std::string()) {}
  11184. inline Client::Client(const std::string &scheme_host_port,
  11185. const std::string &client_cert_path,
  11186. const std::string &client_key_path) {
  11187. const static std::regex re(
  11188. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  11189. std::smatch m;
  11190. if (std::regex_match(scheme_host_port, m, re)) {
  11191. auto scheme = m[1].str();
  11192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11193. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  11194. #else
  11195. if (!scheme.empty() && scheme != "http") {
  11196. #endif
  11197. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11198. std::string msg = "'" + scheme + "' scheme is not supported.";
  11199. throw std::invalid_argument(msg);
  11200. #endif
  11201. return;
  11202. }
  11203. auto is_ssl = scheme == "https";
  11204. auto host = m[2].str();
  11205. if (host.empty()) { host = m[3].str(); }
  11206. auto port_str = m[4].str();
  11207. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  11208. if (is_ssl) {
  11209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11210. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  11211. client_key_path);
  11212. is_ssl_ = is_ssl;
  11213. #endif
  11214. } else {
  11215. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11216. client_key_path);
  11217. }
  11218. } else {
  11219. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  11220. // if port param below changes.
  11221. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  11222. client_cert_path, client_key_path);
  11223. }
  11224. } // namespace detail
  11225. inline Client::Client(const std::string &host, int port)
  11226. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  11227. inline Client::Client(const std::string &host, int port,
  11228. const std::string &client_cert_path,
  11229. const std::string &client_key_path)
  11230. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  11231. client_key_path)) {}
  11232. inline Client::~Client() = default;
  11233. inline bool Client::is_valid() const {
  11234. return cli_ != nullptr && cli_->is_valid();
  11235. }
  11236. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  11237. return cli_->Get(path, std::move(progress));
  11238. }
  11239. inline Result Client::Get(const std::string &path, const Headers &headers,
  11240. DownloadProgress progress) {
  11241. return cli_->Get(path, headers, std::move(progress));
  11242. }
  11243. inline Result Client::Get(const std::string &path,
  11244. ContentReceiver content_receiver,
  11245. DownloadProgress progress) {
  11246. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  11247. }
  11248. inline Result Client::Get(const std::string &path, const Headers &headers,
  11249. ContentReceiver content_receiver,
  11250. DownloadProgress progress) {
  11251. return cli_->Get(path, headers, std::move(content_receiver),
  11252. std::move(progress));
  11253. }
  11254. inline Result Client::Get(const std::string &path,
  11255. ResponseHandler response_handler,
  11256. ContentReceiver content_receiver,
  11257. DownloadProgress progress) {
  11258. return cli_->Get(path, std::move(response_handler),
  11259. std::move(content_receiver), std::move(progress));
  11260. }
  11261. inline Result Client::Get(const std::string &path, const Headers &headers,
  11262. ResponseHandler response_handler,
  11263. ContentReceiver content_receiver,
  11264. DownloadProgress progress) {
  11265. return cli_->Get(path, headers, std::move(response_handler),
  11266. std::move(content_receiver), std::move(progress));
  11267. }
  11268. inline Result Client::Get(const std::string &path, const Params &params,
  11269. const Headers &headers, DownloadProgress progress) {
  11270. return cli_->Get(path, params, headers, std::move(progress));
  11271. }
  11272. inline Result Client::Get(const std::string &path, const Params &params,
  11273. const Headers &headers,
  11274. ContentReceiver content_receiver,
  11275. DownloadProgress progress) {
  11276. return cli_->Get(path, params, headers, std::move(content_receiver),
  11277. std::move(progress));
  11278. }
  11279. inline Result Client::Get(const std::string &path, const Params &params,
  11280. const Headers &headers,
  11281. ResponseHandler response_handler,
  11282. ContentReceiver content_receiver,
  11283. DownloadProgress progress) {
  11284. return cli_->Get(path, params, headers, std::move(response_handler),
  11285. std::move(content_receiver), std::move(progress));
  11286. }
  11287. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  11288. inline Result Client::Head(const std::string &path, const Headers &headers) {
  11289. return cli_->Head(path, headers);
  11290. }
  11291. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  11292. inline Result Client::Post(const std::string &path, const Headers &headers) {
  11293. return cli_->Post(path, headers);
  11294. }
  11295. inline Result Client::Post(const std::string &path, const char *body,
  11296. size_t content_length,
  11297. const std::string &content_type,
  11298. UploadProgress progress) {
  11299. return cli_->Post(path, body, content_length, content_type, progress);
  11300. }
  11301. inline Result Client::Post(const std::string &path, const Headers &headers,
  11302. const char *body, size_t content_length,
  11303. const std::string &content_type,
  11304. UploadProgress progress) {
  11305. return cli_->Post(path, headers, body, content_length, content_type,
  11306. progress);
  11307. }
  11308. inline Result Client::Post(const std::string &path, const std::string &body,
  11309. const std::string &content_type,
  11310. UploadProgress progress) {
  11311. return cli_->Post(path, body, content_type, progress);
  11312. }
  11313. inline Result Client::Post(const std::string &path, const Headers &headers,
  11314. const std::string &body,
  11315. const std::string &content_type,
  11316. UploadProgress progress) {
  11317. return cli_->Post(path, headers, body, content_type, progress);
  11318. }
  11319. inline Result Client::Post(const std::string &path, size_t content_length,
  11320. ContentProvider content_provider,
  11321. const std::string &content_type,
  11322. UploadProgress progress) {
  11323. return cli_->Post(path, content_length, std::move(content_provider),
  11324. content_type, progress);
  11325. }
  11326. inline Result Client::Post(const std::string &path, size_t content_length,
  11327. ContentProvider content_provider,
  11328. const std::string &content_type,
  11329. ContentReceiver content_receiver,
  11330. UploadProgress progress) {
  11331. return cli_->Post(path, content_length, std::move(content_provider),
  11332. content_type, std::move(content_receiver), progress);
  11333. }
  11334. inline Result Client::Post(const std::string &path,
  11335. ContentProviderWithoutLength content_provider,
  11336. const std::string &content_type,
  11337. UploadProgress progress) {
  11338. return cli_->Post(path, std::move(content_provider), content_type, progress);
  11339. }
  11340. inline Result Client::Post(const std::string &path,
  11341. ContentProviderWithoutLength content_provider,
  11342. const std::string &content_type,
  11343. ContentReceiver content_receiver,
  11344. UploadProgress progress) {
  11345. return cli_->Post(path, std::move(content_provider), content_type,
  11346. std::move(content_receiver), progress);
  11347. }
  11348. inline Result Client::Post(const std::string &path, const Headers &headers,
  11349. size_t content_length,
  11350. ContentProvider content_provider,
  11351. const std::string &content_type,
  11352. UploadProgress progress) {
  11353. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11354. content_type, progress);
  11355. }
  11356. inline Result Client::Post(const std::string &path, const Headers &headers,
  11357. size_t content_length,
  11358. ContentProvider content_provider,
  11359. const std::string &content_type,
  11360. ContentReceiver content_receiver,
  11361. DownloadProgress progress) {
  11362. return cli_->Post(path, headers, content_length, std::move(content_provider),
  11363. content_type, std::move(content_receiver), progress);
  11364. }
  11365. inline Result Client::Post(const std::string &path, const Headers &headers,
  11366. ContentProviderWithoutLength content_provider,
  11367. const std::string &content_type,
  11368. UploadProgress progress) {
  11369. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11370. progress);
  11371. }
  11372. inline Result Client::Post(const std::string &path, const Headers &headers,
  11373. ContentProviderWithoutLength content_provider,
  11374. const std::string &content_type,
  11375. ContentReceiver content_receiver,
  11376. DownloadProgress progress) {
  11377. return cli_->Post(path, headers, std::move(content_provider), content_type,
  11378. std::move(content_receiver), progress);
  11379. }
  11380. inline Result Client::Post(const std::string &path, const Params &params) {
  11381. return cli_->Post(path, params);
  11382. }
  11383. inline Result Client::Post(const std::string &path, const Headers &headers,
  11384. const Params &params) {
  11385. return cli_->Post(path, headers, params);
  11386. }
  11387. inline Result Client::Post(const std::string &path,
  11388. const UploadFormDataItems &items,
  11389. UploadProgress progress) {
  11390. return cli_->Post(path, items, progress);
  11391. }
  11392. inline Result Client::Post(const std::string &path, const Headers &headers,
  11393. const UploadFormDataItems &items,
  11394. UploadProgress progress) {
  11395. return cli_->Post(path, headers, items, progress);
  11396. }
  11397. inline Result Client::Post(const std::string &path, const Headers &headers,
  11398. const UploadFormDataItems &items,
  11399. const std::string &boundary,
  11400. UploadProgress progress) {
  11401. return cli_->Post(path, headers, items, boundary, progress);
  11402. }
  11403. inline Result Client::Post(const std::string &path, const Headers &headers,
  11404. const UploadFormDataItems &items,
  11405. const FormDataProviderItems &provider_items,
  11406. UploadProgress progress) {
  11407. return cli_->Post(path, headers, items, provider_items, progress);
  11408. }
  11409. inline Result Client::Post(const std::string &path, const Headers &headers,
  11410. const std::string &body,
  11411. const std::string &content_type,
  11412. ContentReceiver content_receiver,
  11413. DownloadProgress progress) {
  11414. return cli_->Post(path, headers, body, content_type,
  11415. std::move(content_receiver), progress);
  11416. }
  11417. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  11418. inline Result Client::Put(const std::string &path, const Headers &headers) {
  11419. return cli_->Put(path, headers);
  11420. }
  11421. inline Result Client::Put(const std::string &path, const char *body,
  11422. size_t content_length,
  11423. const std::string &content_type,
  11424. UploadProgress progress) {
  11425. return cli_->Put(path, body, content_length, content_type, progress);
  11426. }
  11427. inline Result Client::Put(const std::string &path, const Headers &headers,
  11428. const char *body, size_t content_length,
  11429. const std::string &content_type,
  11430. UploadProgress progress) {
  11431. return cli_->Put(path, headers, body, content_length, content_type, progress);
  11432. }
  11433. inline Result Client::Put(const std::string &path, const std::string &body,
  11434. const std::string &content_type,
  11435. UploadProgress progress) {
  11436. return cli_->Put(path, body, content_type, progress);
  11437. }
  11438. inline Result Client::Put(const std::string &path, const Headers &headers,
  11439. const std::string &body,
  11440. const std::string &content_type,
  11441. UploadProgress progress) {
  11442. return cli_->Put(path, headers, body, content_type, progress);
  11443. }
  11444. inline Result Client::Put(const std::string &path, size_t content_length,
  11445. ContentProvider content_provider,
  11446. const std::string &content_type,
  11447. UploadProgress progress) {
  11448. return cli_->Put(path, content_length, std::move(content_provider),
  11449. content_type, progress);
  11450. }
  11451. inline Result Client::Put(const std::string &path, size_t content_length,
  11452. ContentProvider content_provider,
  11453. const std::string &content_type,
  11454. ContentReceiver content_receiver,
  11455. UploadProgress progress) {
  11456. return cli_->Put(path, content_length, std::move(content_provider),
  11457. content_type, std::move(content_receiver), progress);
  11458. }
  11459. inline Result Client::Put(const std::string &path,
  11460. ContentProviderWithoutLength content_provider,
  11461. const std::string &content_type,
  11462. UploadProgress progress) {
  11463. return cli_->Put(path, std::move(content_provider), content_type, progress);
  11464. }
  11465. inline Result Client::Put(const std::string &path,
  11466. ContentProviderWithoutLength content_provider,
  11467. const std::string &content_type,
  11468. ContentReceiver content_receiver,
  11469. UploadProgress progress) {
  11470. return cli_->Put(path, std::move(content_provider), content_type,
  11471. std::move(content_receiver), progress);
  11472. }
  11473. inline Result Client::Put(const std::string &path, const Headers &headers,
  11474. size_t content_length,
  11475. ContentProvider content_provider,
  11476. const std::string &content_type,
  11477. UploadProgress progress) {
  11478. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11479. content_type, progress);
  11480. }
  11481. inline Result Client::Put(const std::string &path, const Headers &headers,
  11482. size_t content_length,
  11483. ContentProvider content_provider,
  11484. const std::string &content_type,
  11485. ContentReceiver content_receiver,
  11486. UploadProgress progress) {
  11487. return cli_->Put(path, headers, content_length, std::move(content_provider),
  11488. content_type, std::move(content_receiver), progress);
  11489. }
  11490. inline Result Client::Put(const std::string &path, const Headers &headers,
  11491. ContentProviderWithoutLength content_provider,
  11492. const std::string &content_type,
  11493. UploadProgress progress) {
  11494. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11495. progress);
  11496. }
  11497. inline Result Client::Put(const std::string &path, const Headers &headers,
  11498. ContentProviderWithoutLength content_provider,
  11499. const std::string &content_type,
  11500. ContentReceiver content_receiver,
  11501. UploadProgress progress) {
  11502. return cli_->Put(path, headers, std::move(content_provider), content_type,
  11503. std::move(content_receiver), progress);
  11504. }
  11505. inline Result Client::Put(const std::string &path, const Params &params) {
  11506. return cli_->Put(path, params);
  11507. }
  11508. inline Result Client::Put(const std::string &path, const Headers &headers,
  11509. const Params &params) {
  11510. return cli_->Put(path, headers, params);
  11511. }
  11512. inline Result Client::Put(const std::string &path,
  11513. const UploadFormDataItems &items,
  11514. UploadProgress progress) {
  11515. return cli_->Put(path, items, progress);
  11516. }
  11517. inline Result Client::Put(const std::string &path, const Headers &headers,
  11518. const UploadFormDataItems &items,
  11519. UploadProgress progress) {
  11520. return cli_->Put(path, headers, items, progress);
  11521. }
  11522. inline Result Client::Put(const std::string &path, const Headers &headers,
  11523. const UploadFormDataItems &items,
  11524. const std::string &boundary,
  11525. UploadProgress progress) {
  11526. return cli_->Put(path, headers, items, boundary, progress);
  11527. }
  11528. inline Result Client::Put(const std::string &path, const Headers &headers,
  11529. const UploadFormDataItems &items,
  11530. const FormDataProviderItems &provider_items,
  11531. UploadProgress progress) {
  11532. return cli_->Put(path, headers, items, provider_items, progress);
  11533. }
  11534. inline Result Client::Put(const std::string &path, const Headers &headers,
  11535. const std::string &body,
  11536. const std::string &content_type,
  11537. ContentReceiver content_receiver,
  11538. DownloadProgress progress) {
  11539. return cli_->Put(path, headers, body, content_type, content_receiver,
  11540. progress);
  11541. }
  11542. inline Result Client::Patch(const std::string &path) {
  11543. return cli_->Patch(path);
  11544. }
  11545. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  11546. return cli_->Patch(path, headers);
  11547. }
  11548. inline Result Client::Patch(const std::string &path, const char *body,
  11549. size_t content_length,
  11550. const std::string &content_type,
  11551. UploadProgress progress) {
  11552. return cli_->Patch(path, body, content_length, content_type, progress);
  11553. }
  11554. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11555. const char *body, size_t content_length,
  11556. const std::string &content_type,
  11557. UploadProgress progress) {
  11558. return cli_->Patch(path, headers, body, content_length, content_type,
  11559. progress);
  11560. }
  11561. inline Result Client::Patch(const std::string &path, const std::string &body,
  11562. const std::string &content_type,
  11563. UploadProgress progress) {
  11564. return cli_->Patch(path, body, content_type, progress);
  11565. }
  11566. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11567. const std::string &body,
  11568. const std::string &content_type,
  11569. UploadProgress progress) {
  11570. return cli_->Patch(path, headers, body, content_type, progress);
  11571. }
  11572. inline Result Client::Patch(const std::string &path, size_t content_length,
  11573. ContentProvider content_provider,
  11574. const std::string &content_type,
  11575. UploadProgress progress) {
  11576. return cli_->Patch(path, content_length, std::move(content_provider),
  11577. content_type, progress);
  11578. }
  11579. inline Result Client::Patch(const std::string &path, size_t content_length,
  11580. ContentProvider content_provider,
  11581. const std::string &content_type,
  11582. ContentReceiver content_receiver,
  11583. UploadProgress progress) {
  11584. return cli_->Patch(path, content_length, std::move(content_provider),
  11585. content_type, std::move(content_receiver), progress);
  11586. }
  11587. inline Result Client::Patch(const std::string &path,
  11588. ContentProviderWithoutLength content_provider,
  11589. const std::string &content_type,
  11590. UploadProgress progress) {
  11591. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  11592. }
  11593. inline Result Client::Patch(const std::string &path,
  11594. ContentProviderWithoutLength content_provider,
  11595. const std::string &content_type,
  11596. ContentReceiver content_receiver,
  11597. UploadProgress progress) {
  11598. return cli_->Patch(path, std::move(content_provider), content_type,
  11599. std::move(content_receiver), progress);
  11600. }
  11601. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11602. size_t content_length,
  11603. ContentProvider content_provider,
  11604. const std::string &content_type,
  11605. UploadProgress progress) {
  11606. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11607. content_type, progress);
  11608. }
  11609. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11610. size_t content_length,
  11611. ContentProvider content_provider,
  11612. const std::string &content_type,
  11613. ContentReceiver content_receiver,
  11614. UploadProgress progress) {
  11615. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  11616. content_type, std::move(content_receiver), progress);
  11617. }
  11618. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11619. ContentProviderWithoutLength content_provider,
  11620. const std::string &content_type,
  11621. UploadProgress progress) {
  11622. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11623. progress);
  11624. }
  11625. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11626. ContentProviderWithoutLength content_provider,
  11627. const std::string &content_type,
  11628. ContentReceiver content_receiver,
  11629. UploadProgress progress) {
  11630. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  11631. std::move(content_receiver), progress);
  11632. }
  11633. inline Result Client::Patch(const std::string &path, const Params &params) {
  11634. return cli_->Patch(path, params);
  11635. }
  11636. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11637. const Params &params) {
  11638. return cli_->Patch(path, headers, params);
  11639. }
  11640. inline Result Client::Patch(const std::string &path,
  11641. const UploadFormDataItems &items,
  11642. UploadProgress progress) {
  11643. return cli_->Patch(path, items, progress);
  11644. }
  11645. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11646. const UploadFormDataItems &items,
  11647. UploadProgress progress) {
  11648. return cli_->Patch(path, headers, items, progress);
  11649. }
  11650. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11651. const UploadFormDataItems &items,
  11652. const std::string &boundary,
  11653. UploadProgress progress) {
  11654. return cli_->Patch(path, headers, items, boundary, progress);
  11655. }
  11656. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11657. const UploadFormDataItems &items,
  11658. const FormDataProviderItems &provider_items,
  11659. UploadProgress progress) {
  11660. return cli_->Patch(path, headers, items, provider_items, progress);
  11661. }
  11662. inline Result Client::Patch(const std::string &path, const Headers &headers,
  11663. const std::string &body,
  11664. const std::string &content_type,
  11665. ContentReceiver content_receiver,
  11666. DownloadProgress progress) {
  11667. return cli_->Patch(path, headers, body, content_type, content_receiver,
  11668. progress);
  11669. }
  11670. inline Result Client::Delete(const std::string &path,
  11671. DownloadProgress progress) {
  11672. return cli_->Delete(path, progress);
  11673. }
  11674. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11675. DownloadProgress progress) {
  11676. return cli_->Delete(path, headers, progress);
  11677. }
  11678. inline Result Client::Delete(const std::string &path, const char *body,
  11679. size_t content_length,
  11680. const std::string &content_type,
  11681. DownloadProgress progress) {
  11682. return cli_->Delete(path, body, content_length, content_type, progress);
  11683. }
  11684. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11685. const char *body, size_t content_length,
  11686. const std::string &content_type,
  11687. DownloadProgress progress) {
  11688. return cli_->Delete(path, headers, body, content_length, content_type,
  11689. progress);
  11690. }
  11691. inline Result Client::Delete(const std::string &path, const std::string &body,
  11692. const std::string &content_type,
  11693. DownloadProgress progress) {
  11694. return cli_->Delete(path, body, content_type, progress);
  11695. }
  11696. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11697. const std::string &body,
  11698. const std::string &content_type,
  11699. DownloadProgress progress) {
  11700. return cli_->Delete(path, headers, body, content_type, progress);
  11701. }
  11702. inline Result Client::Delete(const std::string &path, const Params &params,
  11703. DownloadProgress progress) {
  11704. return cli_->Delete(path, params, progress);
  11705. }
  11706. inline Result Client::Delete(const std::string &path, const Headers &headers,
  11707. const Params &params, DownloadProgress progress) {
  11708. return cli_->Delete(path, headers, params, progress);
  11709. }
  11710. inline Result Client::Options(const std::string &path) {
  11711. return cli_->Options(path);
  11712. }
  11713. inline Result Client::Options(const std::string &path, const Headers &headers) {
  11714. return cli_->Options(path, headers);
  11715. }
  11716. inline ClientImpl::StreamHandle
  11717. Client::open_stream(const std::string &method, const std::string &path,
  11718. const Params &params, const Headers &headers,
  11719. const std::string &body, const std::string &content_type) {
  11720. return cli_->open_stream(method, path, params, headers, body, content_type);
  11721. }
  11722. inline bool Client::send(Request &req, Response &res, Error &error) {
  11723. return cli_->send(req, res, error);
  11724. }
  11725. inline Result Client::send(const Request &req) { return cli_->send(req); }
  11726. inline void Client::stop() { cli_->stop(); }
  11727. inline std::string Client::host() const { return cli_->host(); }
  11728. inline int Client::port() const { return cli_->port(); }
  11729. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  11730. inline socket_t Client::socket() const { return cli_->socket(); }
  11731. inline void
  11732. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  11733. cli_->set_hostname_addr_map(std::move(addr_map));
  11734. }
  11735. inline void Client::set_default_headers(Headers headers) {
  11736. cli_->set_default_headers(std::move(headers));
  11737. }
  11738. inline void Client::set_header_writer(
  11739. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  11740. cli_->set_header_writer(writer);
  11741. }
  11742. inline void Client::set_address_family(int family) {
  11743. cli_->set_address_family(family);
  11744. }
  11745. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  11746. inline void Client::set_socket_options(SocketOptions socket_options) {
  11747. cli_->set_socket_options(std::move(socket_options));
  11748. }
  11749. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  11750. cli_->set_connection_timeout(sec, usec);
  11751. }
  11752. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  11753. cli_->set_read_timeout(sec, usec);
  11754. }
  11755. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  11756. cli_->set_write_timeout(sec, usec);
  11757. }
  11758. inline void Client::set_basic_auth(const std::string &username,
  11759. const std::string &password) {
  11760. cli_->set_basic_auth(username, password);
  11761. }
  11762. inline void Client::set_bearer_token_auth(const std::string &token) {
  11763. cli_->set_bearer_token_auth(token);
  11764. }
  11765. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11766. inline void Client::set_digest_auth(const std::string &username,
  11767. const std::string &password) {
  11768. cli_->set_digest_auth(username, password);
  11769. }
  11770. #endif
  11771. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  11772. inline void Client::set_follow_location(bool on) {
  11773. cli_->set_follow_location(on);
  11774. }
  11775. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  11776. [[deprecated("Use set_path_encode instead")]]
  11777. inline void Client::set_url_encode(bool on) {
  11778. cli_->set_path_encode(on);
  11779. }
  11780. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  11781. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  11782. inline void Client::set_interface(const std::string &intf) {
  11783. cli_->set_interface(intf);
  11784. }
  11785. inline void Client::set_proxy(const std::string &host, int port) {
  11786. cli_->set_proxy(host, port);
  11787. }
  11788. inline void Client::set_proxy_basic_auth(const std::string &username,
  11789. const std::string &password) {
  11790. cli_->set_proxy_basic_auth(username, password);
  11791. }
  11792. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  11793. cli_->set_proxy_bearer_token_auth(token);
  11794. }
  11795. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11796. inline void Client::set_proxy_digest_auth(const std::string &username,
  11797. const std::string &password) {
  11798. cli_->set_proxy_digest_auth(username, password);
  11799. }
  11800. #endif
  11801. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11802. inline void Client::enable_server_certificate_verification(bool enabled) {
  11803. cli_->enable_server_certificate_verification(enabled);
  11804. }
  11805. inline void Client::enable_server_hostname_verification(bool enabled) {
  11806. cli_->enable_server_hostname_verification(enabled);
  11807. }
  11808. inline void Client::set_server_certificate_verifier(
  11809. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  11810. cli_->set_server_certificate_verifier(verifier);
  11811. }
  11812. #endif
  11813. inline void Client::set_logger(Logger logger) {
  11814. cli_->set_logger(std::move(logger));
  11815. }
  11816. inline void Client::set_error_logger(ErrorLogger error_logger) {
  11817. cli_->set_error_logger(std::move(error_logger));
  11818. }
  11819. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11820. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  11821. const std::string &ca_cert_dir_path) {
  11822. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  11823. }
  11824. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  11825. if (is_ssl_) {
  11826. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  11827. } else {
  11828. cli_->set_ca_cert_store(ca_cert_store);
  11829. }
  11830. }
  11831. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  11832. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  11833. }
  11834. inline long Client::get_openssl_verify_result() const {
  11835. if (is_ssl_) {
  11836. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  11837. }
  11838. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  11839. }
  11840. inline SSL_CTX *Client::ssl_context() const {
  11841. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  11842. return nullptr;
  11843. }
  11844. #endif
  11845. // ----------------------------------------------------------------------------
  11846. } // namespace httplib
  11847. #endif // CPPHTTPLIB_HTTPLIB_H