httplib.h 279 KB

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