httplib.h 342 KB

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