httplib.h 302 KB

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