httplib.h 366 KB

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