httplib.h 290 KB

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