httplib.h 334 KB

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