httplib.h 303 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441
  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.3"
  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, 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') {
  1980. return false;
  1981. } else if (path[i] == '\\') {
  1982. return false;
  1983. }
  1984. i++;
  1985. }
  1986. auto len = i - beg;
  1987. assert(len > 0);
  1988. if (!path.compare(beg, len, ".")) {
  1989. ;
  1990. } else if (!path.compare(beg, len, "..")) {
  1991. if (level == 0) { return false; }
  1992. level--;
  1993. } else {
  1994. level++;
  1995. }
  1996. // Skip slash
  1997. while (i < path.size() && path[i] == '/') {
  1998. i++;
  1999. }
  2000. }
  2001. return true;
  2002. }
  2003. inline std::string encode_query_param(const std::string &value) {
  2004. std::ostringstream escaped;
  2005. escaped.fill('0');
  2006. escaped << std::hex;
  2007. for (auto c : value) {
  2008. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  2009. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  2010. c == ')') {
  2011. escaped << c;
  2012. } else {
  2013. escaped << std::uppercase;
  2014. escaped << '%' << std::setw(2)
  2015. << static_cast<int>(static_cast<unsigned char>(c));
  2016. escaped << std::nouppercase;
  2017. }
  2018. }
  2019. return escaped.str();
  2020. }
  2021. inline std::string encode_url(const std::string &s) {
  2022. std::string result;
  2023. result.reserve(s.size());
  2024. for (size_t i = 0; s[i]; i++) {
  2025. switch (s[i]) {
  2026. case ' ': result += "%20"; break;
  2027. case '+': result += "%2B"; break;
  2028. case '\r': result += "%0D"; break;
  2029. case '\n': result += "%0A"; break;
  2030. case '\'': result += "%27"; break;
  2031. case ',': result += "%2C"; break;
  2032. // case ':': result += "%3A"; break; // ok? probably...
  2033. case ';': result += "%3B"; break;
  2034. default:
  2035. auto c = static_cast<uint8_t>(s[i]);
  2036. if (c >= 0x80) {
  2037. result += '%';
  2038. char hex[4];
  2039. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  2040. assert(len == 2);
  2041. result.append(hex, static_cast<size_t>(len));
  2042. } else {
  2043. result += s[i];
  2044. }
  2045. break;
  2046. }
  2047. }
  2048. return result;
  2049. }
  2050. inline std::string decode_url(const std::string &s,
  2051. bool convert_plus_to_space) {
  2052. std::string result;
  2053. for (size_t i = 0; i < s.size(); i++) {
  2054. if (s[i] == '%' && i + 1 < s.size()) {
  2055. if (s[i + 1] == 'u') {
  2056. auto val = 0;
  2057. if (from_hex_to_i(s, i + 2, 4, val)) {
  2058. // 4 digits Unicode codes
  2059. char buff[4];
  2060. size_t len = to_utf8(val, buff);
  2061. if (len > 0) { result.append(buff, len); }
  2062. i += 5; // 'u0000'
  2063. } else {
  2064. result += s[i];
  2065. }
  2066. } else {
  2067. auto val = 0;
  2068. if (from_hex_to_i(s, i + 1, 2, val)) {
  2069. // 2 digits hex codes
  2070. result += static_cast<char>(val);
  2071. i += 2; // '00'
  2072. } else {
  2073. result += s[i];
  2074. }
  2075. }
  2076. } else if (convert_plus_to_space && s[i] == '+') {
  2077. result += ' ';
  2078. } else {
  2079. result += s[i];
  2080. }
  2081. }
  2082. return result;
  2083. }
  2084. inline void read_file(const std::string &path, std::string &out) {
  2085. std::ifstream fs(path, std::ios_base::binary);
  2086. fs.seekg(0, std::ios_base::end);
  2087. auto size = fs.tellg();
  2088. fs.seekg(0);
  2089. out.resize(static_cast<size_t>(size));
  2090. fs.read(&out[0], static_cast<std::streamsize>(size));
  2091. }
  2092. inline std::string file_extension(const std::string &path) {
  2093. std::smatch m;
  2094. static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  2095. if (std::regex_search(path, m, re)) { return m[1].str(); }
  2096. return std::string();
  2097. }
  2098. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  2099. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  2100. size_t right) {
  2101. while (b + left < e && is_space_or_tab(b[left])) {
  2102. left++;
  2103. }
  2104. while (right > 0 && is_space_or_tab(b[right - 1])) {
  2105. right--;
  2106. }
  2107. return std::make_pair(left, right);
  2108. }
  2109. inline std::string trim_copy(const std::string &s) {
  2110. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  2111. return s.substr(r.first, r.second - r.first);
  2112. }
  2113. inline std::string trim_double_quotes_copy(const std::string &s) {
  2114. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  2115. return s.substr(1, s.size() - 2);
  2116. }
  2117. return s;
  2118. }
  2119. inline void split(const char *b, const char *e, char d,
  2120. std::function<void(const char *, const char *)> fn) {
  2121. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  2122. }
  2123. inline void split(const char *b, const char *e, char d, size_t m,
  2124. std::function<void(const char *, const char *)> fn) {
  2125. size_t i = 0;
  2126. size_t beg = 0;
  2127. size_t count = 1;
  2128. while (e ? (b + i < e) : (b[i] != '\0')) {
  2129. if (b[i] == d && count < m) {
  2130. auto r = trim(b, e, beg, i);
  2131. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2132. beg = i + 1;
  2133. count++;
  2134. }
  2135. i++;
  2136. }
  2137. if (i) {
  2138. auto r = trim(b, e, beg, i);
  2139. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2140. }
  2141. }
  2142. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  2143. size_t fixed_buffer_size)
  2144. : strm_(strm), fixed_buffer_(fixed_buffer),
  2145. fixed_buffer_size_(fixed_buffer_size) {}
  2146. inline const char *stream_line_reader::ptr() const {
  2147. if (glowable_buffer_.empty()) {
  2148. return fixed_buffer_;
  2149. } else {
  2150. return glowable_buffer_.data();
  2151. }
  2152. }
  2153. inline size_t stream_line_reader::size() const {
  2154. if (glowable_buffer_.empty()) {
  2155. return fixed_buffer_used_size_;
  2156. } else {
  2157. return glowable_buffer_.size();
  2158. }
  2159. }
  2160. inline bool stream_line_reader::end_with_crlf() const {
  2161. auto end = ptr() + size();
  2162. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  2163. }
  2164. inline bool stream_line_reader::getline() {
  2165. fixed_buffer_used_size_ = 0;
  2166. glowable_buffer_.clear();
  2167. for (size_t i = 0;; i++) {
  2168. char byte;
  2169. auto n = strm_.read(&byte, 1);
  2170. if (n < 0) {
  2171. return false;
  2172. } else if (n == 0) {
  2173. if (i == 0) {
  2174. return false;
  2175. } else {
  2176. break;
  2177. }
  2178. }
  2179. append(byte);
  2180. if (byte == '\n') { break; }
  2181. }
  2182. return true;
  2183. }
  2184. inline void stream_line_reader::append(char c) {
  2185. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  2186. fixed_buffer_[fixed_buffer_used_size_++] = c;
  2187. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  2188. } else {
  2189. if (glowable_buffer_.empty()) {
  2190. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  2191. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  2192. }
  2193. glowable_buffer_ += c;
  2194. }
  2195. }
  2196. inline mmap::mmap(const char *path)
  2197. #if defined(_WIN32)
  2198. : hFile_(NULL), hMapping_(NULL)
  2199. #else
  2200. : fd_(-1)
  2201. #endif
  2202. ,
  2203. size_(0), addr_(nullptr) {
  2204. open(path);
  2205. }
  2206. inline mmap::~mmap() { close(); }
  2207. inline bool mmap::open(const char *path) {
  2208. close();
  2209. #if defined(_WIN32)
  2210. hFile_ = ::CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL,
  2211. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  2212. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  2213. size_ = ::GetFileSize(hFile_, NULL);
  2214. hMapping_ = ::CreateFileMapping(hFile_, NULL, PAGE_READONLY, 0, 0, NULL);
  2215. if (hMapping_ == NULL) {
  2216. close();
  2217. return false;
  2218. }
  2219. addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0);
  2220. #else
  2221. fd_ = ::open(path, O_RDONLY);
  2222. if (fd_ == -1) { return false; }
  2223. struct stat sb;
  2224. if (fstat(fd_, &sb) == -1) {
  2225. close();
  2226. return false;
  2227. }
  2228. size_ = static_cast<size_t>(sb.st_size);
  2229. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  2230. #endif
  2231. if (addr_ == nullptr) {
  2232. close();
  2233. return false;
  2234. }
  2235. return true;
  2236. }
  2237. inline bool mmap::is_open() const { return addr_ != nullptr; }
  2238. inline size_t mmap::size() const { return size_; }
  2239. inline const char *mmap::data() const {
  2240. return static_cast<const char *>(addr_);
  2241. }
  2242. inline void mmap::close() {
  2243. #if defined(_WIN32)
  2244. if (addr_) {
  2245. ::UnmapViewOfFile(addr_);
  2246. addr_ = nullptr;
  2247. }
  2248. if (hMapping_) {
  2249. ::CloseHandle(hMapping_);
  2250. hMapping_ = NULL;
  2251. }
  2252. if (hFile_ != INVALID_HANDLE_VALUE) {
  2253. ::CloseHandle(hFile_);
  2254. hFile_ = INVALID_HANDLE_VALUE;
  2255. }
  2256. #else
  2257. if (addr_ != nullptr) {
  2258. munmap(addr_, size_);
  2259. addr_ = nullptr;
  2260. }
  2261. if (fd_ != -1) {
  2262. ::close(fd_);
  2263. fd_ = -1;
  2264. }
  2265. #endif
  2266. size_ = 0;
  2267. }
  2268. inline int close_socket(socket_t sock) {
  2269. #ifdef _WIN32
  2270. return closesocket(sock);
  2271. #else
  2272. return close(sock);
  2273. #endif
  2274. }
  2275. template <typename T> inline ssize_t handle_EINTR(T fn) {
  2276. ssize_t res = 0;
  2277. while (true) {
  2278. res = fn();
  2279. if (res < 0 && errno == EINTR) { continue; }
  2280. break;
  2281. }
  2282. return res;
  2283. }
  2284. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  2285. return handle_EINTR([&]() {
  2286. return recv(sock,
  2287. #ifdef _WIN32
  2288. static_cast<char *>(ptr), static_cast<int>(size),
  2289. #else
  2290. ptr, size,
  2291. #endif
  2292. flags);
  2293. });
  2294. }
  2295. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  2296. int flags) {
  2297. return handle_EINTR([&]() {
  2298. return send(sock,
  2299. #ifdef _WIN32
  2300. static_cast<const char *>(ptr), static_cast<int>(size),
  2301. #else
  2302. ptr, size,
  2303. #endif
  2304. flags);
  2305. });
  2306. }
  2307. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  2308. #ifdef CPPHTTPLIB_USE_POLL
  2309. struct pollfd pfd_read;
  2310. pfd_read.fd = sock;
  2311. pfd_read.events = POLLIN;
  2312. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2313. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  2314. #else
  2315. #ifndef _WIN32
  2316. if (sock >= FD_SETSIZE) { return -1; }
  2317. #endif
  2318. fd_set fds;
  2319. FD_ZERO(&fds);
  2320. FD_SET(sock, &fds);
  2321. timeval tv;
  2322. tv.tv_sec = static_cast<long>(sec);
  2323. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2324. return handle_EINTR([&]() {
  2325. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  2326. });
  2327. #endif
  2328. }
  2329. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  2330. #ifdef CPPHTTPLIB_USE_POLL
  2331. struct pollfd pfd_read;
  2332. pfd_read.fd = sock;
  2333. pfd_read.events = POLLOUT;
  2334. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2335. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  2336. #else
  2337. #ifndef _WIN32
  2338. if (sock >= FD_SETSIZE) { return -1; }
  2339. #endif
  2340. fd_set fds;
  2341. FD_ZERO(&fds);
  2342. FD_SET(sock, &fds);
  2343. timeval tv;
  2344. tv.tv_sec = static_cast<long>(sec);
  2345. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2346. return handle_EINTR([&]() {
  2347. return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
  2348. });
  2349. #endif
  2350. }
  2351. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  2352. time_t usec) {
  2353. #ifdef CPPHTTPLIB_USE_POLL
  2354. struct pollfd pfd_read;
  2355. pfd_read.fd = sock;
  2356. pfd_read.events = POLLIN | POLLOUT;
  2357. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2358. auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  2359. if (poll_res == 0) { return Error::ConnectionTimeout; }
  2360. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  2361. auto error = 0;
  2362. socklen_t len = sizeof(error);
  2363. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2364. reinterpret_cast<char *>(&error), &len);
  2365. auto successful = res >= 0 && !error;
  2366. return successful ? Error::Success : Error::Connection;
  2367. }
  2368. return Error::Connection;
  2369. #else
  2370. #ifndef _WIN32
  2371. if (sock >= FD_SETSIZE) { return Error::Connection; }
  2372. #endif
  2373. fd_set fdsr;
  2374. FD_ZERO(&fdsr);
  2375. FD_SET(sock, &fdsr);
  2376. auto fdsw = fdsr;
  2377. auto fdse = fdsr;
  2378. timeval tv;
  2379. tv.tv_sec = static_cast<long>(sec);
  2380. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2381. auto ret = handle_EINTR([&]() {
  2382. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv);
  2383. });
  2384. if (ret == 0) { return Error::ConnectionTimeout; }
  2385. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  2386. auto error = 0;
  2387. socklen_t len = sizeof(error);
  2388. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2389. reinterpret_cast<char *>(&error), &len);
  2390. auto successful = res >= 0 && !error;
  2391. return successful ? Error::Success : Error::Connection;
  2392. }
  2393. return Error::Connection;
  2394. #endif
  2395. }
  2396. inline bool is_socket_alive(socket_t sock) {
  2397. const auto val = detail::select_read(sock, 0, 0);
  2398. if (val == 0) {
  2399. return true;
  2400. } else if (val < 0 && errno == EBADF) {
  2401. return false;
  2402. }
  2403. char buf[1];
  2404. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  2405. }
  2406. class SocketStream : public Stream {
  2407. public:
  2408. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2409. time_t write_timeout_sec, time_t write_timeout_usec);
  2410. ~SocketStream() override;
  2411. bool is_readable() const override;
  2412. bool is_writable() const override;
  2413. ssize_t read(char *ptr, size_t size) override;
  2414. ssize_t write(const char *ptr, size_t size) override;
  2415. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2416. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2417. socket_t socket() const override;
  2418. private:
  2419. socket_t sock_;
  2420. time_t read_timeout_sec_;
  2421. time_t read_timeout_usec_;
  2422. time_t write_timeout_sec_;
  2423. time_t write_timeout_usec_;
  2424. std::vector<char> read_buff_;
  2425. size_t read_buff_off_ = 0;
  2426. size_t read_buff_content_size_ = 0;
  2427. static const size_t read_buff_size_ = 1024l * 4;
  2428. };
  2429. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2430. class SSLSocketStream : public Stream {
  2431. public:
  2432. SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
  2433. time_t read_timeout_usec, time_t write_timeout_sec,
  2434. time_t write_timeout_usec);
  2435. ~SSLSocketStream() override;
  2436. bool is_readable() const override;
  2437. bool is_writable() const override;
  2438. ssize_t read(char *ptr, size_t size) override;
  2439. ssize_t write(const char *ptr, size_t size) override;
  2440. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2441. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2442. socket_t socket() const override;
  2443. private:
  2444. socket_t sock_;
  2445. SSL *ssl_;
  2446. time_t read_timeout_sec_;
  2447. time_t read_timeout_usec_;
  2448. time_t write_timeout_sec_;
  2449. time_t write_timeout_usec_;
  2450. };
  2451. #endif
  2452. inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) {
  2453. using namespace std::chrono;
  2454. auto start = steady_clock::now();
  2455. while (true) {
  2456. auto val = select_read(sock, 0, 10000);
  2457. if (val < 0) {
  2458. return false;
  2459. } else if (val == 0) {
  2460. auto current = steady_clock::now();
  2461. auto duration = duration_cast<milliseconds>(current - start);
  2462. auto timeout = keep_alive_timeout_sec * 1000;
  2463. if (duration.count() > timeout) { return false; }
  2464. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2465. } else {
  2466. return true;
  2467. }
  2468. }
  2469. }
  2470. template <typename T>
  2471. inline bool
  2472. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2473. size_t keep_alive_max_count,
  2474. time_t keep_alive_timeout_sec, T callback) {
  2475. assert(keep_alive_max_count > 0);
  2476. auto ret = false;
  2477. auto count = keep_alive_max_count;
  2478. while (svr_sock != INVALID_SOCKET && count > 0 &&
  2479. keep_alive(sock, keep_alive_timeout_sec)) {
  2480. auto close_connection = count == 1;
  2481. auto connection_closed = false;
  2482. ret = callback(close_connection, connection_closed);
  2483. if (!ret || connection_closed) { break; }
  2484. count--;
  2485. }
  2486. return ret;
  2487. }
  2488. template <typename T>
  2489. inline bool
  2490. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2491. size_t keep_alive_max_count,
  2492. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  2493. time_t read_timeout_usec, time_t write_timeout_sec,
  2494. time_t write_timeout_usec, T callback) {
  2495. return process_server_socket_core(
  2496. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  2497. [&](bool close_connection, bool &connection_closed) {
  2498. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2499. write_timeout_sec, write_timeout_usec);
  2500. return callback(strm, close_connection, connection_closed);
  2501. });
  2502. }
  2503. inline bool process_client_socket(socket_t sock, time_t read_timeout_sec,
  2504. time_t read_timeout_usec,
  2505. time_t write_timeout_sec,
  2506. time_t write_timeout_usec,
  2507. std::function<bool(Stream &)> callback) {
  2508. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2509. write_timeout_sec, write_timeout_usec);
  2510. return callback(strm);
  2511. }
  2512. inline int shutdown_socket(socket_t sock) {
  2513. #ifdef _WIN32
  2514. return shutdown(sock, SD_BOTH);
  2515. #else
  2516. return shutdown(sock, SHUT_RDWR);
  2517. #endif
  2518. }
  2519. template <typename BindOrConnect>
  2520. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  2521. int address_family, int socket_flags, bool tcp_nodelay,
  2522. SocketOptions socket_options,
  2523. BindOrConnect bind_or_connect) {
  2524. // Get address info
  2525. const char *node = nullptr;
  2526. struct addrinfo hints;
  2527. struct addrinfo *result;
  2528. memset(&hints, 0, sizeof(struct addrinfo));
  2529. hints.ai_socktype = SOCK_STREAM;
  2530. hints.ai_protocol = 0;
  2531. if (!ip.empty()) {
  2532. node = ip.c_str();
  2533. // Ask getaddrinfo to convert IP in c-string to address
  2534. hints.ai_family = AF_UNSPEC;
  2535. hints.ai_flags = AI_NUMERICHOST;
  2536. } else {
  2537. if (!host.empty()) { node = host.c_str(); }
  2538. hints.ai_family = address_family;
  2539. hints.ai_flags = socket_flags;
  2540. }
  2541. #ifndef _WIN32
  2542. if (hints.ai_family == AF_UNIX) {
  2543. const auto addrlen = host.length();
  2544. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  2545. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  2546. if (sock != INVALID_SOCKET) {
  2547. sockaddr_un addr{};
  2548. addr.sun_family = AF_UNIX;
  2549. std::copy(host.begin(), host.end(), addr.sun_path);
  2550. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  2551. hints.ai_addrlen = static_cast<socklen_t>(
  2552. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  2553. fcntl(sock, F_SETFD, FD_CLOEXEC);
  2554. if (socket_options) { socket_options(sock); }
  2555. if (!bind_or_connect(sock, hints)) {
  2556. close_socket(sock);
  2557. sock = INVALID_SOCKET;
  2558. }
  2559. }
  2560. return sock;
  2561. }
  2562. #endif
  2563. auto service = std::to_string(port);
  2564. if (getaddrinfo(node, service.c_str(), &hints, &result)) {
  2565. #if defined __linux__ && !defined __ANDROID__
  2566. res_init();
  2567. #endif
  2568. return INVALID_SOCKET;
  2569. }
  2570. for (auto rp = result; rp; rp = rp->ai_next) {
  2571. // Create a socket
  2572. #ifdef _WIN32
  2573. auto sock =
  2574. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  2575. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  2576. /**
  2577. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  2578. * and above the socket creation fails on older Windows Systems.
  2579. *
  2580. * Let's try to create a socket the old way in this case.
  2581. *
  2582. * Reference:
  2583. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  2584. *
  2585. * WSA_FLAG_NO_HANDLE_INHERIT:
  2586. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  2587. * SP1, and later
  2588. *
  2589. */
  2590. if (sock == INVALID_SOCKET) {
  2591. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  2592. }
  2593. #else
  2594. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  2595. #endif
  2596. if (sock == INVALID_SOCKET) { continue; }
  2597. #ifndef _WIN32
  2598. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  2599. close_socket(sock);
  2600. continue;
  2601. }
  2602. #endif
  2603. if (tcp_nodelay) {
  2604. auto yes = 1;
  2605. #ifdef _WIN32
  2606. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  2607. reinterpret_cast<const char *>(&yes), sizeof(yes));
  2608. #else
  2609. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  2610. reinterpret_cast<const void *>(&yes), sizeof(yes));
  2611. #endif
  2612. }
  2613. if (socket_options) { socket_options(sock); }
  2614. if (rp->ai_family == AF_INET6) {
  2615. auto no = 0;
  2616. #ifdef _WIN32
  2617. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
  2618. reinterpret_cast<const char *>(&no), sizeof(no));
  2619. #else
  2620. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
  2621. reinterpret_cast<const void *>(&no), sizeof(no));
  2622. #endif
  2623. }
  2624. // bind or connect
  2625. if (bind_or_connect(sock, *rp)) {
  2626. freeaddrinfo(result);
  2627. return sock;
  2628. }
  2629. close_socket(sock);
  2630. }
  2631. freeaddrinfo(result);
  2632. return INVALID_SOCKET;
  2633. }
  2634. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  2635. #ifdef _WIN32
  2636. auto flags = nonblocking ? 1UL : 0UL;
  2637. ioctlsocket(sock, FIONBIO, &flags);
  2638. #else
  2639. auto flags = fcntl(sock, F_GETFL, 0);
  2640. fcntl(sock, F_SETFL,
  2641. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  2642. #endif
  2643. }
  2644. inline bool is_connection_error() {
  2645. #ifdef _WIN32
  2646. return WSAGetLastError() != WSAEWOULDBLOCK;
  2647. #else
  2648. return errno != EINPROGRESS;
  2649. #endif
  2650. }
  2651. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  2652. struct addrinfo hints;
  2653. struct addrinfo *result;
  2654. memset(&hints, 0, sizeof(struct addrinfo));
  2655. hints.ai_family = AF_UNSPEC;
  2656. hints.ai_socktype = SOCK_STREAM;
  2657. hints.ai_protocol = 0;
  2658. if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; }
  2659. auto ret = false;
  2660. for (auto rp = result; rp; rp = rp->ai_next) {
  2661. const auto &ai = *rp;
  2662. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  2663. ret = true;
  2664. break;
  2665. }
  2666. }
  2667. freeaddrinfo(result);
  2668. return ret;
  2669. }
  2670. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  2671. #define USE_IF2IP
  2672. #endif
  2673. #ifdef USE_IF2IP
  2674. inline std::string if2ip(int address_family, const std::string &ifn) {
  2675. struct ifaddrs *ifap;
  2676. getifaddrs(&ifap);
  2677. std::string addr_candidate;
  2678. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  2679. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  2680. (AF_UNSPEC == address_family ||
  2681. ifa->ifa_addr->sa_family == address_family)) {
  2682. if (ifa->ifa_addr->sa_family == AF_INET) {
  2683. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  2684. char buf[INET_ADDRSTRLEN];
  2685. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  2686. freeifaddrs(ifap);
  2687. return std::string(buf, INET_ADDRSTRLEN);
  2688. }
  2689. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  2690. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  2691. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  2692. char buf[INET6_ADDRSTRLEN] = {};
  2693. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  2694. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  2695. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  2696. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  2697. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  2698. } else {
  2699. freeifaddrs(ifap);
  2700. return std::string(buf, INET6_ADDRSTRLEN);
  2701. }
  2702. }
  2703. }
  2704. }
  2705. }
  2706. }
  2707. freeifaddrs(ifap);
  2708. return addr_candidate;
  2709. }
  2710. #endif
  2711. inline socket_t create_client_socket(
  2712. const std::string &host, const std::string &ip, int port,
  2713. int address_family, bool tcp_nodelay, SocketOptions socket_options,
  2714. time_t connection_timeout_sec, time_t connection_timeout_usec,
  2715. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  2716. time_t write_timeout_usec, const std::string &intf, Error &error) {
  2717. auto sock = create_socket(
  2718. host, ip, port, address_family, 0, tcp_nodelay, std::move(socket_options),
  2719. [&](socket_t sock2, struct addrinfo &ai) -> bool {
  2720. if (!intf.empty()) {
  2721. #ifdef USE_IF2IP
  2722. auto ip_from_if = if2ip(address_family, intf);
  2723. if (ip_from_if.empty()) { ip_from_if = intf; }
  2724. if (!bind_ip_address(sock2, ip_from_if)) {
  2725. error = Error::BindIPAddress;
  2726. return false;
  2727. }
  2728. #endif
  2729. }
  2730. set_nonblocking(sock2, true);
  2731. auto ret =
  2732. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  2733. if (ret < 0) {
  2734. if (is_connection_error()) {
  2735. error = Error::Connection;
  2736. return false;
  2737. }
  2738. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  2739. connection_timeout_usec);
  2740. if (error != Error::Success) { return false; }
  2741. }
  2742. set_nonblocking(sock2, false);
  2743. {
  2744. #ifdef _WIN32
  2745. auto timeout = static_cast<uint32_t>(read_timeout_sec * 1000 +
  2746. read_timeout_usec / 1000);
  2747. setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO,
  2748. reinterpret_cast<const char *>(&timeout), sizeof(timeout));
  2749. #else
  2750. timeval tv;
  2751. tv.tv_sec = static_cast<long>(read_timeout_sec);
  2752. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec);
  2753. setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO,
  2754. reinterpret_cast<const void *>(&tv), sizeof(tv));
  2755. #endif
  2756. }
  2757. {
  2758. #ifdef _WIN32
  2759. auto timeout = static_cast<uint32_t>(write_timeout_sec * 1000 +
  2760. write_timeout_usec / 1000);
  2761. setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO,
  2762. reinterpret_cast<const char *>(&timeout), sizeof(timeout));
  2763. #else
  2764. timeval tv;
  2765. tv.tv_sec = static_cast<long>(write_timeout_sec);
  2766. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec);
  2767. setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO,
  2768. reinterpret_cast<const void *>(&tv), sizeof(tv));
  2769. #endif
  2770. }
  2771. error = Error::Success;
  2772. return true;
  2773. });
  2774. if (sock != INVALID_SOCKET) {
  2775. error = Error::Success;
  2776. } else {
  2777. if (error == Error::Success) { error = Error::Connection; }
  2778. }
  2779. return sock;
  2780. }
  2781. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  2782. socklen_t addr_len, std::string &ip, int &port) {
  2783. if (addr.ss_family == AF_INET) {
  2784. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  2785. } else if (addr.ss_family == AF_INET6) {
  2786. port =
  2787. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  2788. } else {
  2789. return false;
  2790. }
  2791. std::array<char, NI_MAXHOST> ipstr{};
  2792. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  2793. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  2794. 0, NI_NUMERICHOST)) {
  2795. return false;
  2796. }
  2797. ip = ipstr.data();
  2798. return true;
  2799. }
  2800. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  2801. struct sockaddr_storage addr;
  2802. socklen_t addr_len = sizeof(addr);
  2803. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  2804. &addr_len)) {
  2805. get_ip_and_port(addr, addr_len, ip, port);
  2806. }
  2807. }
  2808. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  2809. struct sockaddr_storage addr;
  2810. socklen_t addr_len = sizeof(addr);
  2811. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  2812. &addr_len)) {
  2813. #ifndef _WIN32
  2814. if (addr.ss_family == AF_UNIX) {
  2815. #if defined(__linux__)
  2816. struct ucred ucred;
  2817. socklen_t len = sizeof(ucred);
  2818. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  2819. port = ucred.pid;
  2820. }
  2821. #elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__
  2822. pid_t pid;
  2823. socklen_t len = sizeof(pid);
  2824. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  2825. port = pid;
  2826. }
  2827. #endif
  2828. return;
  2829. }
  2830. #endif
  2831. get_ip_and_port(addr, addr_len, ip, port);
  2832. }
  2833. }
  2834. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  2835. unsigned int h) {
  2836. return (l == 0)
  2837. ? h
  2838. : str2tag_core(
  2839. s + 1, l - 1,
  2840. // Unsets the 6 high bits of h, therefore no overflow happens
  2841. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  2842. h * 33) ^
  2843. static_cast<unsigned char>(*s));
  2844. }
  2845. inline unsigned int str2tag(const std::string &s) {
  2846. return str2tag_core(s.data(), s.size(), 0);
  2847. }
  2848. namespace udl {
  2849. inline constexpr unsigned int operator"" _t(const char *s, size_t l) {
  2850. return str2tag_core(s, l, 0);
  2851. }
  2852. } // namespace udl
  2853. inline std::string
  2854. find_content_type(const std::string &path,
  2855. const std::map<std::string, std::string> &user_data,
  2856. const std::string &default_content_type) {
  2857. auto ext = file_extension(path);
  2858. auto it = user_data.find(ext);
  2859. if (it != user_data.end()) { return it->second; }
  2860. using udl::operator""_t;
  2861. switch (str2tag(ext)) {
  2862. default: return default_content_type;
  2863. case "css"_t: return "text/css";
  2864. case "csv"_t: return "text/csv";
  2865. case "htm"_t:
  2866. case "html"_t: return "text/html";
  2867. case "js"_t:
  2868. case "mjs"_t: return "text/javascript";
  2869. case "txt"_t: return "text/plain";
  2870. case "vtt"_t: return "text/vtt";
  2871. case "apng"_t: return "image/apng";
  2872. case "avif"_t: return "image/avif";
  2873. case "bmp"_t: return "image/bmp";
  2874. case "gif"_t: return "image/gif";
  2875. case "png"_t: return "image/png";
  2876. case "svg"_t: return "image/svg+xml";
  2877. case "webp"_t: return "image/webp";
  2878. case "ico"_t: return "image/x-icon";
  2879. case "tif"_t: return "image/tiff";
  2880. case "tiff"_t: return "image/tiff";
  2881. case "jpg"_t:
  2882. case "jpeg"_t: return "image/jpeg";
  2883. case "mp4"_t: return "video/mp4";
  2884. case "mpeg"_t: return "video/mpeg";
  2885. case "webm"_t: return "video/webm";
  2886. case "mp3"_t: return "audio/mp3";
  2887. case "mpga"_t: return "audio/mpeg";
  2888. case "weba"_t: return "audio/webm";
  2889. case "wav"_t: return "audio/wave";
  2890. case "otf"_t: return "font/otf";
  2891. case "ttf"_t: return "font/ttf";
  2892. case "woff"_t: return "font/woff";
  2893. case "woff2"_t: return "font/woff2";
  2894. case "7z"_t: return "application/x-7z-compressed";
  2895. case "atom"_t: return "application/atom+xml";
  2896. case "pdf"_t: return "application/pdf";
  2897. case "json"_t: return "application/json";
  2898. case "rss"_t: return "application/rss+xml";
  2899. case "tar"_t: return "application/x-tar";
  2900. case "xht"_t:
  2901. case "xhtml"_t: return "application/xhtml+xml";
  2902. case "xslt"_t: return "application/xslt+xml";
  2903. case "xml"_t: return "application/xml";
  2904. case "gz"_t: return "application/gzip";
  2905. case "zip"_t: return "application/zip";
  2906. case "wasm"_t: return "application/wasm";
  2907. }
  2908. }
  2909. inline bool can_compress_content_type(const std::string &content_type) {
  2910. using udl::operator""_t;
  2911. auto tag = str2tag(content_type);
  2912. switch (tag) {
  2913. case "image/svg+xml"_t:
  2914. case "application/javascript"_t:
  2915. case "application/json"_t:
  2916. case "application/xml"_t:
  2917. case "application/protobuf"_t:
  2918. case "application/xhtml+xml"_t: return true;
  2919. default:
  2920. return !content_type.rfind("text/", 0) && tag != "text/event-stream"_t;
  2921. }
  2922. }
  2923. inline EncodingType encoding_type(const Request &req, const Response &res) {
  2924. auto ret =
  2925. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  2926. if (!ret) { return EncodingType::None; }
  2927. const auto &s = req.get_header_value("Accept-Encoding");
  2928. (void)(s);
  2929. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2930. // TODO: 'Accept-Encoding' has br, not br;q=0
  2931. ret = s.find("br") != std::string::npos;
  2932. if (ret) { return EncodingType::Brotli; }
  2933. #endif
  2934. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2935. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  2936. ret = s.find("gzip") != std::string::npos;
  2937. if (ret) { return EncodingType::Gzip; }
  2938. #endif
  2939. return EncodingType::None;
  2940. }
  2941. inline bool nocompressor::compress(const char *data, size_t data_length,
  2942. bool /*last*/, Callback callback) {
  2943. if (!data_length) { return true; }
  2944. return callback(data, data_length);
  2945. }
  2946. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2947. inline gzip_compressor::gzip_compressor() {
  2948. std::memset(&strm_, 0, sizeof(strm_));
  2949. strm_.zalloc = Z_NULL;
  2950. strm_.zfree = Z_NULL;
  2951. strm_.opaque = Z_NULL;
  2952. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  2953. Z_DEFAULT_STRATEGY) == Z_OK;
  2954. }
  2955. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  2956. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  2957. bool last, Callback callback) {
  2958. assert(is_valid_);
  2959. do {
  2960. constexpr size_t max_avail_in =
  2961. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  2962. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  2963. (std::min)(data_length, max_avail_in));
  2964. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  2965. data_length -= strm_.avail_in;
  2966. data += strm_.avail_in;
  2967. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  2968. auto ret = Z_OK;
  2969. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  2970. do {
  2971. strm_.avail_out = static_cast<uInt>(buff.size());
  2972. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  2973. ret = deflate(&strm_, flush);
  2974. if (ret == Z_STREAM_ERROR) { return false; }
  2975. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  2976. return false;
  2977. }
  2978. } while (strm_.avail_out == 0);
  2979. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  2980. (flush == Z_NO_FLUSH && ret == Z_OK));
  2981. assert(strm_.avail_in == 0);
  2982. } while (data_length > 0);
  2983. return true;
  2984. }
  2985. inline gzip_decompressor::gzip_decompressor() {
  2986. std::memset(&strm_, 0, sizeof(strm_));
  2987. strm_.zalloc = Z_NULL;
  2988. strm_.zfree = Z_NULL;
  2989. strm_.opaque = Z_NULL;
  2990. // 15 is the value of wbits, which should be at the maximum possible value
  2991. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  2992. // that the stream type should be automatically detected either gzip or
  2993. // deflate.
  2994. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  2995. }
  2996. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  2997. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  2998. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  2999. Callback callback) {
  3000. assert(is_valid_);
  3001. auto ret = Z_OK;
  3002. do {
  3003. constexpr size_t max_avail_in =
  3004. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3005. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3006. (std::min)(data_length, max_avail_in));
  3007. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3008. data_length -= strm_.avail_in;
  3009. data += strm_.avail_in;
  3010. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3011. while (strm_.avail_in > 0 && ret == Z_OK) {
  3012. strm_.avail_out = static_cast<uInt>(buff.size());
  3013. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3014. ret = inflate(&strm_, Z_NO_FLUSH);
  3015. assert(ret != Z_STREAM_ERROR);
  3016. switch (ret) {
  3017. case Z_NEED_DICT:
  3018. case Z_DATA_ERROR:
  3019. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  3020. }
  3021. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3022. return false;
  3023. }
  3024. }
  3025. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  3026. } while (data_length > 0);
  3027. return true;
  3028. }
  3029. #endif
  3030. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3031. inline brotli_compressor::brotli_compressor() {
  3032. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  3033. }
  3034. inline brotli_compressor::~brotli_compressor() {
  3035. BrotliEncoderDestroyInstance(state_);
  3036. }
  3037. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  3038. bool last, Callback callback) {
  3039. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3040. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  3041. auto available_in = data_length;
  3042. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3043. for (;;) {
  3044. if (last) {
  3045. if (BrotliEncoderIsFinished(state_)) { break; }
  3046. } else {
  3047. if (!available_in) { break; }
  3048. }
  3049. auto available_out = buff.size();
  3050. auto next_out = buff.data();
  3051. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  3052. &available_out, &next_out, nullptr)) {
  3053. return false;
  3054. }
  3055. auto output_bytes = buff.size() - available_out;
  3056. if (output_bytes) {
  3057. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  3058. }
  3059. }
  3060. return true;
  3061. }
  3062. inline brotli_decompressor::brotli_decompressor() {
  3063. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  3064. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  3065. : BROTLI_DECODER_RESULT_ERROR;
  3066. }
  3067. inline brotli_decompressor::~brotli_decompressor() {
  3068. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  3069. }
  3070. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  3071. inline bool brotli_decompressor::decompress(const char *data,
  3072. size_t data_length,
  3073. Callback callback) {
  3074. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3075. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  3076. return 0;
  3077. }
  3078. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3079. size_t avail_in = data_length;
  3080. size_t total_out;
  3081. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  3082. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3083. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  3084. char *next_out = buff.data();
  3085. size_t avail_out = buff.size();
  3086. decoder_r = BrotliDecoderDecompressStream(
  3087. decoder_s, &avail_in, &next_in, &avail_out,
  3088. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  3089. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  3090. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  3091. }
  3092. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3093. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  3094. }
  3095. #endif
  3096. inline bool has_header(const Headers &headers, const std::string &key) {
  3097. return headers.find(key) != headers.end();
  3098. }
  3099. inline const char *get_header_value(const Headers &headers,
  3100. const std::string &key, size_t id,
  3101. const char *def) {
  3102. auto rng = headers.equal_range(key);
  3103. auto it = rng.first;
  3104. std::advance(it, static_cast<ssize_t>(id));
  3105. if (it != rng.second) { return it->second.c_str(); }
  3106. return def;
  3107. }
  3108. inline bool compare_case_ignore(const std::string &a, const std::string &b) {
  3109. if (a.size() != b.size()) { return false; }
  3110. for (size_t i = 0; i < b.size(); i++) {
  3111. if (::tolower(a[i]) != ::tolower(b[i])) { return false; }
  3112. }
  3113. return true;
  3114. }
  3115. template <typename T>
  3116. inline bool parse_header(const char *beg, const char *end, T fn) {
  3117. // Skip trailing spaces and tabs.
  3118. while (beg < end && is_space_or_tab(end[-1])) {
  3119. end--;
  3120. }
  3121. auto p = beg;
  3122. while (p < end && *p != ':') {
  3123. p++;
  3124. }
  3125. if (p == end) { return false; }
  3126. auto key_end = p;
  3127. if (*p++ != ':') { return false; }
  3128. while (p < end && is_space_or_tab(*p)) {
  3129. p++;
  3130. }
  3131. if (p < end) {
  3132. auto key_len = key_end - beg;
  3133. if (!key_len) { return false; }
  3134. auto key = std::string(beg, key_end);
  3135. auto val = compare_case_ignore(key, "Location")
  3136. ? std::string(p, end)
  3137. : decode_url(std::string(p, end), false);
  3138. fn(std::move(key), std::move(val));
  3139. return true;
  3140. }
  3141. return false;
  3142. }
  3143. inline bool read_headers(Stream &strm, Headers &headers) {
  3144. const auto bufsiz = 2048;
  3145. char buf[bufsiz];
  3146. stream_line_reader line_reader(strm, buf, bufsiz);
  3147. for (;;) {
  3148. if (!line_reader.getline()) { return false; }
  3149. // Check if the line ends with CRLF.
  3150. auto line_terminator_len = 2;
  3151. if (line_reader.end_with_crlf()) {
  3152. // Blank line indicates end of headers.
  3153. if (line_reader.size() == 2) { break; }
  3154. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3155. } else {
  3156. // Blank line indicates end of headers.
  3157. if (line_reader.size() == 1) { break; }
  3158. line_terminator_len = 1;
  3159. }
  3160. #else
  3161. } else {
  3162. continue; // Skip invalid line.
  3163. }
  3164. #endif
  3165. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3166. // Exclude line terminator
  3167. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3168. parse_header(line_reader.ptr(), end,
  3169. [&](std::string &&key, std::string &&val) {
  3170. headers.emplace(std::move(key), std::move(val));
  3171. });
  3172. }
  3173. return true;
  3174. }
  3175. inline bool read_content_with_length(Stream &strm, uint64_t len,
  3176. Progress progress,
  3177. ContentReceiverWithProgress out) {
  3178. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3179. uint64_t r = 0;
  3180. while (r < len) {
  3181. auto read_len = static_cast<size_t>(len - r);
  3182. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3183. if (n <= 0) { return false; }
  3184. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  3185. r += static_cast<uint64_t>(n);
  3186. if (progress) {
  3187. if (!progress(r, len)) { return false; }
  3188. }
  3189. }
  3190. return true;
  3191. }
  3192. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  3193. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3194. uint64_t r = 0;
  3195. while (r < len) {
  3196. auto read_len = static_cast<size_t>(len - r);
  3197. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3198. if (n <= 0) { return; }
  3199. r += static_cast<uint64_t>(n);
  3200. }
  3201. }
  3202. inline bool read_content_without_length(Stream &strm,
  3203. ContentReceiverWithProgress out) {
  3204. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3205. uint64_t r = 0;
  3206. for (;;) {
  3207. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  3208. if (n <= 0) { return true; }
  3209. if (!out(buf, static_cast<size_t>(n), r, 0)) { return false; }
  3210. r += static_cast<uint64_t>(n);
  3211. }
  3212. return true;
  3213. }
  3214. template <typename T>
  3215. inline bool read_content_chunked(Stream &strm, T &x,
  3216. ContentReceiverWithProgress out) {
  3217. const auto bufsiz = 16;
  3218. char buf[bufsiz];
  3219. stream_line_reader line_reader(strm, buf, bufsiz);
  3220. if (!line_reader.getline()) { return false; }
  3221. unsigned long chunk_len;
  3222. while (true) {
  3223. char *end_ptr;
  3224. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  3225. if (end_ptr == line_reader.ptr()) { return false; }
  3226. if (chunk_len == ULONG_MAX) { return false; }
  3227. if (chunk_len == 0) { break; }
  3228. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  3229. return false;
  3230. }
  3231. if (!line_reader.getline()) { return false; }
  3232. if (strcmp(line_reader.ptr(), "\r\n") != 0) { return false; }
  3233. if (!line_reader.getline()) { return false; }
  3234. }
  3235. assert(chunk_len == 0);
  3236. // Trailer
  3237. if (!line_reader.getline()) { return false; }
  3238. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3239. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3240. // Exclude line terminator
  3241. constexpr auto line_terminator_len = 2;
  3242. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3243. parse_header(line_reader.ptr(), end,
  3244. [&](std::string &&key, std::string &&val) {
  3245. x.headers.emplace(std::move(key), std::move(val));
  3246. });
  3247. if (!line_reader.getline()) { return false; }
  3248. }
  3249. return true;
  3250. }
  3251. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  3252. return compare_case_ignore(
  3253. get_header_value(headers, "Transfer-Encoding", 0, ""), "chunked");
  3254. }
  3255. template <typename T, typename U>
  3256. bool prepare_content_receiver(T &x, int &status,
  3257. ContentReceiverWithProgress receiver,
  3258. bool decompress, U callback) {
  3259. if (decompress) {
  3260. std::string encoding = x.get_header_value("Content-Encoding");
  3261. std::unique_ptr<decompressor> decompressor;
  3262. if (encoding == "gzip" || encoding == "deflate") {
  3263. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3264. decompressor = detail::make_unique<gzip_decompressor>();
  3265. #else
  3266. status = StatusCode::UnsupportedMediaType_415;
  3267. return false;
  3268. #endif
  3269. } else if (encoding.find("br") != std::string::npos) {
  3270. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3271. decompressor = detail::make_unique<brotli_decompressor>();
  3272. #else
  3273. status = StatusCode::UnsupportedMediaType_415;
  3274. return false;
  3275. #endif
  3276. }
  3277. if (decompressor) {
  3278. if (decompressor->is_valid()) {
  3279. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  3280. uint64_t off, uint64_t len) {
  3281. return decompressor->decompress(buf, n,
  3282. [&](const char *buf2, size_t n2) {
  3283. return receiver(buf2, n2, off, len);
  3284. });
  3285. };
  3286. return callback(std::move(out));
  3287. } else {
  3288. status = StatusCode::InternalServerError_500;
  3289. return false;
  3290. }
  3291. }
  3292. }
  3293. ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off,
  3294. uint64_t len) {
  3295. return receiver(buf, n, off, len);
  3296. };
  3297. return callback(std::move(out));
  3298. }
  3299. template <typename T>
  3300. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  3301. Progress progress, ContentReceiverWithProgress receiver,
  3302. bool decompress) {
  3303. return prepare_content_receiver(
  3304. x, status, std::move(receiver), decompress,
  3305. [&](const ContentReceiverWithProgress &out) {
  3306. auto ret = true;
  3307. auto exceed_payload_max_length = false;
  3308. if (is_chunked_transfer_encoding(x.headers)) {
  3309. ret = read_content_chunked(strm, x, out);
  3310. } else if (!has_header(x.headers, "Content-Length")) {
  3311. ret = read_content_without_length(strm, out);
  3312. } else {
  3313. auto len = get_header_value_u64(x.headers, "Content-Length", 0, 0);
  3314. if (len > payload_max_length) {
  3315. exceed_payload_max_length = true;
  3316. skip_content_with_length(strm, len);
  3317. ret = false;
  3318. } else if (len > 0) {
  3319. ret = read_content_with_length(strm, len, std::move(progress), out);
  3320. }
  3321. }
  3322. if (!ret) {
  3323. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  3324. : StatusCode::BadRequest_400;
  3325. }
  3326. return ret;
  3327. });
  3328. } // namespace detail
  3329. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  3330. ssize_t write_len = 0;
  3331. for (const auto &x : headers) {
  3332. auto len =
  3333. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  3334. if (len < 0) { return len; }
  3335. write_len += len;
  3336. }
  3337. auto len = strm.write("\r\n");
  3338. if (len < 0) { return len; }
  3339. write_len += len;
  3340. return write_len;
  3341. }
  3342. inline bool write_data(Stream &strm, const char *d, size_t l) {
  3343. size_t offset = 0;
  3344. while (offset < l) {
  3345. auto length = strm.write(d + offset, l - offset);
  3346. if (length < 0) { return false; }
  3347. offset += static_cast<size_t>(length);
  3348. }
  3349. return true;
  3350. }
  3351. template <typename T>
  3352. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  3353. size_t offset, size_t length, T is_shutting_down,
  3354. Error &error) {
  3355. size_t end_offset = offset + length;
  3356. auto ok = true;
  3357. DataSink data_sink;
  3358. data_sink.write = [&](const char *d, size_t l) -> bool {
  3359. if (ok) {
  3360. if (strm.is_writable() && write_data(strm, d, l)) {
  3361. offset += l;
  3362. } else {
  3363. ok = false;
  3364. }
  3365. }
  3366. return ok;
  3367. };
  3368. data_sink.is_writable = [&]() -> bool { return strm.is_writable(); };
  3369. while (offset < end_offset && !is_shutting_down()) {
  3370. if (!strm.is_writable()) {
  3371. error = Error::Write;
  3372. return false;
  3373. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  3374. error = Error::Canceled;
  3375. return false;
  3376. } else if (!ok) {
  3377. error = Error::Write;
  3378. return false;
  3379. }
  3380. }
  3381. error = Error::Success;
  3382. return true;
  3383. }
  3384. template <typename T>
  3385. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  3386. size_t offset, size_t length,
  3387. const T &is_shutting_down) {
  3388. auto error = Error::Success;
  3389. return write_content(strm, content_provider, offset, length, is_shutting_down,
  3390. error);
  3391. }
  3392. template <typename T>
  3393. inline bool
  3394. write_content_without_length(Stream &strm,
  3395. const ContentProvider &content_provider,
  3396. const T &is_shutting_down) {
  3397. size_t offset = 0;
  3398. auto data_available = true;
  3399. auto ok = true;
  3400. DataSink data_sink;
  3401. data_sink.write = [&](const char *d, size_t l) -> bool {
  3402. if (ok) {
  3403. offset += l;
  3404. if (!strm.is_writable() || !write_data(strm, d, l)) { ok = false; }
  3405. }
  3406. return ok;
  3407. };
  3408. data_sink.is_writable = [&]() -> bool { return strm.is_writable(); };
  3409. data_sink.done = [&](void) { data_available = false; };
  3410. while (data_available && !is_shutting_down()) {
  3411. if (!strm.is_writable()) {
  3412. return false;
  3413. } else if (!content_provider(offset, 0, data_sink)) {
  3414. return false;
  3415. } else if (!ok) {
  3416. return false;
  3417. }
  3418. }
  3419. return true;
  3420. }
  3421. template <typename T, typename U>
  3422. inline bool
  3423. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  3424. const T &is_shutting_down, U &compressor, Error &error) {
  3425. size_t offset = 0;
  3426. auto data_available = true;
  3427. auto ok = true;
  3428. DataSink data_sink;
  3429. data_sink.write = [&](const char *d, size_t l) -> bool {
  3430. if (ok) {
  3431. data_available = l > 0;
  3432. offset += l;
  3433. std::string payload;
  3434. if (compressor.compress(d, l, false,
  3435. [&](const char *data, size_t data_len) {
  3436. payload.append(data, data_len);
  3437. return true;
  3438. })) {
  3439. if (!payload.empty()) {
  3440. // Emit chunked response header and footer for each chunk
  3441. auto chunk =
  3442. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  3443. if (!strm.is_writable() ||
  3444. !write_data(strm, chunk.data(), chunk.size())) {
  3445. ok = false;
  3446. }
  3447. }
  3448. } else {
  3449. ok = false;
  3450. }
  3451. }
  3452. return ok;
  3453. };
  3454. data_sink.is_writable = [&]() -> bool { return strm.is_writable(); };
  3455. auto done_with_trailer = [&](const Headers *trailer) {
  3456. if (!ok) { return; }
  3457. data_available = false;
  3458. std::string payload;
  3459. if (!compressor.compress(nullptr, 0, true,
  3460. [&](const char *data, size_t data_len) {
  3461. payload.append(data, data_len);
  3462. return true;
  3463. })) {
  3464. ok = false;
  3465. return;
  3466. }
  3467. if (!payload.empty()) {
  3468. // Emit chunked response header and footer for each chunk
  3469. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  3470. if (!strm.is_writable() ||
  3471. !write_data(strm, chunk.data(), chunk.size())) {
  3472. ok = false;
  3473. return;
  3474. }
  3475. }
  3476. static const std::string done_marker("0\r\n");
  3477. if (!write_data(strm, done_marker.data(), done_marker.size())) {
  3478. ok = false;
  3479. }
  3480. // Trailer
  3481. if (trailer) {
  3482. for (const auto &kv : *trailer) {
  3483. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  3484. if (!write_data(strm, field_line.data(), field_line.size())) {
  3485. ok = false;
  3486. }
  3487. }
  3488. }
  3489. static const std::string crlf("\r\n");
  3490. if (!write_data(strm, crlf.data(), crlf.size())) { ok = false; }
  3491. };
  3492. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  3493. data_sink.done_with_trailer = [&](const Headers &trailer) {
  3494. done_with_trailer(&trailer);
  3495. };
  3496. while (data_available && !is_shutting_down()) {
  3497. if (!strm.is_writable()) {
  3498. error = Error::Write;
  3499. return false;
  3500. } else if (!content_provider(offset, 0, data_sink)) {
  3501. error = Error::Canceled;
  3502. return false;
  3503. } else if (!ok) {
  3504. error = Error::Write;
  3505. return false;
  3506. }
  3507. }
  3508. error = Error::Success;
  3509. return true;
  3510. }
  3511. template <typename T, typename U>
  3512. inline bool write_content_chunked(Stream &strm,
  3513. const ContentProvider &content_provider,
  3514. const T &is_shutting_down, U &compressor) {
  3515. auto error = Error::Success;
  3516. return write_content_chunked(strm, content_provider, is_shutting_down,
  3517. compressor, error);
  3518. }
  3519. template <typename T>
  3520. inline bool redirect(T &cli, Request &req, Response &res,
  3521. const std::string &path, const std::string &location,
  3522. Error &error) {
  3523. Request new_req = req;
  3524. new_req.path = path;
  3525. new_req.redirect_count_ -= 1;
  3526. if (res.status == StatusCode::SeeOther_303 &&
  3527. (req.method != "GET" && req.method != "HEAD")) {
  3528. new_req.method = "GET";
  3529. new_req.body.clear();
  3530. new_req.headers.clear();
  3531. }
  3532. Response new_res;
  3533. auto ret = cli.send(new_req, new_res, error);
  3534. if (ret) {
  3535. req = new_req;
  3536. res = new_res;
  3537. if (res.location.empty()) { res.location = location; }
  3538. }
  3539. return ret;
  3540. }
  3541. inline std::string params_to_query_str(const Params &params) {
  3542. std::string query;
  3543. for (auto it = params.begin(); it != params.end(); ++it) {
  3544. if (it != params.begin()) { query += "&"; }
  3545. query += it->first;
  3546. query += "=";
  3547. query += encode_query_param(it->second);
  3548. }
  3549. return query;
  3550. }
  3551. inline void parse_query_text(const std::string &s, Params &params) {
  3552. std::set<std::string> cache;
  3553. split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) {
  3554. std::string kv(b, e);
  3555. if (cache.find(kv) != cache.end()) { return; }
  3556. cache.insert(kv);
  3557. std::string key;
  3558. std::string val;
  3559. split(b, e, '=', [&](const char *b2, const char *e2) {
  3560. if (key.empty()) {
  3561. key.assign(b2, e2);
  3562. } else {
  3563. val.assign(b2, e2);
  3564. }
  3565. });
  3566. if (!key.empty()) {
  3567. params.emplace(decode_url(key, true), decode_url(val, true));
  3568. }
  3569. });
  3570. }
  3571. inline bool parse_multipart_boundary(const std::string &content_type,
  3572. std::string &boundary) {
  3573. auto boundary_keyword = "boundary=";
  3574. auto pos = content_type.find(boundary_keyword);
  3575. if (pos == std::string::npos) { return false; }
  3576. auto end = content_type.find(';', pos);
  3577. auto beg = pos + strlen(boundary_keyword);
  3578. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  3579. return !boundary.empty();
  3580. }
  3581. inline void parse_disposition_params(const std::string &s, Params &params) {
  3582. std::set<std::string> cache;
  3583. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  3584. std::string kv(b, e);
  3585. if (cache.find(kv) != cache.end()) { return; }
  3586. cache.insert(kv);
  3587. std::string key;
  3588. std::string val;
  3589. split(b, e, '=', [&](const char *b2, const char *e2) {
  3590. if (key.empty()) {
  3591. key.assign(b2, e2);
  3592. } else {
  3593. val.assign(b2, e2);
  3594. }
  3595. });
  3596. if (!key.empty()) {
  3597. params.emplace(trim_double_quotes_copy((key)),
  3598. trim_double_quotes_copy((val)));
  3599. }
  3600. });
  3601. }
  3602. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  3603. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  3604. #else
  3605. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  3606. #endif
  3607. static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  3608. std::smatch m;
  3609. if (std::regex_match(s, m, re_first_range)) {
  3610. auto pos = static_cast<size_t>(m.position(1));
  3611. auto len = static_cast<size_t>(m.length(1));
  3612. auto all_valid_ranges = true;
  3613. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  3614. if (!all_valid_ranges) { return; }
  3615. static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
  3616. std::cmatch cm;
  3617. if (std::regex_match(b, e, cm, re_another_range)) {
  3618. ssize_t first = -1;
  3619. if (!cm.str(1).empty()) {
  3620. first = static_cast<ssize_t>(std::stoll(cm.str(1)));
  3621. }
  3622. ssize_t last = -1;
  3623. if (!cm.str(2).empty()) {
  3624. last = static_cast<ssize_t>(std::stoll(cm.str(2)));
  3625. }
  3626. if (first != -1 && last != -1 && first > last) {
  3627. all_valid_ranges = false;
  3628. return;
  3629. }
  3630. ranges.emplace_back(std::make_pair(first, last));
  3631. }
  3632. });
  3633. return all_valid_ranges;
  3634. }
  3635. return false;
  3636. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  3637. }
  3638. #else
  3639. } catch (...) { return false; }
  3640. #endif
  3641. class MultipartFormDataParser {
  3642. public:
  3643. MultipartFormDataParser() = default;
  3644. void set_boundary(std::string &&boundary) {
  3645. boundary_ = boundary;
  3646. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  3647. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  3648. }
  3649. bool is_valid() const { return is_valid_; }
  3650. bool parse(const char *buf, size_t n, const ContentReceiver &content_callback,
  3651. const MultipartContentHeader &header_callback) {
  3652. buf_append(buf, n);
  3653. while (buf_size() > 0) {
  3654. switch (state_) {
  3655. case 0: { // Initial boundary
  3656. buf_erase(buf_find(dash_boundary_crlf_));
  3657. if (dash_boundary_crlf_.size() > buf_size()) { return true; }
  3658. if (!buf_start_with(dash_boundary_crlf_)) { return false; }
  3659. buf_erase(dash_boundary_crlf_.size());
  3660. state_ = 1;
  3661. break;
  3662. }
  3663. case 1: { // New entry
  3664. clear_file_info();
  3665. state_ = 2;
  3666. break;
  3667. }
  3668. case 2: { // Headers
  3669. auto pos = buf_find(crlf_);
  3670. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3671. while (pos < buf_size()) {
  3672. // Empty line
  3673. if (pos == 0) {
  3674. if (!header_callback(file_)) {
  3675. is_valid_ = false;
  3676. return false;
  3677. }
  3678. buf_erase(crlf_.size());
  3679. state_ = 3;
  3680. break;
  3681. }
  3682. const auto header = buf_head(pos);
  3683. if (!parse_header(header.data(), header.data() + header.size(),
  3684. [&](std::string &&, std::string &&) {})) {
  3685. is_valid_ = false;
  3686. return false;
  3687. }
  3688. static const std::string header_content_type = "Content-Type:";
  3689. if (start_with_case_ignore(header, header_content_type)) {
  3690. file_.content_type =
  3691. trim_copy(header.substr(header_content_type.size()));
  3692. } else {
  3693. static const std::regex re_content_disposition(
  3694. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  3695. std::regex_constants::icase);
  3696. std::smatch m;
  3697. if (std::regex_match(header, m, re_content_disposition)) {
  3698. Params params;
  3699. parse_disposition_params(m[1], params);
  3700. auto it = params.find("name");
  3701. if (it != params.end()) {
  3702. file_.name = it->second;
  3703. } else {
  3704. is_valid_ = false;
  3705. return false;
  3706. }
  3707. it = params.find("filename");
  3708. if (it != params.end()) { file_.filename = it->second; }
  3709. it = params.find("filename*");
  3710. if (it != params.end()) {
  3711. // Only allow UTF-8 enconnding...
  3712. static const std::regex re_rfc5987_encoding(
  3713. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  3714. std::smatch m2;
  3715. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  3716. file_.filename = decode_url(m2[1], false); // override...
  3717. } else {
  3718. is_valid_ = false;
  3719. return false;
  3720. }
  3721. }
  3722. }
  3723. }
  3724. buf_erase(pos + crlf_.size());
  3725. pos = buf_find(crlf_);
  3726. }
  3727. if (state_ != 3) { return true; }
  3728. break;
  3729. }
  3730. case 3: { // Body
  3731. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  3732. auto pos = buf_find(crlf_dash_boundary_);
  3733. if (pos < buf_size()) {
  3734. if (!content_callback(buf_data(), pos)) {
  3735. is_valid_ = false;
  3736. return false;
  3737. }
  3738. buf_erase(pos + crlf_dash_boundary_.size());
  3739. state_ = 4;
  3740. } else {
  3741. auto len = buf_size() - crlf_dash_boundary_.size();
  3742. if (len > 0) {
  3743. if (!content_callback(buf_data(), len)) {
  3744. is_valid_ = false;
  3745. return false;
  3746. }
  3747. buf_erase(len);
  3748. }
  3749. return true;
  3750. }
  3751. break;
  3752. }
  3753. case 4: { // Boundary
  3754. if (crlf_.size() > buf_size()) { return true; }
  3755. if (buf_start_with(crlf_)) {
  3756. buf_erase(crlf_.size());
  3757. state_ = 1;
  3758. } else {
  3759. if (dash_.size() > buf_size()) { return true; }
  3760. if (buf_start_with(dash_)) {
  3761. buf_erase(dash_.size());
  3762. is_valid_ = true;
  3763. buf_erase(buf_size()); // Remove epilogue
  3764. } else {
  3765. return true;
  3766. }
  3767. }
  3768. break;
  3769. }
  3770. }
  3771. }
  3772. return true;
  3773. }
  3774. private:
  3775. void clear_file_info() {
  3776. file_.name.clear();
  3777. file_.filename.clear();
  3778. file_.content_type.clear();
  3779. }
  3780. bool start_with_case_ignore(const std::string &a,
  3781. const std::string &b) const {
  3782. if (a.size() < b.size()) { return false; }
  3783. for (size_t i = 0; i < b.size(); i++) {
  3784. if (::tolower(a[i]) != ::tolower(b[i])) { return false; }
  3785. }
  3786. return true;
  3787. }
  3788. const std::string dash_ = "--";
  3789. const std::string crlf_ = "\r\n";
  3790. std::string boundary_;
  3791. std::string dash_boundary_crlf_;
  3792. std::string crlf_dash_boundary_;
  3793. size_t state_ = 0;
  3794. bool is_valid_ = false;
  3795. MultipartFormData file_;
  3796. // Buffer
  3797. bool start_with(const std::string &a, size_t spos, size_t epos,
  3798. const std::string &b) const {
  3799. if (epos - spos < b.size()) { return false; }
  3800. for (size_t i = 0; i < b.size(); i++) {
  3801. if (a[i + spos] != b[i]) { return false; }
  3802. }
  3803. return true;
  3804. }
  3805. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  3806. const char *buf_data() const { return &buf_[buf_spos_]; }
  3807. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  3808. bool buf_start_with(const std::string &s) const {
  3809. return start_with(buf_, buf_spos_, buf_epos_, s);
  3810. }
  3811. size_t buf_find(const std::string &s) const {
  3812. auto c = s.front();
  3813. size_t off = buf_spos_;
  3814. while (off < buf_epos_) {
  3815. auto pos = off;
  3816. while (true) {
  3817. if (pos == buf_epos_) { return buf_size(); }
  3818. if (buf_[pos] == c) { break; }
  3819. pos++;
  3820. }
  3821. auto remaining_size = buf_epos_ - pos;
  3822. if (s.size() > remaining_size) { return buf_size(); }
  3823. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  3824. off = pos + 1;
  3825. }
  3826. return buf_size();
  3827. }
  3828. void buf_append(const char *data, size_t n) {
  3829. auto remaining_size = buf_size();
  3830. if (remaining_size > 0 && buf_spos_ > 0) {
  3831. for (size_t i = 0; i < remaining_size; i++) {
  3832. buf_[i] = buf_[buf_spos_ + i];
  3833. }
  3834. }
  3835. buf_spos_ = 0;
  3836. buf_epos_ = remaining_size;
  3837. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  3838. for (size_t i = 0; i < n; i++) {
  3839. buf_[buf_epos_ + i] = data[i];
  3840. }
  3841. buf_epos_ += n;
  3842. }
  3843. void buf_erase(size_t size) { buf_spos_ += size; }
  3844. std::string buf_;
  3845. size_t buf_spos_ = 0;
  3846. size_t buf_epos_ = 0;
  3847. };
  3848. inline std::string to_lower(const char *beg, const char *end) {
  3849. std::string out;
  3850. auto it = beg;
  3851. while (it != end) {
  3852. out += static_cast<char>(::tolower(*it));
  3853. it++;
  3854. }
  3855. return out;
  3856. }
  3857. inline std::string random_string(size_t length) {
  3858. static const char data[] =
  3859. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  3860. // std::random_device might actually be deterministic on some
  3861. // platforms, but due to lack of support in the c++ standard library,
  3862. // doing better requires either some ugly hacks or breaking portability.
  3863. static std::random_device seed_gen;
  3864. // Request 128 bits of entropy for initialization
  3865. static std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(),
  3866. seed_gen()};
  3867. static std::mt19937 engine(seed_sequence);
  3868. std::string result;
  3869. for (size_t i = 0; i < length; i++) {
  3870. result += data[engine() % (sizeof(data) - 1)];
  3871. }
  3872. return result;
  3873. }
  3874. inline std::string make_multipart_data_boundary() {
  3875. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  3876. }
  3877. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  3878. auto valid = true;
  3879. for (size_t i = 0; i < boundary.size(); i++) {
  3880. auto c = boundary[i];
  3881. if (!std::isalnum(c) && c != '-' && c != '_') {
  3882. valid = false;
  3883. break;
  3884. }
  3885. }
  3886. return valid;
  3887. }
  3888. template <typename T>
  3889. inline std::string
  3890. serialize_multipart_formdata_item_begin(const T &item,
  3891. const std::string &boundary) {
  3892. std::string body = "--" + boundary + "\r\n";
  3893. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3894. if (!item.filename.empty()) {
  3895. body += "; filename=\"" + item.filename + "\"";
  3896. }
  3897. body += "\r\n";
  3898. if (!item.content_type.empty()) {
  3899. body += "Content-Type: " + item.content_type + "\r\n";
  3900. }
  3901. body += "\r\n";
  3902. return body;
  3903. }
  3904. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  3905. inline std::string
  3906. serialize_multipart_formdata_finish(const std::string &boundary) {
  3907. return "--" + boundary + "--\r\n";
  3908. }
  3909. inline std::string
  3910. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  3911. return "multipart/form-data; boundary=" + boundary;
  3912. }
  3913. inline std::string
  3914. serialize_multipart_formdata(const MultipartFormDataItems &items,
  3915. const std::string &boundary, bool finish = true) {
  3916. std::string body;
  3917. for (const auto &item : items) {
  3918. body += serialize_multipart_formdata_item_begin(item, boundary);
  3919. body += item.content + serialize_multipart_formdata_item_end();
  3920. }
  3921. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  3922. return body;
  3923. }
  3924. inline bool range_error(Request &req, Response &res) {
  3925. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  3926. ssize_t contant_len = static_cast<ssize_t>(
  3927. res.content_length_ ? res.content_length_ : res.body.size());
  3928. ssize_t prev_first_pos = -1;
  3929. ssize_t prev_last_pos = -1;
  3930. size_t overwrapping_count = 0;
  3931. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  3932. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  3933. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  3934. // Too many ranges
  3935. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  3936. for (auto &r : req.ranges) {
  3937. auto &first_pos = r.first;
  3938. auto &last_pos = r.second;
  3939. if (first_pos == -1 && last_pos == -1) {
  3940. first_pos = 0;
  3941. last_pos = contant_len;
  3942. }
  3943. if (first_pos == -1) {
  3944. first_pos = contant_len - last_pos;
  3945. last_pos = contant_len - 1;
  3946. }
  3947. if (last_pos == -1) { last_pos = contant_len - 1; }
  3948. // Range must be within content length
  3949. if (!(0 <= first_pos && first_pos <= last_pos &&
  3950. last_pos <= contant_len - 1)) {
  3951. return true;
  3952. }
  3953. // Ranges must be in ascending order
  3954. if (first_pos <= prev_first_pos) { return true; }
  3955. // Request must not have more than two overlapping ranges
  3956. if (first_pos <= prev_last_pos) {
  3957. overwrapping_count++;
  3958. if (overwrapping_count > 2) { return true; }
  3959. }
  3960. prev_first_pos = (std::max)(prev_first_pos, first_pos);
  3961. prev_last_pos = (std::max)(prev_last_pos, last_pos);
  3962. }
  3963. }
  3964. return false;
  3965. }
  3966. inline std::pair<size_t, size_t>
  3967. get_range_offset_and_length(Range r, size_t content_length) {
  3968. assert(r.first != -1 && r.second != -1);
  3969. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  3970. assert(r.first <= r.second &&
  3971. r.second < static_cast<ssize_t>(content_length));
  3972. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  3973. }
  3974. inline std::string make_content_range_header_field(
  3975. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  3976. auto st = offset_and_length.first;
  3977. auto ed = st + offset_and_length.second - 1;
  3978. std::string field = "bytes ";
  3979. field += std::to_string(st);
  3980. field += "-";
  3981. field += std::to_string(ed);
  3982. field += "/";
  3983. field += std::to_string(content_length);
  3984. return field;
  3985. }
  3986. template <typename SToken, typename CToken, typename Content>
  3987. bool process_multipart_ranges_data(const Request &req,
  3988. const std::string &boundary,
  3989. const std::string &content_type,
  3990. size_t content_length, SToken stoken,
  3991. CToken ctoken, Content content) {
  3992. for (size_t i = 0; i < req.ranges.size(); i++) {
  3993. ctoken("--");
  3994. stoken(boundary);
  3995. ctoken("\r\n");
  3996. if (!content_type.empty()) {
  3997. ctoken("Content-Type: ");
  3998. stoken(content_type);
  3999. ctoken("\r\n");
  4000. }
  4001. auto offset_and_length =
  4002. get_range_offset_and_length(req.ranges[i], content_length);
  4003. ctoken("Content-Range: ");
  4004. stoken(make_content_range_header_field(offset_and_length, content_length));
  4005. ctoken("\r\n");
  4006. ctoken("\r\n");
  4007. if (!content(offset_and_length.first, offset_and_length.second)) {
  4008. return false;
  4009. }
  4010. ctoken("\r\n");
  4011. }
  4012. ctoken("--");
  4013. stoken(boundary);
  4014. ctoken("--");
  4015. return true;
  4016. }
  4017. inline void make_multipart_ranges_data(const Request &req, Response &res,
  4018. const std::string &boundary,
  4019. const std::string &content_type,
  4020. size_t content_length,
  4021. std::string &data) {
  4022. process_multipart_ranges_data(
  4023. req, boundary, content_type, content_length,
  4024. [&](const std::string &token) { data += token; },
  4025. [&](const std::string &token) { data += token; },
  4026. [&](size_t offset, size_t length) {
  4027. assert(offset + length <= content_length);
  4028. data += res.body.substr(offset, length);
  4029. return true;
  4030. });
  4031. }
  4032. inline size_t get_multipart_ranges_data_length(const Request &req,
  4033. const std::string &boundary,
  4034. const std::string &content_type,
  4035. size_t content_length) {
  4036. size_t data_length = 0;
  4037. process_multipart_ranges_data(
  4038. req, boundary, content_type, content_length,
  4039. [&](const std::string &token) { data_length += token.size(); },
  4040. [&](const std::string &token) { data_length += token.size(); },
  4041. [&](size_t /*offset*/, size_t length) {
  4042. data_length += length;
  4043. return true;
  4044. });
  4045. return data_length;
  4046. }
  4047. template <typename T>
  4048. inline bool
  4049. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  4050. const std::string &boundary,
  4051. const std::string &content_type,
  4052. size_t content_length, const T &is_shutting_down) {
  4053. return process_multipart_ranges_data(
  4054. req, boundary, content_type, content_length,
  4055. [&](const std::string &token) { strm.write(token); },
  4056. [&](const std::string &token) { strm.write(token); },
  4057. [&](size_t offset, size_t length) {
  4058. return write_content(strm, res.content_provider_, offset, length,
  4059. is_shutting_down);
  4060. });
  4061. }
  4062. inline bool expect_content(const Request &req) {
  4063. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  4064. req.method == "PRI" || req.method == "DELETE") {
  4065. return true;
  4066. }
  4067. // TODO: check if Content-Length is set
  4068. return false;
  4069. }
  4070. inline bool has_crlf(const std::string &s) {
  4071. auto p = s.c_str();
  4072. while (*p) {
  4073. if (*p == '\r' || *p == '\n') { return true; }
  4074. p++;
  4075. }
  4076. return false;
  4077. }
  4078. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4079. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  4080. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  4081. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  4082. unsigned int hash_length = 0;
  4083. unsigned char hash[EVP_MAX_MD_SIZE];
  4084. EVP_DigestInit_ex(context.get(), algo, nullptr);
  4085. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  4086. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  4087. std::stringstream ss;
  4088. for (auto i = 0u; i < hash_length; ++i) {
  4089. ss << std::hex << std::setw(2) << std::setfill('0')
  4090. << static_cast<unsigned int>(hash[i]);
  4091. }
  4092. return ss.str();
  4093. }
  4094. inline std::string MD5(const std::string &s) {
  4095. return message_digest(s, EVP_md5());
  4096. }
  4097. inline std::string SHA_256(const std::string &s) {
  4098. return message_digest(s, EVP_sha256());
  4099. }
  4100. inline std::string SHA_512(const std::string &s) {
  4101. return message_digest(s, EVP_sha512());
  4102. }
  4103. #endif
  4104. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4105. #ifdef _WIN32
  4106. // NOTE: This code came up with the following stackoverflow post:
  4107. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  4108. inline bool load_system_certs_on_windows(X509_STORE *store) {
  4109. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  4110. if (!hStore) { return false; }
  4111. auto result = false;
  4112. PCCERT_CONTEXT pContext = NULL;
  4113. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  4114. nullptr) {
  4115. auto encoded_cert =
  4116. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  4117. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  4118. if (x509) {
  4119. X509_STORE_add_cert(store, x509);
  4120. X509_free(x509);
  4121. result = true;
  4122. }
  4123. }
  4124. CertFreeCertificateContext(pContext);
  4125. CertCloseStore(hStore, 0);
  4126. return result;
  4127. }
  4128. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
  4129. #if TARGET_OS_OSX
  4130. template <typename T>
  4131. using CFObjectPtr =
  4132. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  4133. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  4134. if (obj) { CFRelease(obj); }
  4135. }
  4136. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  4137. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  4138. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  4139. kCFBooleanTrue};
  4140. CFObjectPtr<CFDictionaryRef> query(
  4141. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  4142. sizeof(keys) / sizeof(keys[0]),
  4143. &kCFTypeDictionaryKeyCallBacks,
  4144. &kCFTypeDictionaryValueCallBacks),
  4145. cf_object_ptr_deleter);
  4146. if (!query) { return false; }
  4147. CFTypeRef security_items = nullptr;
  4148. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  4149. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  4150. return false;
  4151. }
  4152. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  4153. return true;
  4154. }
  4155. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  4156. CFArrayRef root_security_items = nullptr;
  4157. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  4158. return false;
  4159. }
  4160. certs.reset(root_security_items);
  4161. return true;
  4162. }
  4163. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  4164. auto result = false;
  4165. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  4166. const auto cert = reinterpret_cast<const __SecCertificate *>(
  4167. CFArrayGetValueAtIndex(certs, i));
  4168. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  4169. CFDataRef cert_data = nullptr;
  4170. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  4171. errSecSuccess) {
  4172. continue;
  4173. }
  4174. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  4175. auto encoded_cert = static_cast<const unsigned char *>(
  4176. CFDataGetBytePtr(cert_data_ptr.get()));
  4177. auto x509 =
  4178. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  4179. if (x509) {
  4180. X509_STORE_add_cert(store, x509);
  4181. X509_free(x509);
  4182. result = true;
  4183. }
  4184. }
  4185. return result;
  4186. }
  4187. inline bool load_system_certs_on_macos(X509_STORE *store) {
  4188. auto result = false;
  4189. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  4190. if (retrieve_certs_from_keychain(certs) && certs) {
  4191. result = add_certs_to_x509_store(certs.get(), store);
  4192. }
  4193. if (retrieve_root_certs_from_keychain(certs) && certs) {
  4194. result = add_certs_to_x509_store(certs.get(), store) || result;
  4195. }
  4196. return result;
  4197. }
  4198. #endif // TARGET_OS_OSX
  4199. #endif // _WIN32
  4200. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  4201. #ifdef _WIN32
  4202. class WSInit {
  4203. public:
  4204. WSInit() {
  4205. WSADATA wsaData;
  4206. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  4207. }
  4208. ~WSInit() {
  4209. if (is_valid_) WSACleanup();
  4210. }
  4211. bool is_valid_ = false;
  4212. };
  4213. static WSInit wsinit_;
  4214. #endif
  4215. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4216. inline std::pair<std::string, std::string> make_digest_authentication_header(
  4217. const Request &req, const std::map<std::string, std::string> &auth,
  4218. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  4219. const std::string &password, bool is_proxy = false) {
  4220. std::string nc;
  4221. {
  4222. std::stringstream ss;
  4223. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  4224. nc = ss.str();
  4225. }
  4226. std::string qop;
  4227. if (auth.find("qop") != auth.end()) {
  4228. qop = auth.at("qop");
  4229. if (qop.find("auth-int") != std::string::npos) {
  4230. qop = "auth-int";
  4231. } else if (qop.find("auth") != std::string::npos) {
  4232. qop = "auth";
  4233. } else {
  4234. qop.clear();
  4235. }
  4236. }
  4237. std::string algo = "MD5";
  4238. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  4239. std::string response;
  4240. {
  4241. auto H = algo == "SHA-256" ? detail::SHA_256
  4242. : algo == "SHA-512" ? detail::SHA_512
  4243. : detail::MD5;
  4244. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  4245. auto A2 = req.method + ":" + req.path;
  4246. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  4247. if (qop.empty()) {
  4248. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  4249. } else {
  4250. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  4251. ":" + qop + ":" + H(A2));
  4252. }
  4253. }
  4254. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  4255. auto field = "Digest username=\"" + username + "\", realm=\"" +
  4256. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  4257. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  4258. (qop.empty() ? ", response=\""
  4259. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  4260. cnonce + "\", response=\"") +
  4261. response + "\"" +
  4262. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  4263. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  4264. return std::make_pair(key, field);
  4265. }
  4266. #endif
  4267. inline bool parse_www_authenticate(const Response &res,
  4268. std::map<std::string, std::string> &auth,
  4269. bool is_proxy) {
  4270. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  4271. if (res.has_header(auth_key)) {
  4272. static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  4273. auto s = res.get_header_value(auth_key);
  4274. auto pos = s.find(' ');
  4275. if (pos != std::string::npos) {
  4276. auto type = s.substr(0, pos);
  4277. if (type == "Basic") {
  4278. return false;
  4279. } else if (type == "Digest") {
  4280. s = s.substr(pos + 1);
  4281. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  4282. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  4283. const auto &m = *i;
  4284. auto key = s.substr(static_cast<size_t>(m.position(1)),
  4285. static_cast<size_t>(m.length(1)));
  4286. auto val = m.length(2) > 0
  4287. ? s.substr(static_cast<size_t>(m.position(2)),
  4288. static_cast<size_t>(m.length(2)))
  4289. : s.substr(static_cast<size_t>(m.position(3)),
  4290. static_cast<size_t>(m.length(3)));
  4291. auth[key] = val;
  4292. }
  4293. return true;
  4294. }
  4295. }
  4296. }
  4297. return false;
  4298. }
  4299. class ContentProviderAdapter {
  4300. public:
  4301. explicit ContentProviderAdapter(
  4302. ContentProviderWithoutLength &&content_provider)
  4303. : content_provider_(content_provider) {}
  4304. bool operator()(size_t offset, size_t, DataSink &sink) {
  4305. return content_provider_(offset, sink);
  4306. }
  4307. private:
  4308. ContentProviderWithoutLength content_provider_;
  4309. };
  4310. } // namespace detail
  4311. inline std::string hosted_at(const std::string &hostname) {
  4312. std::vector<std::string> addrs;
  4313. hosted_at(hostname, addrs);
  4314. if (addrs.empty()) { return std::string(); }
  4315. return addrs[0];
  4316. }
  4317. inline void hosted_at(const std::string &hostname,
  4318. std::vector<std::string> &addrs) {
  4319. struct addrinfo hints;
  4320. struct addrinfo *result;
  4321. memset(&hints, 0, sizeof(struct addrinfo));
  4322. hints.ai_family = AF_UNSPEC;
  4323. hints.ai_socktype = SOCK_STREAM;
  4324. hints.ai_protocol = 0;
  4325. if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) {
  4326. #if defined __linux__ && !defined __ANDROID__
  4327. res_init();
  4328. #endif
  4329. return;
  4330. }
  4331. for (auto rp = result; rp; rp = rp->ai_next) {
  4332. const auto &addr =
  4333. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  4334. std::string ip;
  4335. auto dummy = -1;
  4336. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  4337. dummy)) {
  4338. addrs.push_back(ip);
  4339. }
  4340. }
  4341. freeaddrinfo(result);
  4342. }
  4343. inline std::string append_query_params(const std::string &path,
  4344. const Params &params) {
  4345. std::string path_with_query = path;
  4346. const static std::regex re("[^?]+\\?.*");
  4347. auto delm = std::regex_match(path, re) ? '&' : '?';
  4348. path_with_query += delm + detail::params_to_query_str(params);
  4349. return path_with_query;
  4350. }
  4351. // Header utilities
  4352. inline std::pair<std::string, std::string>
  4353. make_range_header(const Ranges &ranges) {
  4354. std::string field = "bytes=";
  4355. auto i = 0;
  4356. for (const auto &r : ranges) {
  4357. if (i != 0) { field += ", "; }
  4358. if (r.first != -1) { field += std::to_string(r.first); }
  4359. field += '-';
  4360. if (r.second != -1) { field += std::to_string(r.second); }
  4361. i++;
  4362. }
  4363. return std::make_pair("Range", std::move(field));
  4364. }
  4365. inline std::pair<std::string, std::string>
  4366. make_basic_authentication_header(const std::string &username,
  4367. const std::string &password, bool is_proxy) {
  4368. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  4369. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  4370. return std::make_pair(key, std::move(field));
  4371. }
  4372. inline std::pair<std::string, std::string>
  4373. make_bearer_token_authentication_header(const std::string &token,
  4374. bool is_proxy = false) {
  4375. auto field = "Bearer " + token;
  4376. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  4377. return std::make_pair(key, std::move(field));
  4378. }
  4379. // Request implementation
  4380. inline bool Request::has_header(const std::string &key) const {
  4381. return detail::has_header(headers, key);
  4382. }
  4383. inline std::string Request::get_header_value(const std::string &key,
  4384. size_t id) const {
  4385. return detail::get_header_value(headers, key, id, "");
  4386. }
  4387. inline size_t Request::get_header_value_count(const std::string &key) const {
  4388. auto r = headers.equal_range(key);
  4389. return static_cast<size_t>(std::distance(r.first, r.second));
  4390. }
  4391. inline void Request::set_header(const std::string &key,
  4392. const std::string &val) {
  4393. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  4394. headers.emplace(key, val);
  4395. }
  4396. }
  4397. inline bool Request::has_param(const std::string &key) const {
  4398. return params.find(key) != params.end();
  4399. }
  4400. inline std::string Request::get_param_value(const std::string &key,
  4401. size_t id) const {
  4402. auto rng = params.equal_range(key);
  4403. auto it = rng.first;
  4404. std::advance(it, static_cast<ssize_t>(id));
  4405. if (it != rng.second) { return it->second; }
  4406. return std::string();
  4407. }
  4408. inline size_t Request::get_param_value_count(const std::string &key) const {
  4409. auto r = params.equal_range(key);
  4410. return static_cast<size_t>(std::distance(r.first, r.second));
  4411. }
  4412. inline bool Request::is_multipart_form_data() const {
  4413. const auto &content_type = get_header_value("Content-Type");
  4414. return !content_type.rfind("multipart/form-data", 0);
  4415. }
  4416. inline bool Request::has_file(const std::string &key) const {
  4417. return files.find(key) != files.end();
  4418. }
  4419. inline MultipartFormData Request::get_file_value(const std::string &key) const {
  4420. auto it = files.find(key);
  4421. if (it != files.end()) { return it->second; }
  4422. return MultipartFormData();
  4423. }
  4424. inline std::vector<MultipartFormData>
  4425. Request::get_file_values(const std::string &key) const {
  4426. std::vector<MultipartFormData> values;
  4427. auto rng = files.equal_range(key);
  4428. for (auto it = rng.first; it != rng.second; it++) {
  4429. values.push_back(it->second);
  4430. }
  4431. return values;
  4432. }
  4433. // Response implementation
  4434. inline bool Response::has_header(const std::string &key) const {
  4435. return headers.find(key) != headers.end();
  4436. }
  4437. inline std::string Response::get_header_value(const std::string &key,
  4438. size_t id) const {
  4439. return detail::get_header_value(headers, key, id, "");
  4440. }
  4441. inline size_t Response::get_header_value_count(const std::string &key) const {
  4442. auto r = headers.equal_range(key);
  4443. return static_cast<size_t>(std::distance(r.first, r.second));
  4444. }
  4445. inline void Response::set_header(const std::string &key,
  4446. const std::string &val) {
  4447. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  4448. headers.emplace(key, val);
  4449. }
  4450. }
  4451. inline void Response::set_redirect(const std::string &url, int stat) {
  4452. if (!detail::has_crlf(url)) {
  4453. set_header("Location", url);
  4454. if (300 <= stat && stat < 400) {
  4455. this->status = stat;
  4456. } else {
  4457. this->status = StatusCode::Found_302;
  4458. }
  4459. }
  4460. }
  4461. inline void Response::set_content(const char *s, size_t n,
  4462. const std::string &content_type) {
  4463. body.assign(s, n);
  4464. auto rng = headers.equal_range("Content-Type");
  4465. headers.erase(rng.first, rng.second);
  4466. set_header("Content-Type", content_type);
  4467. }
  4468. inline void Response::set_content(const std::string &s,
  4469. const std::string &content_type) {
  4470. set_content(s.data(), s.size(), content_type);
  4471. }
  4472. inline void Response::set_content(std::string &&s,
  4473. const std::string &content_type) {
  4474. body = std::move(s);
  4475. auto rng = headers.equal_range("Content-Type");
  4476. headers.erase(rng.first, rng.second);
  4477. set_header("Content-Type", content_type);
  4478. }
  4479. inline void Response::set_content_provider(
  4480. size_t in_length, const std::string &content_type, ContentProvider provider,
  4481. ContentProviderResourceReleaser resource_releaser) {
  4482. set_header("Content-Type", content_type);
  4483. content_length_ = in_length;
  4484. if (in_length > 0) { content_provider_ = std::move(provider); }
  4485. content_provider_resource_releaser_ = std::move(resource_releaser);
  4486. is_chunked_content_provider_ = false;
  4487. }
  4488. inline void Response::set_content_provider(
  4489. const std::string &content_type, ContentProviderWithoutLength provider,
  4490. ContentProviderResourceReleaser resource_releaser) {
  4491. set_header("Content-Type", content_type);
  4492. content_length_ = 0;
  4493. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  4494. content_provider_resource_releaser_ = std::move(resource_releaser);
  4495. is_chunked_content_provider_ = false;
  4496. }
  4497. inline void Response::set_chunked_content_provider(
  4498. const std::string &content_type, ContentProviderWithoutLength provider,
  4499. ContentProviderResourceReleaser resource_releaser) {
  4500. set_header("Content-Type", content_type);
  4501. content_length_ = 0;
  4502. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  4503. content_provider_resource_releaser_ = std::move(resource_releaser);
  4504. is_chunked_content_provider_ = true;
  4505. }
  4506. // Result implementation
  4507. inline bool Result::has_request_header(const std::string &key) const {
  4508. return request_headers_.find(key) != request_headers_.end();
  4509. }
  4510. inline std::string Result::get_request_header_value(const std::string &key,
  4511. size_t id) const {
  4512. return detail::get_header_value(request_headers_, key, id, "");
  4513. }
  4514. inline size_t
  4515. Result::get_request_header_value_count(const std::string &key) const {
  4516. auto r = request_headers_.equal_range(key);
  4517. return static_cast<size_t>(std::distance(r.first, r.second));
  4518. }
  4519. // Stream implementation
  4520. inline ssize_t Stream::write(const char *ptr) {
  4521. return write(ptr, strlen(ptr));
  4522. }
  4523. inline ssize_t Stream::write(const std::string &s) {
  4524. return write(s.data(), s.size());
  4525. }
  4526. namespace detail {
  4527. // Socket stream implementation
  4528. inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
  4529. time_t read_timeout_usec,
  4530. time_t write_timeout_sec,
  4531. time_t write_timeout_usec)
  4532. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  4533. read_timeout_usec_(read_timeout_usec),
  4534. write_timeout_sec_(write_timeout_sec),
  4535. write_timeout_usec_(write_timeout_usec), read_buff_(read_buff_size_, 0) {}
  4536. inline SocketStream::~SocketStream() = default;
  4537. inline bool SocketStream::is_readable() const {
  4538. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  4539. }
  4540. inline bool SocketStream::is_writable() const {
  4541. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  4542. is_socket_alive(sock_);
  4543. }
  4544. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  4545. #ifdef _WIN32
  4546. size =
  4547. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  4548. #else
  4549. size = (std::min)(size,
  4550. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  4551. #endif
  4552. if (read_buff_off_ < read_buff_content_size_) {
  4553. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  4554. if (size <= remaining_size) {
  4555. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  4556. read_buff_off_ += size;
  4557. return static_cast<ssize_t>(size);
  4558. } else {
  4559. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  4560. read_buff_off_ += remaining_size;
  4561. return static_cast<ssize_t>(remaining_size);
  4562. }
  4563. }
  4564. if (!is_readable()) { return -1; }
  4565. read_buff_off_ = 0;
  4566. read_buff_content_size_ = 0;
  4567. if (size < read_buff_size_) {
  4568. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  4569. CPPHTTPLIB_RECV_FLAGS);
  4570. if (n <= 0) {
  4571. return n;
  4572. } else if (n <= static_cast<ssize_t>(size)) {
  4573. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  4574. return n;
  4575. } else {
  4576. memcpy(ptr, read_buff_.data(), size);
  4577. read_buff_off_ = size;
  4578. read_buff_content_size_ = static_cast<size_t>(n);
  4579. return static_cast<ssize_t>(size);
  4580. }
  4581. } else {
  4582. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  4583. }
  4584. }
  4585. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  4586. if (!is_writable()) { return -1; }
  4587. #if defined(_WIN32) && !defined(_WIN64)
  4588. size =
  4589. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  4590. #endif
  4591. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  4592. }
  4593. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  4594. int &port) const {
  4595. return detail::get_remote_ip_and_port(sock_, ip, port);
  4596. }
  4597. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  4598. int &port) const {
  4599. return detail::get_local_ip_and_port(sock_, ip, port);
  4600. }
  4601. inline socket_t SocketStream::socket() const { return sock_; }
  4602. // Buffer stream implementation
  4603. inline bool BufferStream::is_readable() const { return true; }
  4604. inline bool BufferStream::is_writable() const { return true; }
  4605. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  4606. #if defined(_MSC_VER) && _MSC_VER < 1910
  4607. auto len_read = buffer._Copy_s(ptr, size, size, position);
  4608. #else
  4609. auto len_read = buffer.copy(ptr, size, position);
  4610. #endif
  4611. position += static_cast<size_t>(len_read);
  4612. return static_cast<ssize_t>(len_read);
  4613. }
  4614. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  4615. buffer.append(ptr, size);
  4616. return static_cast<ssize_t>(size);
  4617. }
  4618. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  4619. int & /*port*/) const {}
  4620. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  4621. int & /*port*/) const {}
  4622. inline socket_t BufferStream::socket() const { return 0; }
  4623. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  4624. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern) {
  4625. // One past the last ending position of a path param substring
  4626. std::size_t last_param_end = 0;
  4627. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4628. // Needed to ensure that parameter names are unique during matcher
  4629. // construction
  4630. // If exceptions are disabled, only last duplicate path
  4631. // parameter will be set
  4632. std::unordered_set<std::string> param_name_set;
  4633. #endif
  4634. while (true) {
  4635. const auto marker_pos = pattern.find(marker, last_param_end);
  4636. if (marker_pos == std::string::npos) { break; }
  4637. static_fragments_.push_back(
  4638. pattern.substr(last_param_end, marker_pos - last_param_end));
  4639. const auto param_name_start = marker_pos + 1;
  4640. auto sep_pos = pattern.find(separator, param_name_start);
  4641. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  4642. auto param_name =
  4643. pattern.substr(param_name_start, sep_pos - param_name_start);
  4644. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4645. if (param_name_set.find(param_name) != param_name_set.cend()) {
  4646. std::string msg = "Encountered path parameter '" + param_name +
  4647. "' multiple times in route pattern '" + pattern + "'.";
  4648. throw std::invalid_argument(msg);
  4649. }
  4650. #endif
  4651. param_names_.push_back(std::move(param_name));
  4652. last_param_end = sep_pos + 1;
  4653. }
  4654. if (last_param_end < pattern.length()) {
  4655. static_fragments_.push_back(pattern.substr(last_param_end));
  4656. }
  4657. }
  4658. inline bool PathParamsMatcher::match(Request &request) const {
  4659. request.matches = std::smatch();
  4660. request.path_params.clear();
  4661. request.path_params.reserve(param_names_.size());
  4662. // One past the position at which the path matched the pattern last time
  4663. std::size_t starting_pos = 0;
  4664. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  4665. const auto &fragment = static_fragments_[i];
  4666. if (starting_pos + fragment.length() > request.path.length()) {
  4667. return false;
  4668. }
  4669. // Avoid unnecessary allocation by using strncmp instead of substr +
  4670. // comparison
  4671. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  4672. fragment.length()) != 0) {
  4673. return false;
  4674. }
  4675. starting_pos += fragment.length();
  4676. // Should only happen when we have a static fragment after a param
  4677. // Example: '/users/:id/subscriptions'
  4678. // The 'subscriptions' fragment here does not have a corresponding param
  4679. if (i >= param_names_.size()) { continue; }
  4680. auto sep_pos = request.path.find(separator, starting_pos);
  4681. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  4682. const auto &param_name = param_names_[i];
  4683. request.path_params.emplace(
  4684. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  4685. // Mark everythin up to '/' as matched
  4686. starting_pos = sep_pos + 1;
  4687. }
  4688. // Returns false if the path is longer than the pattern
  4689. return starting_pos >= request.path.length();
  4690. }
  4691. inline bool RegexMatcher::match(Request &request) const {
  4692. request.path_params.clear();
  4693. return std::regex_match(request.path, request.matches, regex_);
  4694. }
  4695. } // namespace detail
  4696. // HTTP server implementation
  4697. inline Server::Server()
  4698. : new_task_queue(
  4699. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  4700. #ifndef _WIN32
  4701. signal(SIGPIPE, SIG_IGN);
  4702. #endif
  4703. }
  4704. inline Server::~Server() = default;
  4705. inline std::unique_ptr<detail::MatcherBase>
  4706. Server::make_matcher(const std::string &pattern) {
  4707. if (pattern.find("/:") != std::string::npos) {
  4708. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  4709. } else {
  4710. return detail::make_unique<detail::RegexMatcher>(pattern);
  4711. }
  4712. }
  4713. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  4714. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  4715. return *this;
  4716. }
  4717. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  4718. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  4719. return *this;
  4720. }
  4721. inline Server &Server::Post(const std::string &pattern,
  4722. HandlerWithContentReader handler) {
  4723. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  4724. std::move(handler));
  4725. return *this;
  4726. }
  4727. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  4728. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  4729. return *this;
  4730. }
  4731. inline Server &Server::Put(const std::string &pattern,
  4732. HandlerWithContentReader handler) {
  4733. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  4734. std::move(handler));
  4735. return *this;
  4736. }
  4737. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  4738. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  4739. return *this;
  4740. }
  4741. inline Server &Server::Patch(const std::string &pattern,
  4742. HandlerWithContentReader handler) {
  4743. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  4744. std::move(handler));
  4745. return *this;
  4746. }
  4747. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  4748. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  4749. return *this;
  4750. }
  4751. inline Server &Server::Delete(const std::string &pattern,
  4752. HandlerWithContentReader handler) {
  4753. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  4754. std::move(handler));
  4755. return *this;
  4756. }
  4757. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  4758. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  4759. return *this;
  4760. }
  4761. inline bool Server::set_base_dir(const std::string &dir,
  4762. const std::string &mount_point) {
  4763. return set_mount_point(mount_point, dir);
  4764. }
  4765. inline bool Server::set_mount_point(const std::string &mount_point,
  4766. const std::string &dir, Headers headers) {
  4767. if (detail::is_dir(dir)) {
  4768. std::string mnt = !mount_point.empty() ? mount_point : "/";
  4769. if (!mnt.empty() && mnt[0] == '/') {
  4770. base_dirs_.push_back({mnt, dir, std::move(headers)});
  4771. return true;
  4772. }
  4773. }
  4774. return false;
  4775. }
  4776. inline bool Server::remove_mount_point(const std::string &mount_point) {
  4777. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  4778. if (it->mount_point == mount_point) {
  4779. base_dirs_.erase(it);
  4780. return true;
  4781. }
  4782. }
  4783. return false;
  4784. }
  4785. inline Server &
  4786. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  4787. const std::string &mime) {
  4788. file_extension_and_mimetype_map_[ext] = mime;
  4789. return *this;
  4790. }
  4791. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  4792. default_file_mimetype_ = mime;
  4793. return *this;
  4794. }
  4795. inline Server &Server::set_file_request_handler(Handler handler) {
  4796. file_request_handler_ = std::move(handler);
  4797. return *this;
  4798. }
  4799. inline Server &Server::set_error_handler(HandlerWithResponse handler) {
  4800. error_handler_ = std::move(handler);
  4801. return *this;
  4802. }
  4803. inline Server &Server::set_error_handler(Handler handler) {
  4804. error_handler_ = [handler](const Request &req, Response &res) {
  4805. handler(req, res);
  4806. return HandlerResponse::Handled;
  4807. };
  4808. return *this;
  4809. }
  4810. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  4811. exception_handler_ = std::move(handler);
  4812. return *this;
  4813. }
  4814. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  4815. pre_routing_handler_ = std::move(handler);
  4816. return *this;
  4817. }
  4818. inline Server &Server::set_post_routing_handler(Handler handler) {
  4819. post_routing_handler_ = std::move(handler);
  4820. return *this;
  4821. }
  4822. inline Server &Server::set_logger(Logger logger) {
  4823. logger_ = std::move(logger);
  4824. return *this;
  4825. }
  4826. inline Server &
  4827. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  4828. expect_100_continue_handler_ = std::move(handler);
  4829. return *this;
  4830. }
  4831. inline Server &Server::set_address_family(int family) {
  4832. address_family_ = family;
  4833. return *this;
  4834. }
  4835. inline Server &Server::set_tcp_nodelay(bool on) {
  4836. tcp_nodelay_ = on;
  4837. return *this;
  4838. }
  4839. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  4840. socket_options_ = std::move(socket_options);
  4841. return *this;
  4842. }
  4843. inline Server &Server::set_default_headers(Headers headers) {
  4844. default_headers_ = std::move(headers);
  4845. return *this;
  4846. }
  4847. inline Server &Server::set_header_writer(
  4848. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  4849. header_writer_ = writer;
  4850. return *this;
  4851. }
  4852. inline Server &Server::set_keep_alive_max_count(size_t count) {
  4853. keep_alive_max_count_ = count;
  4854. return *this;
  4855. }
  4856. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  4857. keep_alive_timeout_sec_ = sec;
  4858. return *this;
  4859. }
  4860. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  4861. read_timeout_sec_ = sec;
  4862. read_timeout_usec_ = usec;
  4863. return *this;
  4864. }
  4865. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  4866. write_timeout_sec_ = sec;
  4867. write_timeout_usec_ = usec;
  4868. return *this;
  4869. }
  4870. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  4871. idle_interval_sec_ = sec;
  4872. idle_interval_usec_ = usec;
  4873. return *this;
  4874. }
  4875. inline Server &Server::set_payload_max_length(size_t length) {
  4876. payload_max_length_ = length;
  4877. return *this;
  4878. }
  4879. inline bool Server::bind_to_port(const std::string &host, int port,
  4880. int socket_flags) {
  4881. return bind_internal(host, port, socket_flags) >= 0;
  4882. }
  4883. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  4884. return bind_internal(host, 0, socket_flags);
  4885. }
  4886. inline bool Server::listen_after_bind() {
  4887. auto se = detail::scope_exit([&]() { done_ = true; });
  4888. return listen_internal();
  4889. }
  4890. inline bool Server::listen(const std::string &host, int port,
  4891. int socket_flags) {
  4892. auto se = detail::scope_exit([&]() { done_ = true; });
  4893. return bind_to_port(host, port, socket_flags) && listen_internal();
  4894. }
  4895. inline bool Server::is_running() const { return is_running_; }
  4896. inline void Server::wait_until_ready() const {
  4897. while (!is_running() && !done_) {
  4898. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  4899. }
  4900. }
  4901. inline void Server::stop() {
  4902. if (is_running_) {
  4903. assert(svr_sock_ != INVALID_SOCKET);
  4904. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  4905. detail::shutdown_socket(sock);
  4906. detail::close_socket(sock);
  4907. }
  4908. }
  4909. inline bool Server::parse_request_line(const char *s, Request &req) const {
  4910. auto len = strlen(s);
  4911. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  4912. len -= 2;
  4913. {
  4914. size_t count = 0;
  4915. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  4916. switch (count) {
  4917. case 0: req.method = std::string(b, e); break;
  4918. case 1: req.target = std::string(b, e); break;
  4919. case 2: req.version = std::string(b, e); break;
  4920. default: break;
  4921. }
  4922. count++;
  4923. });
  4924. if (count != 3) { return false; }
  4925. }
  4926. static const std::set<std::string> methods{
  4927. "GET", "HEAD", "POST", "PUT", "DELETE",
  4928. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  4929. if (methods.find(req.method) == methods.end()) { return false; }
  4930. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; }
  4931. {
  4932. // Skip URL fragment
  4933. for (size_t i = 0; i < req.target.size(); i++) {
  4934. if (req.target[i] == '#') {
  4935. req.target.erase(i);
  4936. break;
  4937. }
  4938. }
  4939. size_t count = 0;
  4940. detail::split(req.target.data(), req.target.data() + req.target.size(), '?',
  4941. 2, [&](const char *b, const char *e) {
  4942. switch (count) {
  4943. case 0:
  4944. req.path = detail::decode_url(std::string(b, e), false);
  4945. break;
  4946. case 1: {
  4947. if (e - b > 0) {
  4948. detail::parse_query_text(std::string(b, e), req.params);
  4949. }
  4950. break;
  4951. }
  4952. default: break;
  4953. }
  4954. count++;
  4955. });
  4956. if (count > 2) { return false; }
  4957. }
  4958. return true;
  4959. }
  4960. inline bool Server::write_response(Stream &strm, bool close_connection,
  4961. Request &req, Response &res) {
  4962. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  4963. // incorrectly to the error content.
  4964. req.ranges.clear();
  4965. return write_response_core(strm, close_connection, req, res, false);
  4966. }
  4967. inline bool Server::write_response_with_content(Stream &strm,
  4968. bool close_connection,
  4969. const Request &req,
  4970. Response &res) {
  4971. return write_response_core(strm, close_connection, req, res, true);
  4972. }
  4973. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  4974. const Request &req, Response &res,
  4975. bool need_apply_ranges) {
  4976. assert(res.status != -1);
  4977. if (400 <= res.status && error_handler_ &&
  4978. error_handler_(req, res) == HandlerResponse::Handled) {
  4979. need_apply_ranges = true;
  4980. }
  4981. std::string content_type;
  4982. std::string boundary;
  4983. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  4984. // Prepare additional headers
  4985. if (close_connection || req.get_header_value("Connection") == "close") {
  4986. res.set_header("Connection", "close");
  4987. } else {
  4988. std::stringstream ss;
  4989. ss << "timeout=" << keep_alive_timeout_sec_
  4990. << ", max=" << keep_alive_max_count_;
  4991. res.set_header("Keep-Alive", ss.str());
  4992. }
  4993. if (!res.has_header("Content-Type") &&
  4994. (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) {
  4995. res.set_header("Content-Type", "text/plain");
  4996. }
  4997. if (!res.has_header("Content-Length") && res.body.empty() &&
  4998. !res.content_length_ && !res.content_provider_) {
  4999. res.set_header("Content-Length", "0");
  5000. }
  5001. if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
  5002. res.set_header("Accept-Ranges", "bytes");
  5003. }
  5004. if (post_routing_handler_) { post_routing_handler_(req, res); }
  5005. // Response line and headers
  5006. {
  5007. detail::BufferStream bstrm;
  5008. if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  5009. status_message(res.status))) {
  5010. return false;
  5011. }
  5012. if (!header_writer_(bstrm, res.headers)) { return false; }
  5013. // Flush buffer
  5014. auto &data = bstrm.get_buffer();
  5015. detail::write_data(strm, data.data(), data.size());
  5016. }
  5017. // Body
  5018. auto ret = true;
  5019. if (req.method != "HEAD") {
  5020. if (!res.body.empty()) {
  5021. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  5022. ret = false;
  5023. }
  5024. } else if (res.content_provider_) {
  5025. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  5026. res.content_provider_success_ = true;
  5027. } else {
  5028. ret = false;
  5029. }
  5030. }
  5031. }
  5032. // Log
  5033. if (logger_) { logger_(req, res); }
  5034. return ret;
  5035. }
  5036. inline bool
  5037. Server::write_content_with_provider(Stream &strm, const Request &req,
  5038. Response &res, const std::string &boundary,
  5039. const std::string &content_type) {
  5040. auto is_shutting_down = [this]() {
  5041. return this->svr_sock_ == INVALID_SOCKET;
  5042. };
  5043. if (res.content_length_ > 0) {
  5044. if (req.ranges.empty()) {
  5045. return detail::write_content(strm, res.content_provider_, 0,
  5046. res.content_length_, is_shutting_down);
  5047. } else if (req.ranges.size() == 1) {
  5048. auto offset_and_length = detail::get_range_offset_and_length(
  5049. req.ranges[0], res.content_length_);
  5050. return detail::write_content(strm, res.content_provider_,
  5051. offset_and_length.first,
  5052. offset_and_length.second, is_shutting_down);
  5053. } else {
  5054. return detail::write_multipart_ranges_data(
  5055. strm, req, res, boundary, content_type, res.content_length_,
  5056. is_shutting_down);
  5057. }
  5058. } else {
  5059. if (res.is_chunked_content_provider_) {
  5060. auto type = detail::encoding_type(req, res);
  5061. std::unique_ptr<detail::compressor> compressor;
  5062. if (type == detail::EncodingType::Gzip) {
  5063. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5064. compressor = detail::make_unique<detail::gzip_compressor>();
  5065. #endif
  5066. } else if (type == detail::EncodingType::Brotli) {
  5067. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5068. compressor = detail::make_unique<detail::brotli_compressor>();
  5069. #endif
  5070. } else {
  5071. compressor = detail::make_unique<detail::nocompressor>();
  5072. }
  5073. assert(compressor != nullptr);
  5074. return detail::write_content_chunked(strm, res.content_provider_,
  5075. is_shutting_down, *compressor);
  5076. } else {
  5077. return detail::write_content_without_length(strm, res.content_provider_,
  5078. is_shutting_down);
  5079. }
  5080. }
  5081. }
  5082. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  5083. MultipartFormDataMap::iterator cur;
  5084. auto file_count = 0;
  5085. if (read_content_core(
  5086. strm, req, res,
  5087. // Regular
  5088. [&](const char *buf, size_t n) {
  5089. if (req.body.size() + n > req.body.max_size()) { return false; }
  5090. req.body.append(buf, n);
  5091. return true;
  5092. },
  5093. // Multipart
  5094. [&](const MultipartFormData &file) {
  5095. if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  5096. return false;
  5097. }
  5098. cur = req.files.emplace(file.name, file);
  5099. return true;
  5100. },
  5101. [&](const char *buf, size_t n) {
  5102. auto &content = cur->second.content;
  5103. if (content.size() + n > content.max_size()) { return false; }
  5104. content.append(buf, n);
  5105. return true;
  5106. })) {
  5107. const auto &content_type = req.get_header_value("Content-Type");
  5108. if (!content_type.find("application/x-www-form-urlencoded")) {
  5109. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  5110. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  5111. return false;
  5112. }
  5113. detail::parse_query_text(req.body, req.params);
  5114. }
  5115. return true;
  5116. }
  5117. return false;
  5118. }
  5119. inline bool Server::read_content_with_content_receiver(
  5120. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  5121. MultipartContentHeader multipart_header,
  5122. ContentReceiver multipart_receiver) {
  5123. return read_content_core(strm, req, res, std::move(receiver),
  5124. std::move(multipart_header),
  5125. std::move(multipart_receiver));
  5126. }
  5127. inline bool
  5128. Server::read_content_core(Stream &strm, Request &req, Response &res,
  5129. ContentReceiver receiver,
  5130. MultipartContentHeader multipart_header,
  5131. ContentReceiver multipart_receiver) const {
  5132. detail::MultipartFormDataParser multipart_form_data_parser;
  5133. ContentReceiverWithProgress out;
  5134. if (req.is_multipart_form_data()) {
  5135. const auto &content_type = req.get_header_value("Content-Type");
  5136. std::string boundary;
  5137. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  5138. res.status = StatusCode::BadRequest_400;
  5139. return false;
  5140. }
  5141. multipart_form_data_parser.set_boundary(std::move(boundary));
  5142. out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {
  5143. /* For debug
  5144. size_t pos = 0;
  5145. while (pos < n) {
  5146. auto read_size = (std::min)<size_t>(1, n - pos);
  5147. auto ret = multipart_form_data_parser.parse(
  5148. buf + pos, read_size, multipart_receiver, multipart_header);
  5149. if (!ret) { return false; }
  5150. pos += read_size;
  5151. }
  5152. return true;
  5153. */
  5154. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  5155. multipart_header);
  5156. };
  5157. } else {
  5158. out = [receiver](const char *buf, size_t n, uint64_t /*off*/,
  5159. uint64_t /*len*/) { return receiver(buf, n); };
  5160. }
  5161. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  5162. return true;
  5163. }
  5164. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  5165. out, true)) {
  5166. return false;
  5167. }
  5168. if (req.is_multipart_form_data()) {
  5169. if (!multipart_form_data_parser.is_valid()) {
  5170. res.status = StatusCode::BadRequest_400;
  5171. return false;
  5172. }
  5173. }
  5174. return true;
  5175. }
  5176. inline bool Server::handle_file_request(const Request &req, Response &res,
  5177. bool head) {
  5178. for (const auto &entry : base_dirs_) {
  5179. // Prefix match
  5180. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  5181. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  5182. if (detail::is_valid_path(sub_path)) {
  5183. auto path = entry.base_dir + sub_path;
  5184. if (path.back() == '/') { path += "index.html"; }
  5185. if (detail::is_file(path)) {
  5186. for (const auto &kv : entry.headers) {
  5187. res.set_header(kv.first, kv.second);
  5188. }
  5189. auto mm = std::make_shared<detail::mmap>(path.c_str());
  5190. if (!mm->is_open()) { return false; }
  5191. res.set_content_provider(
  5192. mm->size(),
  5193. detail::find_content_type(path, file_extension_and_mimetype_map_,
  5194. default_file_mimetype_),
  5195. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  5196. sink.write(mm->data() + offset, length);
  5197. return true;
  5198. });
  5199. if (!head && file_request_handler_) {
  5200. file_request_handler_(req, res);
  5201. }
  5202. return true;
  5203. }
  5204. }
  5205. }
  5206. }
  5207. return false;
  5208. }
  5209. inline socket_t
  5210. Server::create_server_socket(const std::string &host, int port,
  5211. int socket_flags,
  5212. SocketOptions socket_options) const {
  5213. return detail::create_socket(
  5214. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  5215. std::move(socket_options),
  5216. [](socket_t sock, struct addrinfo &ai) -> bool {
  5217. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5218. return false;
  5219. }
  5220. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; }
  5221. return true;
  5222. });
  5223. }
  5224. inline int Server::bind_internal(const std::string &host, int port,
  5225. int socket_flags) {
  5226. if (!is_valid()) { return -1; }
  5227. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  5228. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  5229. if (port == 0) {
  5230. struct sockaddr_storage addr;
  5231. socklen_t addr_len = sizeof(addr);
  5232. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  5233. &addr_len) == -1) {
  5234. return -1;
  5235. }
  5236. if (addr.ss_family == AF_INET) {
  5237. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  5238. } else if (addr.ss_family == AF_INET6) {
  5239. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  5240. } else {
  5241. return -1;
  5242. }
  5243. } else {
  5244. return port;
  5245. }
  5246. }
  5247. inline bool Server::listen_internal() {
  5248. auto ret = true;
  5249. is_running_ = true;
  5250. auto se = detail::scope_exit([&]() { is_running_ = false; });
  5251. {
  5252. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  5253. while (svr_sock_ != INVALID_SOCKET) {
  5254. #ifndef _WIN32
  5255. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  5256. #endif
  5257. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  5258. idle_interval_usec_);
  5259. if (val == 0) { // Timeout
  5260. task_queue->on_idle();
  5261. continue;
  5262. }
  5263. #ifndef _WIN32
  5264. }
  5265. #endif
  5266. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  5267. if (sock == INVALID_SOCKET) {
  5268. if (errno == EMFILE) {
  5269. // The per-process limit of open file descriptors has been reached.
  5270. // Try to accept new connections after a short sleep.
  5271. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  5272. continue;
  5273. } else if (errno == EINTR || errno == EAGAIN) {
  5274. continue;
  5275. }
  5276. if (svr_sock_ != INVALID_SOCKET) {
  5277. detail::close_socket(svr_sock_);
  5278. ret = false;
  5279. } else {
  5280. ; // The server socket was closed by user.
  5281. }
  5282. break;
  5283. }
  5284. {
  5285. #ifdef _WIN32
  5286. auto timeout = static_cast<uint32_t>(read_timeout_sec_ * 1000 +
  5287. read_timeout_usec_ / 1000);
  5288. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
  5289. reinterpret_cast<const char *>(&timeout), sizeof(timeout));
  5290. #else
  5291. timeval tv;
  5292. tv.tv_sec = static_cast<long>(read_timeout_sec_);
  5293. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec_);
  5294. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
  5295. reinterpret_cast<const void *>(&tv), sizeof(tv));
  5296. #endif
  5297. }
  5298. {
  5299. #ifdef _WIN32
  5300. auto timeout = static_cast<uint32_t>(write_timeout_sec_ * 1000 +
  5301. write_timeout_usec_ / 1000);
  5302. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,
  5303. reinterpret_cast<const char *>(&timeout), sizeof(timeout));
  5304. #else
  5305. timeval tv;
  5306. tv.tv_sec = static_cast<long>(write_timeout_sec_);
  5307. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec_);
  5308. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,
  5309. reinterpret_cast<const void *>(&tv), sizeof(tv));
  5310. #endif
  5311. }
  5312. if (!task_queue->enqueue(
  5313. [this, sock]() { process_and_close_socket(sock); })) {
  5314. detail::shutdown_socket(sock);
  5315. detail::close_socket(sock);
  5316. }
  5317. }
  5318. task_queue->shutdown();
  5319. }
  5320. return ret;
  5321. }
  5322. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  5323. if (pre_routing_handler_ &&
  5324. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  5325. return true;
  5326. }
  5327. // File handler
  5328. auto is_head_request = req.method == "HEAD";
  5329. if ((req.method == "GET" || is_head_request) &&
  5330. handle_file_request(req, res, is_head_request)) {
  5331. return true;
  5332. }
  5333. if (detail::expect_content(req)) {
  5334. // Content reader handler
  5335. {
  5336. ContentReader reader(
  5337. [&](ContentReceiver receiver) {
  5338. return read_content_with_content_receiver(
  5339. strm, req, res, std::move(receiver), nullptr, nullptr);
  5340. },
  5341. [&](MultipartContentHeader header, ContentReceiver receiver) {
  5342. return read_content_with_content_receiver(strm, req, res, nullptr,
  5343. std::move(header),
  5344. std::move(receiver));
  5345. });
  5346. if (req.method == "POST") {
  5347. if (dispatch_request_for_content_reader(
  5348. req, res, std::move(reader),
  5349. post_handlers_for_content_reader_)) {
  5350. return true;
  5351. }
  5352. } else if (req.method == "PUT") {
  5353. if (dispatch_request_for_content_reader(
  5354. req, res, std::move(reader),
  5355. put_handlers_for_content_reader_)) {
  5356. return true;
  5357. }
  5358. } else if (req.method == "PATCH") {
  5359. if (dispatch_request_for_content_reader(
  5360. req, res, std::move(reader),
  5361. patch_handlers_for_content_reader_)) {
  5362. return true;
  5363. }
  5364. } else if (req.method == "DELETE") {
  5365. if (dispatch_request_for_content_reader(
  5366. req, res, std::move(reader),
  5367. delete_handlers_for_content_reader_)) {
  5368. return true;
  5369. }
  5370. }
  5371. }
  5372. // Read content into `req.body`
  5373. if (!read_content(strm, req, res)) { return false; }
  5374. }
  5375. // Regular handler
  5376. if (req.method == "GET" || req.method == "HEAD") {
  5377. return dispatch_request(req, res, get_handlers_);
  5378. } else if (req.method == "POST") {
  5379. return dispatch_request(req, res, post_handlers_);
  5380. } else if (req.method == "PUT") {
  5381. return dispatch_request(req, res, put_handlers_);
  5382. } else if (req.method == "DELETE") {
  5383. return dispatch_request(req, res, delete_handlers_);
  5384. } else if (req.method == "OPTIONS") {
  5385. return dispatch_request(req, res, options_handlers_);
  5386. } else if (req.method == "PATCH") {
  5387. return dispatch_request(req, res, patch_handlers_);
  5388. }
  5389. res.status = StatusCode::BadRequest_400;
  5390. return false;
  5391. }
  5392. inline bool Server::dispatch_request(Request &req, Response &res,
  5393. const Handlers &handlers) const {
  5394. for (const auto &x : handlers) {
  5395. const auto &matcher = x.first;
  5396. const auto &handler = x.second;
  5397. if (matcher->match(req)) {
  5398. handler(req, res);
  5399. return true;
  5400. }
  5401. }
  5402. return false;
  5403. }
  5404. inline void Server::apply_ranges(const Request &req, Response &res,
  5405. std::string &content_type,
  5406. std::string &boundary) const {
  5407. if (req.ranges.size() > 1) {
  5408. auto it = res.headers.find("Content-Type");
  5409. if (it != res.headers.end()) {
  5410. content_type = it->second;
  5411. res.headers.erase(it);
  5412. }
  5413. boundary = detail::make_multipart_data_boundary();
  5414. res.set_header("Content-Type",
  5415. "multipart/byteranges; boundary=" + boundary);
  5416. }
  5417. auto type = detail::encoding_type(req, res);
  5418. if (res.body.empty()) {
  5419. if (res.content_length_ > 0) {
  5420. size_t length = 0;
  5421. if (req.ranges.empty()) {
  5422. length = res.content_length_;
  5423. } else if (req.ranges.size() == 1) {
  5424. auto offset_and_length = detail::get_range_offset_and_length(
  5425. req.ranges[0], res.content_length_);
  5426. length = offset_and_length.second;
  5427. auto content_range = detail::make_content_range_header_field(
  5428. offset_and_length, res.content_length_);
  5429. res.set_header("Content-Range", content_range);
  5430. } else {
  5431. length = detail::get_multipart_ranges_data_length(
  5432. req, boundary, content_type, res.content_length_);
  5433. }
  5434. res.set_header("Content-Length", std::to_string(length));
  5435. } else {
  5436. if (res.content_provider_) {
  5437. if (res.is_chunked_content_provider_) {
  5438. res.set_header("Transfer-Encoding", "chunked");
  5439. if (type == detail::EncodingType::Gzip) {
  5440. res.set_header("Content-Encoding", "gzip");
  5441. } else if (type == detail::EncodingType::Brotli) {
  5442. res.set_header("Content-Encoding", "br");
  5443. }
  5444. }
  5445. }
  5446. }
  5447. } else {
  5448. if (req.ranges.empty()) {
  5449. ;
  5450. } else if (req.ranges.size() == 1) {
  5451. auto offset_and_length =
  5452. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  5453. auto offset = offset_and_length.first;
  5454. auto length = offset_and_length.second;
  5455. auto content_range = detail::make_content_range_header_field(
  5456. offset_and_length, res.body.size());
  5457. res.set_header("Content-Range", content_range);
  5458. assert(offset + length <= res.body.size());
  5459. res.body = res.body.substr(offset, length);
  5460. } else {
  5461. std::string data;
  5462. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  5463. res.body.size(), data);
  5464. res.body.swap(data);
  5465. }
  5466. if (type != detail::EncodingType::None) {
  5467. std::unique_ptr<detail::compressor> compressor;
  5468. std::string content_encoding;
  5469. if (type == detail::EncodingType::Gzip) {
  5470. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5471. compressor = detail::make_unique<detail::gzip_compressor>();
  5472. content_encoding = "gzip";
  5473. #endif
  5474. } else if (type == detail::EncodingType::Brotli) {
  5475. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5476. compressor = detail::make_unique<detail::brotli_compressor>();
  5477. content_encoding = "br";
  5478. #endif
  5479. }
  5480. if (compressor) {
  5481. std::string compressed;
  5482. if (compressor->compress(res.body.data(), res.body.size(), true,
  5483. [&](const char *data, size_t data_len) {
  5484. compressed.append(data, data_len);
  5485. return true;
  5486. })) {
  5487. res.body.swap(compressed);
  5488. res.set_header("Content-Encoding", content_encoding);
  5489. }
  5490. }
  5491. }
  5492. auto length = std::to_string(res.body.size());
  5493. res.set_header("Content-Length", length);
  5494. }
  5495. }
  5496. inline bool Server::dispatch_request_for_content_reader(
  5497. Request &req, Response &res, ContentReader content_reader,
  5498. const HandlersForContentReader &handlers) const {
  5499. for (const auto &x : handlers) {
  5500. const auto &matcher = x.first;
  5501. const auto &handler = x.second;
  5502. if (matcher->match(req)) {
  5503. handler(req, res, content_reader);
  5504. return true;
  5505. }
  5506. }
  5507. return false;
  5508. }
  5509. inline bool
  5510. Server::process_request(Stream &strm, bool close_connection,
  5511. bool &connection_closed,
  5512. const std::function<void(Request &)> &setup_request) {
  5513. std::array<char, 2048> buf{};
  5514. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  5515. // Connection has been closed on client
  5516. if (!line_reader.getline()) { return false; }
  5517. Request req;
  5518. Response res;
  5519. res.version = "HTTP/1.1";
  5520. res.headers = default_headers_;
  5521. #ifdef _WIN32
  5522. // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL).
  5523. #else
  5524. #ifndef CPPHTTPLIB_USE_POLL
  5525. // Socket file descriptor exceeded FD_SETSIZE...
  5526. if (strm.socket() >= FD_SETSIZE) {
  5527. Headers dummy;
  5528. detail::read_headers(strm, dummy);
  5529. res.status = StatusCode::InternalServerError_500;
  5530. return write_response(strm, close_connection, req, res);
  5531. }
  5532. #endif
  5533. #endif
  5534. // Check if the request URI doesn't exceed the limit
  5535. if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  5536. Headers dummy;
  5537. detail::read_headers(strm, dummy);
  5538. res.status = StatusCode::UriTooLong_414;
  5539. return write_response(strm, close_connection, req, res);
  5540. }
  5541. // Request line and headers
  5542. if (!parse_request_line(line_reader.ptr(), req) ||
  5543. !detail::read_headers(strm, req.headers)) {
  5544. res.status = StatusCode::BadRequest_400;
  5545. return write_response(strm, close_connection, req, res);
  5546. }
  5547. if (req.get_header_value("Connection") == "close") {
  5548. connection_closed = true;
  5549. }
  5550. if (req.version == "HTTP/1.0" &&
  5551. req.get_header_value("Connection") != "Keep-Alive") {
  5552. connection_closed = true;
  5553. }
  5554. strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);
  5555. req.set_header("REMOTE_ADDR", req.remote_addr);
  5556. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  5557. strm.get_local_ip_and_port(req.local_addr, req.local_port);
  5558. req.set_header("LOCAL_ADDR", req.local_addr);
  5559. req.set_header("LOCAL_PORT", std::to_string(req.local_port));
  5560. if (req.has_header("Range")) {
  5561. const auto &range_header_value = req.get_header_value("Range");
  5562. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  5563. res.status = StatusCode::RangeNotSatisfiable_416;
  5564. return write_response(strm, close_connection, req, res);
  5565. }
  5566. }
  5567. if (setup_request) { setup_request(req); }
  5568. if (req.get_header_value("Expect") == "100-continue") {
  5569. int status = StatusCode::Continue_100;
  5570. if (expect_100_continue_handler_) {
  5571. status = expect_100_continue_handler_(req, res);
  5572. }
  5573. switch (status) {
  5574. case StatusCode::Continue_100:
  5575. case StatusCode::ExpectationFailed_417:
  5576. strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
  5577. status_message(status));
  5578. break;
  5579. default: return write_response(strm, close_connection, req, res);
  5580. }
  5581. }
  5582. // Routing
  5583. auto routed = false;
  5584. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  5585. routed = routing(req, res, strm);
  5586. #else
  5587. try {
  5588. routed = routing(req, res, strm);
  5589. } catch (std::exception &e) {
  5590. if (exception_handler_) {
  5591. auto ep = std::current_exception();
  5592. exception_handler_(req, res, ep);
  5593. routed = true;
  5594. } else {
  5595. res.status = StatusCode::InternalServerError_500;
  5596. std::string val;
  5597. auto s = e.what();
  5598. for (size_t i = 0; s[i]; i++) {
  5599. switch (s[i]) {
  5600. case '\r': val += "\\r"; break;
  5601. case '\n': val += "\\n"; break;
  5602. default: val += s[i]; break;
  5603. }
  5604. }
  5605. res.set_header("EXCEPTION_WHAT", val);
  5606. }
  5607. } catch (...) {
  5608. if (exception_handler_) {
  5609. auto ep = std::current_exception();
  5610. exception_handler_(req, res, ep);
  5611. routed = true;
  5612. } else {
  5613. res.status = StatusCode::InternalServerError_500;
  5614. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  5615. }
  5616. }
  5617. #endif
  5618. if (routed) {
  5619. if (res.status == -1) {
  5620. res.status = req.ranges.empty() ? StatusCode::OK_200
  5621. : StatusCode::PartialContent_206;
  5622. }
  5623. if (detail::range_error(req, res)) {
  5624. res.body.clear();
  5625. res.content_length_ = 0;
  5626. res.content_provider_ = nullptr;
  5627. res.status = StatusCode::RangeNotSatisfiable_416;
  5628. return write_response(strm, close_connection, req, res);
  5629. }
  5630. return write_response_with_content(strm, close_connection, req, res);
  5631. } else {
  5632. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  5633. return write_response(strm, close_connection, req, res);
  5634. }
  5635. }
  5636. inline bool Server::is_valid() const { return true; }
  5637. inline bool Server::process_and_close_socket(socket_t sock) {
  5638. auto ret = detail::process_server_socket(
  5639. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  5640. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  5641. write_timeout_usec_,
  5642. [this](Stream &strm, bool close_connection, bool &connection_closed) {
  5643. return process_request(strm, close_connection, connection_closed,
  5644. nullptr);
  5645. });
  5646. detail::shutdown_socket(sock);
  5647. detail::close_socket(sock);
  5648. return ret;
  5649. }
  5650. // HTTP client implementation
  5651. inline ClientImpl::ClientImpl(const std::string &host)
  5652. : ClientImpl(host, 80, std::string(), std::string()) {}
  5653. inline ClientImpl::ClientImpl(const std::string &host, int port)
  5654. : ClientImpl(host, port, std::string(), std::string()) {}
  5655. inline ClientImpl::ClientImpl(const std::string &host, int port,
  5656. const std::string &client_cert_path,
  5657. const std::string &client_key_path)
  5658. : host_(host), port_(port),
  5659. host_and_port_(adjust_host_string(host) + ":" + std::to_string(port)),
  5660. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  5661. inline ClientImpl::~ClientImpl() {
  5662. std::lock_guard<std::mutex> guard(socket_mutex_);
  5663. shutdown_socket(socket_);
  5664. close_socket(socket_);
  5665. }
  5666. inline bool ClientImpl::is_valid() const { return true; }
  5667. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  5668. client_cert_path_ = rhs.client_cert_path_;
  5669. client_key_path_ = rhs.client_key_path_;
  5670. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  5671. read_timeout_sec_ = rhs.read_timeout_sec_;
  5672. read_timeout_usec_ = rhs.read_timeout_usec_;
  5673. write_timeout_sec_ = rhs.write_timeout_sec_;
  5674. write_timeout_usec_ = rhs.write_timeout_usec_;
  5675. basic_auth_username_ = rhs.basic_auth_username_;
  5676. basic_auth_password_ = rhs.basic_auth_password_;
  5677. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  5678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5679. digest_auth_username_ = rhs.digest_auth_username_;
  5680. digest_auth_password_ = rhs.digest_auth_password_;
  5681. #endif
  5682. keep_alive_ = rhs.keep_alive_;
  5683. follow_location_ = rhs.follow_location_;
  5684. url_encode_ = rhs.url_encode_;
  5685. address_family_ = rhs.address_family_;
  5686. tcp_nodelay_ = rhs.tcp_nodelay_;
  5687. socket_options_ = rhs.socket_options_;
  5688. compress_ = rhs.compress_;
  5689. decompress_ = rhs.decompress_;
  5690. interface_ = rhs.interface_;
  5691. proxy_host_ = rhs.proxy_host_;
  5692. proxy_port_ = rhs.proxy_port_;
  5693. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  5694. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  5695. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  5696. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5697. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  5698. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  5699. #endif
  5700. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5701. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  5702. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  5703. ca_cert_store_ = rhs.ca_cert_store_;
  5704. #endif
  5705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5706. server_certificate_verification_ = rhs.server_certificate_verification_;
  5707. #endif
  5708. logger_ = rhs.logger_;
  5709. }
  5710. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  5711. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5712. return detail::create_client_socket(
  5713. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  5714. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  5715. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  5716. write_timeout_usec_, interface_, error);
  5717. }
  5718. // Check is custom IP specified for host_
  5719. std::string ip;
  5720. auto it = addr_map_.find(host_);
  5721. if (it != addr_map_.end()) { ip = it->second; }
  5722. return detail::create_client_socket(
  5723. host_, ip, port_, address_family_, tcp_nodelay_, socket_options_,
  5724. connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_,
  5725. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_,
  5726. error);
  5727. }
  5728. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  5729. Error &error) {
  5730. auto sock = create_client_socket(error);
  5731. if (sock == INVALID_SOCKET) { return false; }
  5732. socket.sock = sock;
  5733. return true;
  5734. }
  5735. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  5736. bool /*shutdown_gracefully*/) {
  5737. // If there are any requests in flight from threads other than us, then it's
  5738. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  5739. assert(socket_requests_in_flight_ == 0 ||
  5740. socket_requests_are_from_thread_ == std::this_thread::get_id());
  5741. }
  5742. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  5743. if (socket.sock == INVALID_SOCKET) { return; }
  5744. detail::shutdown_socket(socket.sock);
  5745. }
  5746. inline void ClientImpl::close_socket(Socket &socket) {
  5747. // If there are requests in flight in another thread, usually closing
  5748. // the socket will be fine and they will simply receive an error when
  5749. // using the closed socket, but it is still a bug since rarely the OS
  5750. // may reassign the socket id to be used for a new socket, and then
  5751. // suddenly they will be operating on a live socket that is different
  5752. // than the one they intended!
  5753. assert(socket_requests_in_flight_ == 0 ||
  5754. socket_requests_are_from_thread_ == std::this_thread::get_id());
  5755. // It is also a bug if this happens while SSL is still active
  5756. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5757. assert(socket.ssl == nullptr);
  5758. #endif
  5759. if (socket.sock == INVALID_SOCKET) { return; }
  5760. detail::close_socket(socket.sock);
  5761. socket.sock = INVALID_SOCKET;
  5762. }
  5763. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  5764. Response &res) const {
  5765. std::array<char, 2048> buf{};
  5766. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  5767. if (!line_reader.getline()) { return false; }
  5768. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5769. const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  5770. #else
  5771. const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  5772. #endif
  5773. std::cmatch m;
  5774. if (!std::regex_match(line_reader.ptr(), m, re)) {
  5775. return req.method == "CONNECT";
  5776. }
  5777. res.version = std::string(m[1]);
  5778. res.status = std::stoi(std::string(m[2]));
  5779. res.reason = std::string(m[3]);
  5780. // Ignore '100 Continue'
  5781. while (res.status == StatusCode::Continue_100) {
  5782. if (!line_reader.getline()) { return false; } // CRLF
  5783. if (!line_reader.getline()) { return false; } // next response line
  5784. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  5785. res.version = std::string(m[1]);
  5786. res.status = std::stoi(std::string(m[2]));
  5787. res.reason = std::string(m[3]);
  5788. }
  5789. return true;
  5790. }
  5791. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  5792. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  5793. auto ret = send_(req, res, error);
  5794. if (error == Error::SSLPeerCouldBeClosed_) {
  5795. assert(!ret);
  5796. ret = send_(req, res, error);
  5797. }
  5798. return ret;
  5799. }
  5800. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  5801. {
  5802. std::lock_guard<std::mutex> guard(socket_mutex_);
  5803. // Set this to false immediately - if it ever gets set to true by the end of
  5804. // the request, we know another thread instructed us to close the socket.
  5805. socket_should_be_closed_when_request_is_done_ = false;
  5806. auto is_alive = false;
  5807. if (socket_.is_open()) {
  5808. is_alive = detail::is_socket_alive(socket_.sock);
  5809. if (!is_alive) {
  5810. // Attempt to avoid sigpipe by shutting down nongracefully if it seems
  5811. // like the other side has already closed the connection Also, there
  5812. // cannot be any requests in flight from other threads since we locked
  5813. // request_mutex_, so safe to close everything immediately
  5814. const bool shutdown_gracefully = false;
  5815. shutdown_ssl(socket_, shutdown_gracefully);
  5816. shutdown_socket(socket_);
  5817. close_socket(socket_);
  5818. }
  5819. }
  5820. if (!is_alive) {
  5821. if (!create_and_connect_socket(socket_, error)) { return false; }
  5822. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5823. // TODO: refactoring
  5824. if (is_ssl()) {
  5825. auto &scli = static_cast<SSLClient &>(*this);
  5826. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5827. auto success = false;
  5828. if (!scli.connect_with_proxy(socket_, res, success, error)) {
  5829. return success;
  5830. }
  5831. }
  5832. if (!scli.initialize_ssl(socket_, error)) { return false; }
  5833. }
  5834. #endif
  5835. }
  5836. // Mark the current socket as being in use so that it cannot be closed by
  5837. // anyone else while this request is ongoing, even though we will be
  5838. // releasing the mutex.
  5839. if (socket_requests_in_flight_ > 1) {
  5840. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  5841. }
  5842. socket_requests_in_flight_ += 1;
  5843. socket_requests_are_from_thread_ = std::this_thread::get_id();
  5844. }
  5845. for (const auto &header : default_headers_) {
  5846. if (req.headers.find(header.first) == req.headers.end()) {
  5847. req.headers.insert(header);
  5848. }
  5849. }
  5850. auto ret = false;
  5851. auto close_connection = !keep_alive_;
  5852. auto se = detail::scope_exit([&]() {
  5853. // Briefly lock mutex in order to mark that a request is no longer ongoing
  5854. std::lock_guard<std::mutex> guard(socket_mutex_);
  5855. socket_requests_in_flight_ -= 1;
  5856. if (socket_requests_in_flight_ <= 0) {
  5857. assert(socket_requests_in_flight_ == 0);
  5858. socket_requests_are_from_thread_ = std::thread::id();
  5859. }
  5860. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  5861. !ret) {
  5862. shutdown_ssl(socket_, true);
  5863. shutdown_socket(socket_);
  5864. close_socket(socket_);
  5865. }
  5866. });
  5867. ret = process_socket(socket_, [&](Stream &strm) {
  5868. return handle_request(strm, req, res, close_connection, error);
  5869. });
  5870. if (!ret) {
  5871. if (error == Error::Success) { error = Error::Unknown; }
  5872. }
  5873. return ret;
  5874. }
  5875. inline Result ClientImpl::send(const Request &req) {
  5876. auto req2 = req;
  5877. return send_(std::move(req2));
  5878. }
  5879. inline Result ClientImpl::send_(Request &&req) {
  5880. auto res = detail::make_unique<Response>();
  5881. auto error = Error::Success;
  5882. auto ret = send(req, *res, error);
  5883. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  5884. }
  5885. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  5886. Response &res, bool close_connection,
  5887. Error &error) {
  5888. if (req.path.empty()) {
  5889. error = Error::Connection;
  5890. return false;
  5891. }
  5892. auto req_save = req;
  5893. bool ret;
  5894. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  5895. auto req2 = req;
  5896. req2.path = "http://" + host_and_port_ + req.path;
  5897. ret = process_request(strm, req2, res, close_connection, error);
  5898. req = req2;
  5899. req.path = req_save.path;
  5900. } else {
  5901. ret = process_request(strm, req, res, close_connection, error);
  5902. }
  5903. if (!ret) { return false; }
  5904. if (res.get_header_value("Connection") == "close" ||
  5905. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  5906. // TODO this requires a not-entirely-obvious chain of calls to be correct
  5907. // for this to be safe.
  5908. // This is safe to call because handle_request is only called by send_
  5909. // which locks the request mutex during the process. It would be a bug
  5910. // to call it from a different thread since it's a thread-safety issue
  5911. // to do these things to the socket if another thread is using the socket.
  5912. std::lock_guard<std::mutex> guard(socket_mutex_);
  5913. shutdown_ssl(socket_, true);
  5914. shutdown_socket(socket_);
  5915. close_socket(socket_);
  5916. }
  5917. if (300 < res.status && res.status < 400 && follow_location_) {
  5918. req = req_save;
  5919. ret = redirect(req, res, error);
  5920. }
  5921. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5922. if ((res.status == StatusCode::Unauthorized_401 ||
  5923. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  5924. req.authorization_count_ < 5) {
  5925. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  5926. const auto &username =
  5927. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  5928. const auto &password =
  5929. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  5930. if (!username.empty() && !password.empty()) {
  5931. std::map<std::string, std::string> auth;
  5932. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  5933. Request new_req = req;
  5934. new_req.authorization_count_ += 1;
  5935. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  5936. : "Authorization");
  5937. new_req.headers.insert(detail::make_digest_authentication_header(
  5938. req, auth, new_req.authorization_count_, detail::random_string(10),
  5939. username, password, is_proxy));
  5940. Response new_res;
  5941. ret = send(new_req, new_res, error);
  5942. if (ret) { res = new_res; }
  5943. }
  5944. }
  5945. }
  5946. #endif
  5947. return ret;
  5948. }
  5949. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  5950. if (req.redirect_count_ == 0) {
  5951. error = Error::ExceedRedirectCount;
  5952. return false;
  5953. }
  5954. auto location = res.get_header_value("location");
  5955. if (location.empty()) { return false; }
  5956. const static std::regex re(
  5957. R"((?:(https?):)?(?://(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  5958. std::smatch m;
  5959. if (!std::regex_match(location, m, re)) { return false; }
  5960. auto scheme = is_ssl() ? "https" : "http";
  5961. auto next_scheme = m[1].str();
  5962. auto next_host = m[2].str();
  5963. if (next_host.empty()) { next_host = m[3].str(); }
  5964. auto port_str = m[4].str();
  5965. auto next_path = m[5].str();
  5966. auto next_query = m[6].str();
  5967. auto next_port = port_;
  5968. if (!port_str.empty()) {
  5969. next_port = std::stoi(port_str);
  5970. } else if (!next_scheme.empty()) {
  5971. next_port = next_scheme == "https" ? 443 : 80;
  5972. }
  5973. if (next_scheme.empty()) { next_scheme = scheme; }
  5974. if (next_host.empty()) { next_host = host_; }
  5975. if (next_path.empty()) { next_path = "/"; }
  5976. auto path = detail::decode_url(next_path, true) + next_query;
  5977. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  5978. return detail::redirect(*this, req, res, path, location, error);
  5979. } else {
  5980. if (next_scheme == "https") {
  5981. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5982. SSLClient cli(next_host, next_port);
  5983. cli.copy_settings(*this);
  5984. if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); }
  5985. return detail::redirect(cli, req, res, path, location, error);
  5986. #else
  5987. return false;
  5988. #endif
  5989. } else {
  5990. ClientImpl cli(next_host, next_port);
  5991. cli.copy_settings(*this);
  5992. return detail::redirect(cli, req, res, path, location, error);
  5993. }
  5994. }
  5995. }
  5996. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  5997. const Request &req,
  5998. Error &error) const {
  5999. auto is_shutting_down = []() { return false; };
  6000. if (req.is_chunked_content_provider_) {
  6001. // TODO: Brotli support
  6002. std::unique_ptr<detail::compressor> compressor;
  6003. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6004. if (compress_) {
  6005. compressor = detail::make_unique<detail::gzip_compressor>();
  6006. } else
  6007. #endif
  6008. {
  6009. compressor = detail::make_unique<detail::nocompressor>();
  6010. }
  6011. return detail::write_content_chunked(strm, req.content_provider_,
  6012. is_shutting_down, *compressor, error);
  6013. } else {
  6014. return detail::write_content(strm, req.content_provider_, 0,
  6015. req.content_length_, is_shutting_down, error);
  6016. }
  6017. }
  6018. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  6019. bool close_connection, Error &error) {
  6020. // Prepare additional headers
  6021. if (close_connection) {
  6022. if (!req.has_header("Connection")) {
  6023. req.set_header("Connection", "close");
  6024. }
  6025. }
  6026. if (!req.has_header("Host")) {
  6027. if (is_ssl()) {
  6028. if (port_ == 443) {
  6029. req.set_header("Host", host_);
  6030. } else {
  6031. req.set_header("Host", host_and_port_);
  6032. }
  6033. } else {
  6034. if (port_ == 80) {
  6035. req.set_header("Host", host_);
  6036. } else {
  6037. req.set_header("Host", host_and_port_);
  6038. }
  6039. }
  6040. }
  6041. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  6042. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  6043. if (!req.has_header("User-Agent")) {
  6044. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  6045. req.set_header("User-Agent", agent);
  6046. }
  6047. #endif
  6048. if (req.body.empty()) {
  6049. if (req.content_provider_) {
  6050. if (!req.is_chunked_content_provider_) {
  6051. if (!req.has_header("Content-Length")) {
  6052. auto length = std::to_string(req.content_length_);
  6053. req.set_header("Content-Length", length);
  6054. }
  6055. }
  6056. } else {
  6057. if (req.method == "POST" || req.method == "PUT" ||
  6058. req.method == "PATCH") {
  6059. req.set_header("Content-Length", "0");
  6060. }
  6061. }
  6062. } else {
  6063. if (!req.has_header("Content-Type")) {
  6064. req.set_header("Content-Type", "text/plain");
  6065. }
  6066. if (!req.has_header("Content-Length")) {
  6067. auto length = std::to_string(req.body.size());
  6068. req.set_header("Content-Length", length);
  6069. }
  6070. }
  6071. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  6072. if (!req.has_header("Authorization")) {
  6073. req.headers.insert(make_basic_authentication_header(
  6074. basic_auth_username_, basic_auth_password_, false));
  6075. }
  6076. }
  6077. if (!proxy_basic_auth_username_.empty() &&
  6078. !proxy_basic_auth_password_.empty()) {
  6079. if (!req.has_header("Proxy-Authorization")) {
  6080. req.headers.insert(make_basic_authentication_header(
  6081. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  6082. }
  6083. }
  6084. if (!bearer_token_auth_token_.empty()) {
  6085. if (!req.has_header("Authorization")) {
  6086. req.headers.insert(make_bearer_token_authentication_header(
  6087. bearer_token_auth_token_, false));
  6088. }
  6089. }
  6090. if (!proxy_bearer_token_auth_token_.empty()) {
  6091. if (!req.has_header("Proxy-Authorization")) {
  6092. req.headers.insert(make_bearer_token_authentication_header(
  6093. proxy_bearer_token_auth_token_, true));
  6094. }
  6095. }
  6096. // Request line and headers
  6097. {
  6098. detail::BufferStream bstrm;
  6099. const auto &path = url_encode_ ? detail::encode_url(req.path) : req.path;
  6100. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  6101. header_writer_(bstrm, req.headers);
  6102. // Flush buffer
  6103. auto &data = bstrm.get_buffer();
  6104. if (!detail::write_data(strm, data.data(), data.size())) {
  6105. error = Error::Write;
  6106. return false;
  6107. }
  6108. }
  6109. // Body
  6110. if (req.body.empty()) {
  6111. return write_content_with_provider(strm, req, error);
  6112. }
  6113. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  6114. error = Error::Write;
  6115. return false;
  6116. }
  6117. return true;
  6118. }
  6119. inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
  6120. Request &req, const char *body, size_t content_length,
  6121. ContentProvider content_provider,
  6122. ContentProviderWithoutLength content_provider_without_length,
  6123. const std::string &content_type, Error &error) {
  6124. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  6125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6126. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  6127. #endif
  6128. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6129. if (compress_ && !content_provider_without_length) {
  6130. // TODO: Brotli support
  6131. detail::gzip_compressor compressor;
  6132. if (content_provider) {
  6133. auto ok = true;
  6134. size_t offset = 0;
  6135. DataSink data_sink;
  6136. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  6137. if (ok) {
  6138. auto last = offset + data_len == content_length;
  6139. auto ret = compressor.compress(
  6140. data, data_len, last,
  6141. [&](const char *compressed_data, size_t compressed_data_len) {
  6142. req.body.append(compressed_data, compressed_data_len);
  6143. return true;
  6144. });
  6145. if (ret) {
  6146. offset += data_len;
  6147. } else {
  6148. ok = false;
  6149. }
  6150. }
  6151. return ok;
  6152. };
  6153. while (ok && offset < content_length) {
  6154. if (!content_provider(offset, content_length - offset, data_sink)) {
  6155. error = Error::Canceled;
  6156. return nullptr;
  6157. }
  6158. }
  6159. } else {
  6160. if (!compressor.compress(body, content_length, true,
  6161. [&](const char *data, size_t data_len) {
  6162. req.body.append(data, data_len);
  6163. return true;
  6164. })) {
  6165. error = Error::Compression;
  6166. return nullptr;
  6167. }
  6168. }
  6169. } else
  6170. #endif
  6171. {
  6172. if (content_provider) {
  6173. req.content_length_ = content_length;
  6174. req.content_provider_ = std::move(content_provider);
  6175. req.is_chunked_content_provider_ = false;
  6176. } else if (content_provider_without_length) {
  6177. req.content_length_ = 0;
  6178. req.content_provider_ = detail::ContentProviderAdapter(
  6179. std::move(content_provider_without_length));
  6180. req.is_chunked_content_provider_ = true;
  6181. req.set_header("Transfer-Encoding", "chunked");
  6182. } else {
  6183. req.body.assign(body, content_length);
  6184. }
  6185. }
  6186. auto res = detail::make_unique<Response>();
  6187. return send(req, *res, error) ? std::move(res) : nullptr;
  6188. }
  6189. inline Result ClientImpl::send_with_content_provider(
  6190. const std::string &method, const std::string &path, const Headers &headers,
  6191. const char *body, size_t content_length, ContentProvider content_provider,
  6192. ContentProviderWithoutLength content_provider_without_length,
  6193. const std::string &content_type) {
  6194. Request req;
  6195. req.method = method;
  6196. req.headers = headers;
  6197. req.path = path;
  6198. auto error = Error::Success;
  6199. auto res = send_with_content_provider(
  6200. req, body, content_length, std::move(content_provider),
  6201. std::move(content_provider_without_length), content_type, error);
  6202. return Result{std::move(res), error, std::move(req.headers)};
  6203. }
  6204. inline std::string
  6205. ClientImpl::adjust_host_string(const std::string &host) const {
  6206. if (host.find(':') != std::string::npos) { return "[" + host + "]"; }
  6207. return host;
  6208. }
  6209. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  6210. Response &res, bool close_connection,
  6211. Error &error) {
  6212. // Send request
  6213. if (!write_request(strm, req, close_connection, error)) { return false; }
  6214. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6215. if (is_ssl()) {
  6216. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  6217. if (!is_proxy_enabled) {
  6218. char buf[1];
  6219. if (SSL_peek(socket_.ssl, buf, 1) == 0 &&
  6220. SSL_get_error(socket_.ssl, 0) == SSL_ERROR_ZERO_RETURN) {
  6221. error = Error::SSLPeerCouldBeClosed_;
  6222. return false;
  6223. }
  6224. }
  6225. }
  6226. #endif
  6227. // Receive response and headers
  6228. if (!read_response_line(strm, req, res) ||
  6229. !detail::read_headers(strm, res.headers)) {
  6230. error = Error::Read;
  6231. return false;
  6232. }
  6233. // Body
  6234. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  6235. req.method != "CONNECT") {
  6236. auto redirect = 300 < res.status && res.status < 400 && follow_location_;
  6237. if (req.response_handler && !redirect) {
  6238. if (!req.response_handler(res)) {
  6239. error = Error::Canceled;
  6240. return false;
  6241. }
  6242. }
  6243. auto out =
  6244. req.content_receiver
  6245. ? static_cast<ContentReceiverWithProgress>(
  6246. [&](const char *buf, size_t n, uint64_t off, uint64_t len) {
  6247. if (redirect) { return true; }
  6248. auto ret = req.content_receiver(buf, n, off, len);
  6249. if (!ret) { error = Error::Canceled; }
  6250. return ret;
  6251. })
  6252. : static_cast<ContentReceiverWithProgress>(
  6253. [&](const char *buf, size_t n, uint64_t /*off*/,
  6254. uint64_t /*len*/) {
  6255. if (res.body.size() + n > res.body.max_size()) {
  6256. return false;
  6257. }
  6258. res.body.append(buf, n);
  6259. return true;
  6260. });
  6261. auto progress = [&](uint64_t current, uint64_t total) {
  6262. if (!req.progress || redirect) { return true; }
  6263. auto ret = req.progress(current, total);
  6264. if (!ret) { error = Error::Canceled; }
  6265. return ret;
  6266. };
  6267. int dummy_status;
  6268. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  6269. dummy_status, std::move(progress), std::move(out),
  6270. decompress_)) {
  6271. if (error != Error::Canceled) { error = Error::Read; }
  6272. return false;
  6273. }
  6274. }
  6275. // Log
  6276. if (logger_) { logger_(req, res); }
  6277. return true;
  6278. }
  6279. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  6280. const std::string &boundary, const MultipartFormDataItems &items,
  6281. const MultipartFormDataProviderItems &provider_items) const {
  6282. size_t cur_item = 0;
  6283. size_t cur_start = 0;
  6284. // cur_item and cur_start are copied to within the std::function and maintain
  6285. // state between successive calls
  6286. return [&, cur_item, cur_start](size_t offset,
  6287. DataSink &sink) mutable -> bool {
  6288. if (!offset && !items.empty()) {
  6289. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  6290. return true;
  6291. } else if (cur_item < provider_items.size()) {
  6292. if (!cur_start) {
  6293. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  6294. provider_items[cur_item], boundary);
  6295. offset += begin.size();
  6296. cur_start = offset;
  6297. sink.os << begin;
  6298. }
  6299. DataSink cur_sink;
  6300. auto has_data = true;
  6301. cur_sink.write = sink.write;
  6302. cur_sink.done = [&]() { has_data = false; };
  6303. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  6304. return false;
  6305. }
  6306. if (!has_data) {
  6307. sink.os << detail::serialize_multipart_formdata_item_end();
  6308. cur_item++;
  6309. cur_start = 0;
  6310. }
  6311. return true;
  6312. } else {
  6313. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  6314. sink.done();
  6315. return true;
  6316. }
  6317. };
  6318. }
  6319. inline bool
  6320. ClientImpl::process_socket(const Socket &socket,
  6321. std::function<bool(Stream &strm)> callback) {
  6322. return detail::process_client_socket(
  6323. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6324. write_timeout_usec_, std::move(callback));
  6325. }
  6326. inline bool ClientImpl::is_ssl() const { return false; }
  6327. inline Result ClientImpl::Get(const std::string &path) {
  6328. return Get(path, Headers(), Progress());
  6329. }
  6330. inline Result ClientImpl::Get(const std::string &path, Progress progress) {
  6331. return Get(path, Headers(), std::move(progress));
  6332. }
  6333. inline Result ClientImpl::Get(const std::string &path, const Headers &headers) {
  6334. return Get(path, headers, Progress());
  6335. }
  6336. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  6337. Progress progress) {
  6338. Request req;
  6339. req.method = "GET";
  6340. req.path = path;
  6341. req.headers = headers;
  6342. req.progress = std::move(progress);
  6343. return send_(std::move(req));
  6344. }
  6345. inline Result ClientImpl::Get(const std::string &path,
  6346. ContentReceiver content_receiver) {
  6347. return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr);
  6348. }
  6349. inline Result ClientImpl::Get(const std::string &path,
  6350. ContentReceiver content_receiver,
  6351. Progress progress) {
  6352. return Get(path, Headers(), nullptr, std::move(content_receiver),
  6353. std::move(progress));
  6354. }
  6355. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  6356. ContentReceiver content_receiver) {
  6357. return Get(path, headers, nullptr, std::move(content_receiver), nullptr);
  6358. }
  6359. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  6360. ContentReceiver content_receiver,
  6361. Progress progress) {
  6362. return Get(path, headers, nullptr, std::move(content_receiver),
  6363. std::move(progress));
  6364. }
  6365. inline Result ClientImpl::Get(const std::string &path,
  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, const Headers &headers,
  6372. ResponseHandler response_handler,
  6373. ContentReceiver content_receiver) {
  6374. return Get(path, headers, std::move(response_handler),
  6375. std::move(content_receiver), nullptr);
  6376. }
  6377. inline Result ClientImpl::Get(const std::string &path,
  6378. ResponseHandler response_handler,
  6379. ContentReceiver content_receiver,
  6380. Progress progress) {
  6381. return Get(path, Headers(), std::move(response_handler),
  6382. std::move(content_receiver), std::move(progress));
  6383. }
  6384. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  6385. ResponseHandler response_handler,
  6386. ContentReceiver content_receiver,
  6387. Progress progress) {
  6388. Request req;
  6389. req.method = "GET";
  6390. req.path = path;
  6391. req.headers = headers;
  6392. req.response_handler = std::move(response_handler);
  6393. req.content_receiver =
  6394. [content_receiver](const char *data, size_t data_length,
  6395. uint64_t /*offset*/, uint64_t /*total_length*/) {
  6396. return content_receiver(data, data_length);
  6397. };
  6398. req.progress = std::move(progress);
  6399. return send_(std::move(req));
  6400. }
  6401. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  6402. const Headers &headers, Progress progress) {
  6403. if (params.empty()) { return Get(path, headers); }
  6404. std::string path_with_query = append_query_params(path, params);
  6405. return Get(path_with_query, headers, std::move(progress));
  6406. }
  6407. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  6408. const Headers &headers,
  6409. ContentReceiver content_receiver,
  6410. Progress progress) {
  6411. return Get(path, params, headers, nullptr, std::move(content_receiver),
  6412. std::move(progress));
  6413. }
  6414. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  6415. const Headers &headers,
  6416. ResponseHandler response_handler,
  6417. ContentReceiver content_receiver,
  6418. Progress progress) {
  6419. if (params.empty()) {
  6420. return Get(path, headers, std::move(response_handler),
  6421. std::move(content_receiver), std::move(progress));
  6422. }
  6423. std::string path_with_query = append_query_params(path, params);
  6424. return Get(path_with_query, headers, std::move(response_handler),
  6425. std::move(content_receiver), std::move(progress));
  6426. }
  6427. inline Result ClientImpl::Head(const std::string &path) {
  6428. return Head(path, Headers());
  6429. }
  6430. inline Result ClientImpl::Head(const std::string &path,
  6431. const Headers &headers) {
  6432. Request req;
  6433. req.method = "HEAD";
  6434. req.headers = headers;
  6435. req.path = path;
  6436. return send_(std::move(req));
  6437. }
  6438. inline Result ClientImpl::Post(const std::string &path) {
  6439. return Post(path, std::string(), std::string());
  6440. }
  6441. inline Result ClientImpl::Post(const std::string &path,
  6442. const Headers &headers) {
  6443. return Post(path, headers, nullptr, 0, std::string());
  6444. }
  6445. inline Result ClientImpl::Post(const std::string &path, const char *body,
  6446. size_t content_length,
  6447. const std::string &content_type) {
  6448. return Post(path, Headers(), body, content_length, content_type);
  6449. }
  6450. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6451. const char *body, size_t content_length,
  6452. const std::string &content_type) {
  6453. return send_with_content_provider("POST", path, headers, body, content_length,
  6454. nullptr, nullptr, content_type);
  6455. }
  6456. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  6457. const std::string &content_type) {
  6458. return Post(path, Headers(), body, content_type);
  6459. }
  6460. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6461. const std::string &body,
  6462. const std::string &content_type) {
  6463. return send_with_content_provider("POST", path, headers, body.data(),
  6464. body.size(), nullptr, nullptr,
  6465. content_type);
  6466. }
  6467. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  6468. return Post(path, Headers(), params);
  6469. }
  6470. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  6471. ContentProvider content_provider,
  6472. const std::string &content_type) {
  6473. return Post(path, Headers(), content_length, std::move(content_provider),
  6474. content_type);
  6475. }
  6476. inline Result ClientImpl::Post(const std::string &path,
  6477. ContentProviderWithoutLength content_provider,
  6478. const std::string &content_type) {
  6479. return Post(path, Headers(), std::move(content_provider), content_type);
  6480. }
  6481. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6482. size_t content_length,
  6483. ContentProvider content_provider,
  6484. const std::string &content_type) {
  6485. return send_with_content_provider("POST", path, headers, nullptr,
  6486. content_length, std::move(content_provider),
  6487. nullptr, content_type);
  6488. }
  6489. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6490. ContentProviderWithoutLength content_provider,
  6491. const std::string &content_type) {
  6492. return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
  6493. std::move(content_provider), content_type);
  6494. }
  6495. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6496. const Params &params) {
  6497. auto query = detail::params_to_query_str(params);
  6498. return Post(path, headers, query, "application/x-www-form-urlencoded");
  6499. }
  6500. inline Result ClientImpl::Post(const std::string &path,
  6501. const MultipartFormDataItems &items) {
  6502. return Post(path, Headers(), items);
  6503. }
  6504. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6505. const MultipartFormDataItems &items) {
  6506. const auto &boundary = detail::make_multipart_data_boundary();
  6507. const auto &content_type =
  6508. detail::serialize_multipart_formdata_get_content_type(boundary);
  6509. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6510. return Post(path, headers, body, content_type);
  6511. }
  6512. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6513. const MultipartFormDataItems &items,
  6514. const std::string &boundary) {
  6515. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  6516. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  6517. }
  6518. const auto &content_type =
  6519. detail::serialize_multipart_formdata_get_content_type(boundary);
  6520. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6521. return Post(path, headers, body, content_type);
  6522. }
  6523. inline Result
  6524. ClientImpl::Post(const std::string &path, const Headers &headers,
  6525. const MultipartFormDataItems &items,
  6526. const MultipartFormDataProviderItems &provider_items) {
  6527. const auto &boundary = detail::make_multipart_data_boundary();
  6528. const auto &content_type =
  6529. detail::serialize_multipart_formdata_get_content_type(boundary);
  6530. return send_with_content_provider(
  6531. "POST", path, headers, nullptr, 0, nullptr,
  6532. get_multipart_content_provider(boundary, items, provider_items),
  6533. content_type);
  6534. }
  6535. inline Result ClientImpl::Put(const std::string &path) {
  6536. return Put(path, std::string(), std::string());
  6537. }
  6538. inline Result ClientImpl::Put(const std::string &path, const char *body,
  6539. size_t content_length,
  6540. const std::string &content_type) {
  6541. return Put(path, Headers(), body, content_length, content_type);
  6542. }
  6543. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6544. const char *body, size_t content_length,
  6545. const std::string &content_type) {
  6546. return send_with_content_provider("PUT", path, headers, body, content_length,
  6547. nullptr, nullptr, content_type);
  6548. }
  6549. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  6550. const std::string &content_type) {
  6551. return Put(path, Headers(), body, content_type);
  6552. }
  6553. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6554. const std::string &body,
  6555. const std::string &content_type) {
  6556. return send_with_content_provider("PUT", path, headers, body.data(),
  6557. body.size(), nullptr, nullptr,
  6558. content_type);
  6559. }
  6560. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  6561. ContentProvider content_provider,
  6562. const std::string &content_type) {
  6563. return Put(path, Headers(), content_length, std::move(content_provider),
  6564. content_type);
  6565. }
  6566. inline Result ClientImpl::Put(const std::string &path,
  6567. ContentProviderWithoutLength content_provider,
  6568. const std::string &content_type) {
  6569. return Put(path, Headers(), std::move(content_provider), content_type);
  6570. }
  6571. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6572. size_t content_length,
  6573. ContentProvider content_provider,
  6574. const std::string &content_type) {
  6575. return send_with_content_provider("PUT", path, headers, nullptr,
  6576. content_length, std::move(content_provider),
  6577. nullptr, content_type);
  6578. }
  6579. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6580. ContentProviderWithoutLength content_provider,
  6581. const std::string &content_type) {
  6582. return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
  6583. std::move(content_provider), content_type);
  6584. }
  6585. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  6586. return Put(path, Headers(), params);
  6587. }
  6588. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6589. const Params &params) {
  6590. auto query = detail::params_to_query_str(params);
  6591. return Put(path, headers, query, "application/x-www-form-urlencoded");
  6592. }
  6593. inline Result ClientImpl::Put(const std::string &path,
  6594. const MultipartFormDataItems &items) {
  6595. return Put(path, Headers(), items);
  6596. }
  6597. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6598. const MultipartFormDataItems &items) {
  6599. const auto &boundary = detail::make_multipart_data_boundary();
  6600. const auto &content_type =
  6601. detail::serialize_multipart_formdata_get_content_type(boundary);
  6602. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6603. return Put(path, headers, body, content_type);
  6604. }
  6605. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6606. const MultipartFormDataItems &items,
  6607. const std::string &boundary) {
  6608. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  6609. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  6610. }
  6611. const auto &content_type =
  6612. detail::serialize_multipart_formdata_get_content_type(boundary);
  6613. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6614. return Put(path, headers, body, content_type);
  6615. }
  6616. inline Result
  6617. ClientImpl::Put(const std::string &path, const Headers &headers,
  6618. const MultipartFormDataItems &items,
  6619. const MultipartFormDataProviderItems &provider_items) {
  6620. const auto &boundary = detail::make_multipart_data_boundary();
  6621. const auto &content_type =
  6622. detail::serialize_multipart_formdata_get_content_type(boundary);
  6623. return send_with_content_provider(
  6624. "PUT", path, headers, nullptr, 0, nullptr,
  6625. get_multipart_content_provider(boundary, items, provider_items),
  6626. content_type);
  6627. }
  6628. inline Result ClientImpl::Patch(const std::string &path) {
  6629. return Patch(path, std::string(), std::string());
  6630. }
  6631. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  6632. size_t content_length,
  6633. const std::string &content_type) {
  6634. return Patch(path, Headers(), body, content_length, content_type);
  6635. }
  6636. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6637. const char *body, size_t content_length,
  6638. const std::string &content_type) {
  6639. return send_with_content_provider("PATCH", path, headers, body,
  6640. content_length, nullptr, nullptr,
  6641. content_type);
  6642. }
  6643. inline Result ClientImpl::Patch(const std::string &path,
  6644. const std::string &body,
  6645. const std::string &content_type) {
  6646. return Patch(path, Headers(), body, content_type);
  6647. }
  6648. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6649. const std::string &body,
  6650. const std::string &content_type) {
  6651. return send_with_content_provider("PATCH", path, headers, body.data(),
  6652. body.size(), nullptr, nullptr,
  6653. content_type);
  6654. }
  6655. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  6656. ContentProvider content_provider,
  6657. const std::string &content_type) {
  6658. return Patch(path, Headers(), content_length, std::move(content_provider),
  6659. content_type);
  6660. }
  6661. inline Result ClientImpl::Patch(const std::string &path,
  6662. ContentProviderWithoutLength content_provider,
  6663. const std::string &content_type) {
  6664. return Patch(path, Headers(), std::move(content_provider), content_type);
  6665. }
  6666. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6667. size_t content_length,
  6668. ContentProvider content_provider,
  6669. const std::string &content_type) {
  6670. return send_with_content_provider("PATCH", path, headers, nullptr,
  6671. content_length, std::move(content_provider),
  6672. nullptr, content_type);
  6673. }
  6674. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6675. ContentProviderWithoutLength content_provider,
  6676. const std::string &content_type) {
  6677. return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
  6678. std::move(content_provider), content_type);
  6679. }
  6680. inline Result ClientImpl::Delete(const std::string &path) {
  6681. return Delete(path, Headers(), std::string(), std::string());
  6682. }
  6683. inline Result ClientImpl::Delete(const std::string &path,
  6684. const Headers &headers) {
  6685. return Delete(path, headers, std::string(), std::string());
  6686. }
  6687. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  6688. size_t content_length,
  6689. const std::string &content_type) {
  6690. return Delete(path, Headers(), body, content_length, content_type);
  6691. }
  6692. inline Result ClientImpl::Delete(const std::string &path,
  6693. const Headers &headers, const char *body,
  6694. size_t content_length,
  6695. const std::string &content_type) {
  6696. Request req;
  6697. req.method = "DELETE";
  6698. req.headers = headers;
  6699. req.path = path;
  6700. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  6701. req.body.assign(body, content_length);
  6702. return send_(std::move(req));
  6703. }
  6704. inline Result ClientImpl::Delete(const std::string &path,
  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::Delete(const std::string &path,
  6710. const Headers &headers,
  6711. const std::string &body,
  6712. const std::string &content_type) {
  6713. return Delete(path, headers, body.data(), body.size(), content_type);
  6714. }
  6715. inline Result ClientImpl::Options(const std::string &path) {
  6716. return Options(path, Headers());
  6717. }
  6718. inline Result ClientImpl::Options(const std::string &path,
  6719. const Headers &headers) {
  6720. Request req;
  6721. req.method = "OPTIONS";
  6722. req.headers = headers;
  6723. req.path = path;
  6724. return send_(std::move(req));
  6725. }
  6726. inline void ClientImpl::stop() {
  6727. std::lock_guard<std::mutex> guard(socket_mutex_);
  6728. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  6729. // do is to shutdown_socket, so that threads using this socket suddenly
  6730. // discover they can't read/write any more and error out. Everything else
  6731. // (closing the socket, shutting ssl down) is unsafe because these actions are
  6732. // not thread-safe.
  6733. if (socket_requests_in_flight_ > 0) {
  6734. shutdown_socket(socket_);
  6735. // Aside from that, we set a flag for the socket to be closed when we're
  6736. // done.
  6737. socket_should_be_closed_when_request_is_done_ = true;
  6738. return;
  6739. }
  6740. // Otherwise, still holding the mutex, we can shut everything down ourselves
  6741. shutdown_ssl(socket_, true);
  6742. shutdown_socket(socket_);
  6743. close_socket(socket_);
  6744. }
  6745. inline std::string ClientImpl::host() const { return host_; }
  6746. inline int ClientImpl::port() const { return port_; }
  6747. inline size_t ClientImpl::is_socket_open() const {
  6748. std::lock_guard<std::mutex> guard(socket_mutex_);
  6749. return socket_.is_open();
  6750. }
  6751. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  6752. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  6753. connection_timeout_sec_ = sec;
  6754. connection_timeout_usec_ = usec;
  6755. }
  6756. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  6757. read_timeout_sec_ = sec;
  6758. read_timeout_usec_ = usec;
  6759. }
  6760. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  6761. write_timeout_sec_ = sec;
  6762. write_timeout_usec_ = usec;
  6763. }
  6764. inline void ClientImpl::set_basic_auth(const std::string &username,
  6765. const std::string &password) {
  6766. basic_auth_username_ = username;
  6767. basic_auth_password_ = password;
  6768. }
  6769. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  6770. bearer_token_auth_token_ = token;
  6771. }
  6772. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6773. inline void ClientImpl::set_digest_auth(const std::string &username,
  6774. const std::string &password) {
  6775. digest_auth_username_ = username;
  6776. digest_auth_password_ = password;
  6777. }
  6778. #endif
  6779. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  6780. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  6781. inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; }
  6782. inline void
  6783. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  6784. addr_map_ = std::move(addr_map);
  6785. }
  6786. inline void ClientImpl::set_default_headers(Headers headers) {
  6787. default_headers_ = std::move(headers);
  6788. }
  6789. inline void ClientImpl::set_header_writer(
  6790. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  6791. header_writer_ = writer;
  6792. }
  6793. inline void ClientImpl::set_address_family(int family) {
  6794. address_family_ = family;
  6795. }
  6796. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  6797. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  6798. socket_options_ = std::move(socket_options);
  6799. }
  6800. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  6801. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  6802. inline void ClientImpl::set_interface(const std::string &intf) {
  6803. interface_ = intf;
  6804. }
  6805. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  6806. proxy_host_ = host;
  6807. proxy_port_ = port;
  6808. }
  6809. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  6810. const std::string &password) {
  6811. proxy_basic_auth_username_ = username;
  6812. proxy_basic_auth_password_ = password;
  6813. }
  6814. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  6815. proxy_bearer_token_auth_token_ = token;
  6816. }
  6817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6818. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  6819. const std::string &password) {
  6820. proxy_digest_auth_username_ = username;
  6821. proxy_digest_auth_password_ = password;
  6822. }
  6823. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  6824. const std::string &ca_cert_dir_path) {
  6825. ca_cert_file_path_ = ca_cert_file_path;
  6826. ca_cert_dir_path_ = ca_cert_dir_path;
  6827. }
  6828. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  6829. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  6830. ca_cert_store_ = ca_cert_store;
  6831. }
  6832. }
  6833. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  6834. std::size_t size) const {
  6835. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  6836. if (!mem) { return nullptr; }
  6837. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  6838. if (!inf) {
  6839. BIO_free_all(mem);
  6840. return nullptr;
  6841. }
  6842. auto cts = X509_STORE_new();
  6843. if (cts) {
  6844. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  6845. auto itmp = sk_X509_INFO_value(inf, i);
  6846. if (!itmp) { continue; }
  6847. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  6848. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  6849. }
  6850. }
  6851. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  6852. BIO_free_all(mem);
  6853. return cts;
  6854. }
  6855. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  6856. server_certificate_verification_ = enabled;
  6857. }
  6858. #endif
  6859. inline void ClientImpl::set_logger(Logger logger) {
  6860. logger_ = std::move(logger);
  6861. }
  6862. /*
  6863. * SSL Implementation
  6864. */
  6865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6866. namespace detail {
  6867. template <typename U, typename V>
  6868. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  6869. U SSL_connect_or_accept, V setup) {
  6870. SSL *ssl = nullptr;
  6871. {
  6872. std::lock_guard<std::mutex> guard(ctx_mutex);
  6873. ssl = SSL_new(ctx);
  6874. }
  6875. if (ssl) {
  6876. set_nonblocking(sock, true);
  6877. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  6878. BIO_set_nbio(bio, 1);
  6879. SSL_set_bio(ssl, bio, bio);
  6880. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  6881. SSL_shutdown(ssl);
  6882. {
  6883. std::lock_guard<std::mutex> guard(ctx_mutex);
  6884. SSL_free(ssl);
  6885. }
  6886. set_nonblocking(sock, false);
  6887. return nullptr;
  6888. }
  6889. BIO_set_nbio(bio, 0);
  6890. set_nonblocking(sock, false);
  6891. }
  6892. return ssl;
  6893. }
  6894. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,
  6895. bool shutdown_gracefully) {
  6896. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  6897. // the remote has closed the network connection
  6898. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  6899. // best-efforts.
  6900. if (shutdown_gracefully) { SSL_shutdown(ssl); }
  6901. std::lock_guard<std::mutex> guard(ctx_mutex);
  6902. SSL_free(ssl);
  6903. }
  6904. template <typename U>
  6905. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  6906. U ssl_connect_or_accept,
  6907. time_t timeout_sec,
  6908. time_t timeout_usec) {
  6909. auto res = 0;
  6910. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  6911. auto err = SSL_get_error(ssl, res);
  6912. switch (err) {
  6913. case SSL_ERROR_WANT_READ:
  6914. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  6915. break;
  6916. case SSL_ERROR_WANT_WRITE:
  6917. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  6918. break;
  6919. default: break;
  6920. }
  6921. return false;
  6922. }
  6923. return true;
  6924. }
  6925. template <typename T>
  6926. inline bool process_server_socket_ssl(
  6927. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  6928. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  6929. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  6930. time_t write_timeout_usec, T callback) {
  6931. return process_server_socket_core(
  6932. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  6933. [&](bool close_connection, bool &connection_closed) {
  6934. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  6935. write_timeout_sec, write_timeout_usec);
  6936. return callback(strm, close_connection, connection_closed);
  6937. });
  6938. }
  6939. template <typename T>
  6940. inline bool
  6941. process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec,
  6942. time_t read_timeout_usec, time_t write_timeout_sec,
  6943. time_t write_timeout_usec, T callback) {
  6944. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  6945. write_timeout_sec, write_timeout_usec);
  6946. return callback(strm);
  6947. }
  6948. class SSLInit {
  6949. public:
  6950. SSLInit() {
  6951. OPENSSL_init_ssl(
  6952. OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  6953. }
  6954. };
  6955. // SSL socket stream implementation
  6956. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
  6957. time_t read_timeout_sec,
  6958. time_t read_timeout_usec,
  6959. time_t write_timeout_sec,
  6960. time_t write_timeout_usec)
  6961. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  6962. read_timeout_usec_(read_timeout_usec),
  6963. write_timeout_sec_(write_timeout_sec),
  6964. write_timeout_usec_(write_timeout_usec) {
  6965. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  6966. }
  6967. inline SSLSocketStream::~SSLSocketStream() = default;
  6968. inline bool SSLSocketStream::is_readable() const {
  6969. return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  6970. }
  6971. inline bool SSLSocketStream::is_writable() const {
  6972. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  6973. is_socket_alive(sock_);
  6974. }
  6975. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  6976. if (SSL_pending(ssl_) > 0) {
  6977. return SSL_read(ssl_, ptr, static_cast<int>(size));
  6978. } else if (is_readable()) {
  6979. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  6980. if (ret < 0) {
  6981. auto err = SSL_get_error(ssl_, ret);
  6982. auto n = 1000;
  6983. #ifdef _WIN32
  6984. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  6985. (err == SSL_ERROR_SYSCALL &&
  6986. WSAGetLastError() == WSAETIMEDOUT))) {
  6987. #else
  6988. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  6989. #endif
  6990. if (SSL_pending(ssl_) > 0) {
  6991. return SSL_read(ssl_, ptr, static_cast<int>(size));
  6992. } else if (is_readable()) {
  6993. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  6994. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  6995. if (ret >= 0) { return ret; }
  6996. err = SSL_get_error(ssl_, ret);
  6997. } else {
  6998. return -1;
  6999. }
  7000. }
  7001. }
  7002. return ret;
  7003. }
  7004. return -1;
  7005. }
  7006. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  7007. if (is_writable()) {
  7008. auto handle_size = static_cast<int>(
  7009. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  7010. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  7011. if (ret < 0) {
  7012. auto err = SSL_get_error(ssl_, ret);
  7013. auto n = 1000;
  7014. #ifdef _WIN32
  7015. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  7016. (err == SSL_ERROR_SYSCALL &&
  7017. WSAGetLastError() == WSAETIMEDOUT))) {
  7018. #else
  7019. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  7020. #endif
  7021. if (is_writable()) {
  7022. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  7023. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  7024. if (ret >= 0) { return ret; }
  7025. err = SSL_get_error(ssl_, ret);
  7026. } else {
  7027. return -1;
  7028. }
  7029. }
  7030. }
  7031. return ret;
  7032. }
  7033. return -1;
  7034. }
  7035. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  7036. int &port) const {
  7037. detail::get_remote_ip_and_port(sock_, ip, port);
  7038. }
  7039. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  7040. int &port) const {
  7041. detail::get_local_ip_and_port(sock_, ip, port);
  7042. }
  7043. inline socket_t SSLSocketStream::socket() const { return sock_; }
  7044. static SSLInit sslinit_;
  7045. } // namespace detail
  7046. // SSL HTTP server implementation
  7047. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  7048. const char *client_ca_cert_file_path,
  7049. const char *client_ca_cert_dir_path,
  7050. const char *private_key_password) {
  7051. ctx_ = SSL_CTX_new(TLS_server_method());
  7052. if (ctx_) {
  7053. SSL_CTX_set_options(ctx_,
  7054. SSL_OP_NO_COMPRESSION |
  7055. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7056. SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION);
  7057. // add default password callback before opening encrypted private key
  7058. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  7059. SSL_CTX_set_default_passwd_cb_userdata(
  7060. ctx_,
  7061. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  7062. }
  7063. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  7064. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  7065. 1) {
  7066. SSL_CTX_free(ctx_);
  7067. ctx_ = nullptr;
  7068. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  7069. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  7070. client_ca_cert_dir_path);
  7071. SSL_CTX_set_verify(
  7072. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  7073. }
  7074. }
  7075. }
  7076. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  7077. X509_STORE *client_ca_cert_store) {
  7078. ctx_ = SSL_CTX_new(TLS_server_method());
  7079. if (ctx_) {
  7080. SSL_CTX_set_options(ctx_,
  7081. SSL_OP_NO_COMPRESSION |
  7082. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7083. SSL_CTX_set_min_proto_version(ctx_, TLS1_1_VERSION);
  7084. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  7085. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  7086. SSL_CTX_free(ctx_);
  7087. ctx_ = nullptr;
  7088. } else if (client_ca_cert_store) {
  7089. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  7090. SSL_CTX_set_verify(
  7091. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  7092. }
  7093. }
  7094. }
  7095. inline SSLServer::SSLServer(
  7096. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  7097. ctx_ = SSL_CTX_new(TLS_method());
  7098. if (ctx_) {
  7099. if (!setup_ssl_ctx_callback(*ctx_)) {
  7100. SSL_CTX_free(ctx_);
  7101. ctx_ = nullptr;
  7102. }
  7103. }
  7104. }
  7105. inline SSLServer::~SSLServer() {
  7106. if (ctx_) { SSL_CTX_free(ctx_); }
  7107. }
  7108. inline bool SSLServer::is_valid() const { return ctx_; }
  7109. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  7110. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  7111. auto ssl = detail::ssl_new(
  7112. sock, ctx_, ctx_mutex_,
  7113. [&](SSL *ssl2) {
  7114. return detail::ssl_connect_or_accept_nonblocking(
  7115. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_);
  7116. },
  7117. [](SSL * /*ssl2*/) { return true; });
  7118. auto ret = false;
  7119. if (ssl) {
  7120. ret = detail::process_server_socket_ssl(
  7121. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  7122. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7123. write_timeout_usec_,
  7124. [this, ssl](Stream &strm, bool close_connection,
  7125. bool &connection_closed) {
  7126. return process_request(strm, close_connection, connection_closed,
  7127. [&](Request &req) { req.ssl = ssl; });
  7128. });
  7129. // Shutdown gracefully if the result seemed successful, non-gracefully if
  7130. // the connection appeared to be closed.
  7131. const bool shutdown_gracefully = ret;
  7132. detail::ssl_delete(ctx_mutex_, ssl, shutdown_gracefully);
  7133. }
  7134. detail::shutdown_socket(sock);
  7135. detail::close_socket(sock);
  7136. return ret;
  7137. }
  7138. // SSL HTTP client implementation
  7139. inline SSLClient::SSLClient(const std::string &host)
  7140. : SSLClient(host, 443, std::string(), std::string()) {}
  7141. inline SSLClient::SSLClient(const std::string &host, int port)
  7142. : SSLClient(host, port, std::string(), std::string()) {}
  7143. inline SSLClient::SSLClient(const std::string &host, int port,
  7144. const std::string &client_cert_path,
  7145. const std::string &client_key_path)
  7146. : ClientImpl(host, port, client_cert_path, client_key_path) {
  7147. ctx_ = SSL_CTX_new(TLS_client_method());
  7148. detail::split(&host_[0], &host_[host_.size()], '.',
  7149. [&](const char *b, const char *e) {
  7150. host_components_.emplace_back(b, e);
  7151. });
  7152. if (!client_cert_path.empty() && !client_key_path.empty()) {
  7153. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  7154. SSL_FILETYPE_PEM) != 1 ||
  7155. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  7156. SSL_FILETYPE_PEM) != 1) {
  7157. SSL_CTX_free(ctx_);
  7158. ctx_ = nullptr;
  7159. }
  7160. }
  7161. }
  7162. inline SSLClient::SSLClient(const std::string &host, int port,
  7163. X509 *client_cert, EVP_PKEY *client_key)
  7164. : ClientImpl(host, port) {
  7165. ctx_ = SSL_CTX_new(TLS_client_method());
  7166. detail::split(&host_[0], &host_[host_.size()], '.',
  7167. [&](const char *b, const char *e) {
  7168. host_components_.emplace_back(b, e);
  7169. });
  7170. if (client_cert != nullptr && client_key != nullptr) {
  7171. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  7172. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  7173. SSL_CTX_free(ctx_);
  7174. ctx_ = nullptr;
  7175. }
  7176. }
  7177. }
  7178. inline SSLClient::~SSLClient() {
  7179. if (ctx_) { SSL_CTX_free(ctx_); }
  7180. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  7181. // base function rather than the derived function once we get to the
  7182. // base class destructor, and won't free the SSL (causing a leak).
  7183. shutdown_ssl_impl(socket_, true);
  7184. }
  7185. inline bool SSLClient::is_valid() const { return ctx_; }
  7186. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  7187. if (ca_cert_store) {
  7188. if (ctx_) {
  7189. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  7190. // Free memory allocated for old cert and use new store `ca_cert_store`
  7191. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  7192. }
  7193. } else {
  7194. X509_STORE_free(ca_cert_store);
  7195. }
  7196. }
  7197. }
  7198. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  7199. std::size_t size) {
  7200. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  7201. }
  7202. inline long SSLClient::get_openssl_verify_result() const {
  7203. return verify_result_;
  7204. }
  7205. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  7206. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  7207. return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
  7208. }
  7209. // Assumes that socket_mutex_ is locked and that there are no requests in flight
  7210. inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res,
  7211. bool &success, Error &error) {
  7212. success = true;
  7213. Response proxy_res;
  7214. if (!detail::process_client_socket(
  7215. socket.sock, read_timeout_sec_, read_timeout_usec_,
  7216. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  7217. Request req2;
  7218. req2.method = "CONNECT";
  7219. req2.path = host_and_port_;
  7220. return process_request(strm, req2, proxy_res, false, error);
  7221. })) {
  7222. // Thread-safe to close everything because we are assuming there are no
  7223. // requests in flight
  7224. shutdown_ssl(socket, true);
  7225. shutdown_socket(socket);
  7226. close_socket(socket);
  7227. success = false;
  7228. return false;
  7229. }
  7230. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  7231. if (!proxy_digest_auth_username_.empty() &&
  7232. !proxy_digest_auth_password_.empty()) {
  7233. std::map<std::string, std::string> auth;
  7234. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  7235. proxy_res = Response();
  7236. if (!detail::process_client_socket(
  7237. socket.sock, read_timeout_sec_, read_timeout_usec_,
  7238. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  7239. Request req3;
  7240. req3.method = "CONNECT";
  7241. req3.path = host_and_port_;
  7242. req3.headers.insert(detail::make_digest_authentication_header(
  7243. req3, auth, 1, detail::random_string(10),
  7244. proxy_digest_auth_username_, proxy_digest_auth_password_,
  7245. true));
  7246. return process_request(strm, req3, proxy_res, false, error);
  7247. })) {
  7248. // Thread-safe to close everything because we are assuming there are
  7249. // no requests in flight
  7250. shutdown_ssl(socket, true);
  7251. shutdown_socket(socket);
  7252. close_socket(socket);
  7253. success = false;
  7254. return false;
  7255. }
  7256. }
  7257. }
  7258. }
  7259. // If status code is not 200, proxy request is failed.
  7260. // Set error to ProxyConnection and return proxy response
  7261. // as the response of the request
  7262. if (proxy_res.status != StatusCode::OK_200) {
  7263. error = Error::ProxyConnection;
  7264. res = std::move(proxy_res);
  7265. // Thread-safe to close everything because we are assuming there are
  7266. // no requests in flight
  7267. shutdown_ssl(socket, true);
  7268. shutdown_socket(socket);
  7269. close_socket(socket);
  7270. return false;
  7271. }
  7272. return true;
  7273. }
  7274. inline bool SSLClient::load_certs() {
  7275. auto ret = true;
  7276. std::call_once(initialize_cert_, [&]() {
  7277. std::lock_guard<std::mutex> guard(ctx_mutex_);
  7278. if (!ca_cert_file_path_.empty()) {
  7279. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  7280. nullptr)) {
  7281. ret = false;
  7282. }
  7283. } else if (!ca_cert_dir_path_.empty()) {
  7284. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  7285. ca_cert_dir_path_.c_str())) {
  7286. ret = false;
  7287. }
  7288. } else {
  7289. auto loaded = false;
  7290. #ifdef _WIN32
  7291. loaded =
  7292. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  7293. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__)
  7294. #if TARGET_OS_OSX
  7295. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  7296. #endif // TARGET_OS_OSX
  7297. #endif // _WIN32
  7298. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  7299. }
  7300. });
  7301. return ret;
  7302. }
  7303. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  7304. auto ssl = detail::ssl_new(
  7305. socket.sock, ctx_, ctx_mutex_,
  7306. [&](SSL *ssl2) {
  7307. if (server_certificate_verification_) {
  7308. if (!load_certs()) {
  7309. error = Error::SSLLoadingCerts;
  7310. return false;
  7311. }
  7312. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  7313. }
  7314. if (!detail::ssl_connect_or_accept_nonblocking(
  7315. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  7316. connection_timeout_usec_)) {
  7317. error = Error::SSLConnection;
  7318. return false;
  7319. }
  7320. if (server_certificate_verification_) {
  7321. verify_result_ = SSL_get_verify_result(ssl2);
  7322. if (verify_result_ != X509_V_OK) {
  7323. error = Error::SSLServerVerification;
  7324. return false;
  7325. }
  7326. auto server_cert = SSL_get1_peer_certificate(ssl2);
  7327. if (server_cert == nullptr) {
  7328. error = Error::SSLServerVerification;
  7329. return false;
  7330. }
  7331. if (!verify_host(server_cert)) {
  7332. X509_free(server_cert);
  7333. error = Error::SSLServerVerification;
  7334. return false;
  7335. }
  7336. X509_free(server_cert);
  7337. }
  7338. return true;
  7339. },
  7340. [&](SSL *ssl2) {
  7341. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  7342. // -Wold-style-cast warning
  7343. // SSL_set_tlsext_host_name(ssl2, host_.c_str());
  7344. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  7345. static_cast<void *>(const_cast<char *>(host_.c_str())));
  7346. return true;
  7347. });
  7348. if (ssl) {
  7349. socket.ssl = ssl;
  7350. return true;
  7351. }
  7352. shutdown_socket(socket);
  7353. close_socket(socket);
  7354. return false;
  7355. }
  7356. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  7357. shutdown_ssl_impl(socket, shutdown_gracefully);
  7358. }
  7359. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  7360. bool shutdown_gracefully) {
  7361. if (socket.sock == INVALID_SOCKET) {
  7362. assert(socket.ssl == nullptr);
  7363. return;
  7364. }
  7365. if (socket.ssl) {
  7366. detail::ssl_delete(ctx_mutex_, socket.ssl, shutdown_gracefully);
  7367. socket.ssl = nullptr;
  7368. }
  7369. assert(socket.ssl == nullptr);
  7370. }
  7371. inline bool
  7372. SSLClient::process_socket(const Socket &socket,
  7373. std::function<bool(Stream &strm)> callback) {
  7374. assert(socket.ssl);
  7375. return detail::process_client_socket_ssl(
  7376. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  7377. write_timeout_sec_, write_timeout_usec_, std::move(callback));
  7378. }
  7379. inline bool SSLClient::is_ssl() const { return true; }
  7380. inline bool SSLClient::verify_host(X509 *server_cert) const {
  7381. /* Quote from RFC2818 section 3.1 "Server Identity"
  7382. If a subjectAltName extension of type dNSName is present, that MUST
  7383. be used as the identity. Otherwise, the (most specific) Common Name
  7384. field in the Subject field of the certificate MUST be used. Although
  7385. the use of the Common Name is existing practice, it is deprecated and
  7386. Certification Authorities are encouraged to use the dNSName instead.
  7387. Matching is performed using the matching rules specified by
  7388. [RFC2459]. If more than one identity of a given type is present in
  7389. the certificate (e.g., more than one dNSName name, a match in any one
  7390. of the set is considered acceptable.) Names may contain the wildcard
  7391. character * which is considered to match any single domain name
  7392. component or component fragment. E.g., *.a.com matches foo.a.com but
  7393. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  7394. In some cases, the URI is specified as an IP address rather than a
  7395. hostname. In this case, the iPAddress subjectAltName must be present
  7396. in the certificate and must exactly match the IP in the URI.
  7397. */
  7398. return verify_host_with_subject_alt_name(server_cert) ||
  7399. verify_host_with_common_name(server_cert);
  7400. }
  7401. inline bool
  7402. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  7403. auto ret = false;
  7404. auto type = GEN_DNS;
  7405. struct in6_addr addr6 {};
  7406. struct in_addr addr {};
  7407. size_t addr_len = 0;
  7408. #ifndef __MINGW32__
  7409. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  7410. type = GEN_IPADD;
  7411. addr_len = sizeof(struct in6_addr);
  7412. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  7413. type = GEN_IPADD;
  7414. addr_len = sizeof(struct in_addr);
  7415. }
  7416. #endif
  7417. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  7418. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  7419. if (alt_names) {
  7420. auto dsn_matched = false;
  7421. auto ip_matched = false;
  7422. auto count = sk_GENERAL_NAME_num(alt_names);
  7423. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  7424. auto val = sk_GENERAL_NAME_value(alt_names, i);
  7425. if (val->type == type) {
  7426. auto name =
  7427. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  7428. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  7429. switch (type) {
  7430. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  7431. case GEN_IPADD:
  7432. if (!memcmp(&addr6, name, addr_len) ||
  7433. !memcmp(&addr, name, addr_len)) {
  7434. ip_matched = true;
  7435. }
  7436. break;
  7437. }
  7438. }
  7439. }
  7440. if (dsn_matched || ip_matched) { ret = true; }
  7441. }
  7442. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  7443. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  7444. return ret;
  7445. }
  7446. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  7447. const auto subject_name = X509_get_subject_name(server_cert);
  7448. if (subject_name != nullptr) {
  7449. char name[BUFSIZ];
  7450. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7451. name, sizeof(name));
  7452. if (name_len != -1) {
  7453. return check_host_name(name, static_cast<size_t>(name_len));
  7454. }
  7455. }
  7456. return false;
  7457. }
  7458. inline bool SSLClient::check_host_name(const char *pattern,
  7459. size_t pattern_len) const {
  7460. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  7461. // Wildcard match
  7462. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7463. std::vector<std::string> pattern_components;
  7464. detail::split(&pattern[0], &pattern[pattern_len], '.',
  7465. [&](const char *b, const char *e) {
  7466. pattern_components.emplace_back(b, e);
  7467. });
  7468. if (host_components_.size() != pattern_components.size()) { return false; }
  7469. auto itr = pattern_components.begin();
  7470. for (const auto &h : host_components_) {
  7471. auto &p = *itr;
  7472. if (p != h && p != "*") {
  7473. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  7474. !p.compare(0, p.size() - 1, h));
  7475. if (!partial_match) { return false; }
  7476. }
  7477. ++itr;
  7478. }
  7479. return true;
  7480. }
  7481. #endif
  7482. // Universal client implementation
  7483. inline Client::Client(const std::string &scheme_host_port)
  7484. : Client(scheme_host_port, std::string(), std::string()) {}
  7485. inline Client::Client(const std::string &scheme_host_port,
  7486. const std::string &client_cert_path,
  7487. const std::string &client_key_path) {
  7488. const static std::regex re(
  7489. R"((?:([a-z]+):\/\/)?(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  7490. std::smatch m;
  7491. if (std::regex_match(scheme_host_port, m, re)) {
  7492. auto scheme = m[1].str();
  7493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7494. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  7495. #else
  7496. if (!scheme.empty() && scheme != "http") {
  7497. #endif
  7498. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7499. std::string msg = "'" + scheme + "' scheme is not supported.";
  7500. throw std::invalid_argument(msg);
  7501. #endif
  7502. return;
  7503. }
  7504. auto is_ssl = scheme == "https";
  7505. auto host = m[2].str();
  7506. if (host.empty()) { host = m[3].str(); }
  7507. auto port_str = m[4].str();
  7508. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  7509. if (is_ssl) {
  7510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7511. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  7512. client_key_path);
  7513. is_ssl_ = is_ssl;
  7514. #endif
  7515. } else {
  7516. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  7517. client_key_path);
  7518. }
  7519. } else {
  7520. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  7521. client_cert_path, client_key_path);
  7522. }
  7523. }
  7524. inline Client::Client(const std::string &host, int port)
  7525. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  7526. inline Client::Client(const std::string &host, int port,
  7527. const std::string &client_cert_path,
  7528. const std::string &client_key_path)
  7529. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  7530. client_key_path)) {}
  7531. inline Client::~Client() = default;
  7532. inline bool Client::is_valid() const {
  7533. return cli_ != nullptr && cli_->is_valid();
  7534. }
  7535. inline Result Client::Get(const std::string &path) { return cli_->Get(path); }
  7536. inline Result Client::Get(const std::string &path, const Headers &headers) {
  7537. return cli_->Get(path, headers);
  7538. }
  7539. inline Result Client::Get(const std::string &path, Progress progress) {
  7540. return cli_->Get(path, std::move(progress));
  7541. }
  7542. inline Result Client::Get(const std::string &path, const Headers &headers,
  7543. Progress progress) {
  7544. return cli_->Get(path, headers, std::move(progress));
  7545. }
  7546. inline Result Client::Get(const std::string &path,
  7547. ContentReceiver content_receiver) {
  7548. return cli_->Get(path, std::move(content_receiver));
  7549. }
  7550. inline Result Client::Get(const std::string &path, const Headers &headers,
  7551. ContentReceiver content_receiver) {
  7552. return cli_->Get(path, headers, std::move(content_receiver));
  7553. }
  7554. inline Result Client::Get(const std::string &path,
  7555. ContentReceiver content_receiver, Progress progress) {
  7556. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  7557. }
  7558. inline Result Client::Get(const std::string &path, const Headers &headers,
  7559. ContentReceiver content_receiver, Progress progress) {
  7560. return cli_->Get(path, headers, std::move(content_receiver),
  7561. std::move(progress));
  7562. }
  7563. inline Result Client::Get(const std::string &path,
  7564. ResponseHandler response_handler,
  7565. ContentReceiver content_receiver) {
  7566. return cli_->Get(path, std::move(response_handler),
  7567. std::move(content_receiver));
  7568. }
  7569. inline Result Client::Get(const std::string &path, const Headers &headers,
  7570. ResponseHandler response_handler,
  7571. ContentReceiver content_receiver) {
  7572. return cli_->Get(path, headers, std::move(response_handler),
  7573. std::move(content_receiver));
  7574. }
  7575. inline Result Client::Get(const std::string &path,
  7576. ResponseHandler response_handler,
  7577. ContentReceiver content_receiver, Progress progress) {
  7578. return cli_->Get(path, std::move(response_handler),
  7579. std::move(content_receiver), std::move(progress));
  7580. }
  7581. inline Result Client::Get(const std::string &path, const Headers &headers,
  7582. ResponseHandler response_handler,
  7583. ContentReceiver content_receiver, Progress progress) {
  7584. return cli_->Get(path, headers, std::move(response_handler),
  7585. std::move(content_receiver), std::move(progress));
  7586. }
  7587. inline Result Client::Get(const std::string &path, const Params &params,
  7588. const Headers &headers, Progress progress) {
  7589. return cli_->Get(path, params, headers, std::move(progress));
  7590. }
  7591. inline Result Client::Get(const std::string &path, const Params &params,
  7592. const Headers &headers,
  7593. ContentReceiver content_receiver, Progress progress) {
  7594. return cli_->Get(path, params, headers, std::move(content_receiver),
  7595. std::move(progress));
  7596. }
  7597. inline Result Client::Get(const std::string &path, const Params &params,
  7598. const Headers &headers,
  7599. ResponseHandler response_handler,
  7600. ContentReceiver content_receiver, Progress progress) {
  7601. return cli_->Get(path, params, headers, std::move(response_handler),
  7602. std::move(content_receiver), std::move(progress));
  7603. }
  7604. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  7605. inline Result Client::Head(const std::string &path, const Headers &headers) {
  7606. return cli_->Head(path, headers);
  7607. }
  7608. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  7609. inline Result Client::Post(const std::string &path, const Headers &headers) {
  7610. return cli_->Post(path, headers);
  7611. }
  7612. inline Result Client::Post(const std::string &path, const char *body,
  7613. size_t content_length,
  7614. const std::string &content_type) {
  7615. return cli_->Post(path, body, content_length, content_type);
  7616. }
  7617. inline Result Client::Post(const std::string &path, const Headers &headers,
  7618. const char *body, size_t content_length,
  7619. const std::string &content_type) {
  7620. return cli_->Post(path, headers, body, content_length, content_type);
  7621. }
  7622. inline Result Client::Post(const std::string &path, const std::string &body,
  7623. const std::string &content_type) {
  7624. return cli_->Post(path, body, content_type);
  7625. }
  7626. inline Result Client::Post(const std::string &path, const Headers &headers,
  7627. const std::string &body,
  7628. const std::string &content_type) {
  7629. return cli_->Post(path, headers, body, content_type);
  7630. }
  7631. inline Result Client::Post(const std::string &path, size_t content_length,
  7632. ContentProvider content_provider,
  7633. const std::string &content_type) {
  7634. return cli_->Post(path, content_length, std::move(content_provider),
  7635. content_type);
  7636. }
  7637. inline Result Client::Post(const std::string &path,
  7638. ContentProviderWithoutLength content_provider,
  7639. const std::string &content_type) {
  7640. return cli_->Post(path, std::move(content_provider), content_type);
  7641. }
  7642. inline Result Client::Post(const std::string &path, const Headers &headers,
  7643. size_t content_length,
  7644. ContentProvider content_provider,
  7645. const std::string &content_type) {
  7646. return cli_->Post(path, headers, content_length, std::move(content_provider),
  7647. content_type);
  7648. }
  7649. inline Result Client::Post(const std::string &path, const Headers &headers,
  7650. ContentProviderWithoutLength content_provider,
  7651. const std::string &content_type) {
  7652. return cli_->Post(path, headers, std::move(content_provider), content_type);
  7653. }
  7654. inline Result Client::Post(const std::string &path, const Params &params) {
  7655. return cli_->Post(path, params);
  7656. }
  7657. inline Result Client::Post(const std::string &path, const Headers &headers,
  7658. const Params &params) {
  7659. return cli_->Post(path, headers, params);
  7660. }
  7661. inline Result Client::Post(const std::string &path,
  7662. const MultipartFormDataItems &items) {
  7663. return cli_->Post(path, items);
  7664. }
  7665. inline Result Client::Post(const std::string &path, const Headers &headers,
  7666. const MultipartFormDataItems &items) {
  7667. return cli_->Post(path, headers, items);
  7668. }
  7669. inline Result Client::Post(const std::string &path, const Headers &headers,
  7670. const MultipartFormDataItems &items,
  7671. const std::string &boundary) {
  7672. return cli_->Post(path, headers, items, boundary);
  7673. }
  7674. inline Result
  7675. Client::Post(const std::string &path, const Headers &headers,
  7676. const MultipartFormDataItems &items,
  7677. const MultipartFormDataProviderItems &provider_items) {
  7678. return cli_->Post(path, headers, items, provider_items);
  7679. }
  7680. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  7681. inline Result Client::Put(const std::string &path, const char *body,
  7682. size_t content_length,
  7683. const std::string &content_type) {
  7684. return cli_->Put(path, body, content_length, content_type);
  7685. }
  7686. inline Result Client::Put(const std::string &path, const Headers &headers,
  7687. const char *body, size_t content_length,
  7688. const std::string &content_type) {
  7689. return cli_->Put(path, headers, body, content_length, content_type);
  7690. }
  7691. inline Result Client::Put(const std::string &path, const std::string &body,
  7692. const std::string &content_type) {
  7693. return cli_->Put(path, body, content_type);
  7694. }
  7695. inline Result Client::Put(const std::string &path, const Headers &headers,
  7696. const std::string &body,
  7697. const std::string &content_type) {
  7698. return cli_->Put(path, headers, body, content_type);
  7699. }
  7700. inline Result Client::Put(const std::string &path, size_t content_length,
  7701. ContentProvider content_provider,
  7702. const std::string &content_type) {
  7703. return cli_->Put(path, content_length, std::move(content_provider),
  7704. content_type);
  7705. }
  7706. inline Result Client::Put(const std::string &path,
  7707. ContentProviderWithoutLength content_provider,
  7708. const std::string &content_type) {
  7709. return cli_->Put(path, std::move(content_provider), content_type);
  7710. }
  7711. inline Result Client::Put(const std::string &path, const Headers &headers,
  7712. size_t content_length,
  7713. ContentProvider content_provider,
  7714. const std::string &content_type) {
  7715. return cli_->Put(path, headers, content_length, std::move(content_provider),
  7716. content_type);
  7717. }
  7718. inline Result Client::Put(const std::string &path, const Headers &headers,
  7719. ContentProviderWithoutLength content_provider,
  7720. const std::string &content_type) {
  7721. return cli_->Put(path, headers, std::move(content_provider), content_type);
  7722. }
  7723. inline Result Client::Put(const std::string &path, const Params &params) {
  7724. return cli_->Put(path, params);
  7725. }
  7726. inline Result Client::Put(const std::string &path, const Headers &headers,
  7727. const Params &params) {
  7728. return cli_->Put(path, headers, params);
  7729. }
  7730. inline Result Client::Put(const std::string &path,
  7731. const MultipartFormDataItems &items) {
  7732. return cli_->Put(path, items);
  7733. }
  7734. inline Result Client::Put(const std::string &path, const Headers &headers,
  7735. const MultipartFormDataItems &items) {
  7736. return cli_->Put(path, headers, items);
  7737. }
  7738. inline Result Client::Put(const std::string &path, const Headers &headers,
  7739. const MultipartFormDataItems &items,
  7740. const std::string &boundary) {
  7741. return cli_->Put(path, headers, items, boundary);
  7742. }
  7743. inline Result
  7744. Client::Put(const std::string &path, const Headers &headers,
  7745. const MultipartFormDataItems &items,
  7746. const MultipartFormDataProviderItems &provider_items) {
  7747. return cli_->Put(path, headers, items, provider_items);
  7748. }
  7749. inline Result Client::Patch(const std::string &path) {
  7750. return cli_->Patch(path);
  7751. }
  7752. inline Result Client::Patch(const std::string &path, const char *body,
  7753. size_t content_length,
  7754. const std::string &content_type) {
  7755. return cli_->Patch(path, body, content_length, content_type);
  7756. }
  7757. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7758. const char *body, size_t content_length,
  7759. const std::string &content_type) {
  7760. return cli_->Patch(path, headers, body, content_length, content_type);
  7761. }
  7762. inline Result Client::Patch(const std::string &path, const std::string &body,
  7763. const std::string &content_type) {
  7764. return cli_->Patch(path, body, content_type);
  7765. }
  7766. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7767. const std::string &body,
  7768. const std::string &content_type) {
  7769. return cli_->Patch(path, headers, body, content_type);
  7770. }
  7771. inline Result Client::Patch(const std::string &path, size_t content_length,
  7772. ContentProvider content_provider,
  7773. const std::string &content_type) {
  7774. return cli_->Patch(path, content_length, std::move(content_provider),
  7775. content_type);
  7776. }
  7777. inline Result Client::Patch(const std::string &path,
  7778. ContentProviderWithoutLength content_provider,
  7779. const std::string &content_type) {
  7780. return cli_->Patch(path, std::move(content_provider), content_type);
  7781. }
  7782. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7783. size_t content_length,
  7784. ContentProvider content_provider,
  7785. const std::string &content_type) {
  7786. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  7787. content_type);
  7788. }
  7789. inline Result Client::Patch(const std::string &path, const Headers &headers,
  7790. ContentProviderWithoutLength content_provider,
  7791. const std::string &content_type) {
  7792. return cli_->Patch(path, headers, std::move(content_provider), content_type);
  7793. }
  7794. inline Result Client::Delete(const std::string &path) {
  7795. return cli_->Delete(path);
  7796. }
  7797. inline Result Client::Delete(const std::string &path, const Headers &headers) {
  7798. return cli_->Delete(path, headers);
  7799. }
  7800. inline Result Client::Delete(const std::string &path, const char *body,
  7801. size_t content_length,
  7802. const std::string &content_type) {
  7803. return cli_->Delete(path, body, content_length, content_type);
  7804. }
  7805. inline Result Client::Delete(const std::string &path, const Headers &headers,
  7806. const char *body, size_t content_length,
  7807. const std::string &content_type) {
  7808. return cli_->Delete(path, headers, body, content_length, content_type);
  7809. }
  7810. inline Result Client::Delete(const std::string &path, const std::string &body,
  7811. const std::string &content_type) {
  7812. return cli_->Delete(path, body, content_type);
  7813. }
  7814. inline Result Client::Delete(const std::string &path, const Headers &headers,
  7815. const std::string &body,
  7816. const std::string &content_type) {
  7817. return cli_->Delete(path, headers, body, content_type);
  7818. }
  7819. inline Result Client::Options(const std::string &path) {
  7820. return cli_->Options(path);
  7821. }
  7822. inline Result Client::Options(const std::string &path, const Headers &headers) {
  7823. return cli_->Options(path, headers);
  7824. }
  7825. inline bool Client::send(Request &req, Response &res, Error &error) {
  7826. return cli_->send(req, res, error);
  7827. }
  7828. inline Result Client::send(const Request &req) { return cli_->send(req); }
  7829. inline void Client::stop() { cli_->stop(); }
  7830. inline std::string Client::host() const { return cli_->host(); }
  7831. inline int Client::port() const { return cli_->port(); }
  7832. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  7833. inline socket_t Client::socket() const { return cli_->socket(); }
  7834. inline void
  7835. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  7836. cli_->set_hostname_addr_map(std::move(addr_map));
  7837. }
  7838. inline void Client::set_default_headers(Headers headers) {
  7839. cli_->set_default_headers(std::move(headers));
  7840. }
  7841. inline void Client::set_header_writer(
  7842. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  7843. cli_->set_header_writer(writer);
  7844. }
  7845. inline void Client::set_address_family(int family) {
  7846. cli_->set_address_family(family);
  7847. }
  7848. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  7849. inline void Client::set_socket_options(SocketOptions socket_options) {
  7850. cli_->set_socket_options(std::move(socket_options));
  7851. }
  7852. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  7853. cli_->set_connection_timeout(sec, usec);
  7854. }
  7855. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  7856. cli_->set_read_timeout(sec, usec);
  7857. }
  7858. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  7859. cli_->set_write_timeout(sec, usec);
  7860. }
  7861. inline void Client::set_basic_auth(const std::string &username,
  7862. const std::string &password) {
  7863. cli_->set_basic_auth(username, password);
  7864. }
  7865. inline void Client::set_bearer_token_auth(const std::string &token) {
  7866. cli_->set_bearer_token_auth(token);
  7867. }
  7868. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7869. inline void Client::set_digest_auth(const std::string &username,
  7870. const std::string &password) {
  7871. cli_->set_digest_auth(username, password);
  7872. }
  7873. #endif
  7874. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  7875. inline void Client::set_follow_location(bool on) {
  7876. cli_->set_follow_location(on);
  7877. }
  7878. inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); }
  7879. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  7880. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  7881. inline void Client::set_interface(const std::string &intf) {
  7882. cli_->set_interface(intf);
  7883. }
  7884. inline void Client::set_proxy(const std::string &host, int port) {
  7885. cli_->set_proxy(host, port);
  7886. }
  7887. inline void Client::set_proxy_basic_auth(const std::string &username,
  7888. const std::string &password) {
  7889. cli_->set_proxy_basic_auth(username, password);
  7890. }
  7891. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  7892. cli_->set_proxy_bearer_token_auth(token);
  7893. }
  7894. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7895. inline void Client::set_proxy_digest_auth(const std::string &username,
  7896. const std::string &password) {
  7897. cli_->set_proxy_digest_auth(username, password);
  7898. }
  7899. #endif
  7900. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7901. inline void Client::enable_server_certificate_verification(bool enabled) {
  7902. cli_->enable_server_certificate_verification(enabled);
  7903. }
  7904. #endif
  7905. inline void Client::set_logger(Logger logger) {
  7906. cli_->set_logger(std::move(logger));
  7907. }
  7908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7909. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  7910. const std::string &ca_cert_dir_path) {
  7911. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  7912. }
  7913. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  7914. if (is_ssl_) {
  7915. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  7916. } else {
  7917. cli_->set_ca_cert_store(ca_cert_store);
  7918. }
  7919. }
  7920. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  7921. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  7922. }
  7923. inline long Client::get_openssl_verify_result() const {
  7924. if (is_ssl_) {
  7925. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  7926. }
  7927. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  7928. }
  7929. inline SSL_CTX *Client::ssl_context() const {
  7930. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  7931. return nullptr;
  7932. }
  7933. #endif
  7934. // ----------------------------------------------------------------------------
  7935. } // namespace httplib
  7936. #if defined(_WIN32) && defined(CPPHTTPLIB_USE_POLL)
  7937. #undef poll
  7938. #endif
  7939. #endif // CPPHTTPLIB_HTTPLIB_H