httplib.h 345 KB

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