httplib.h 341 KB

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