httplib.h 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2020 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. /*
  10. * Configuration
  11. */
  12. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  13. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  14. #endif
  15. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND
  16. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  17. #endif
  18. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  19. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  20. #endif
  21. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  22. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  23. #endif
  24. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  25. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  26. #endif
  27. #ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
  28. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
  29. #endif
  30. #ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
  31. #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
  32. #endif
  33. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_SECOND
  34. #define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 5
  35. #endif
  36. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_USECOND
  37. #define CPPHTTPLIB_WRITE_TIMEOUT_USECOND 0
  38. #endif
  39. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  40. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  41. #endif
  42. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  43. #ifdef _WIN32
  44. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
  45. #else
  46. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  47. #endif
  48. #endif
  49. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  50. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  51. #endif
  52. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  53. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  54. #endif
  55. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  56. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  57. #endif
  58. #ifndef CPPHTTPLIB_TCP_NODELAY
  59. #define CPPHTTPLIB_TCP_NODELAY false
  60. #endif
  61. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  62. #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
  63. #endif
  64. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  65. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  66. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  67. ? std::thread::hardware_concurrency() - 1 \
  68. : 0))
  69. #endif
  70. /*
  71. * Headers
  72. */
  73. #ifdef _WIN32
  74. #ifndef _CRT_SECURE_NO_WARNINGS
  75. #define _CRT_SECURE_NO_WARNINGS
  76. #endif //_CRT_SECURE_NO_WARNINGS
  77. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  78. #define _CRT_NONSTDC_NO_DEPRECATE
  79. #endif //_CRT_NONSTDC_NO_DEPRECATE
  80. #if defined(_MSC_VER)
  81. #ifdef _WIN64
  82. using ssize_t = __int64;
  83. #else
  84. using ssize_t = int;
  85. #endif
  86. #if _MSC_VER < 1900
  87. #define snprintf _snprintf_s
  88. #endif
  89. #endif // _MSC_VER
  90. #ifndef S_ISREG
  91. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  92. #endif // S_ISREG
  93. #ifndef S_ISDIR
  94. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  95. #endif // S_ISDIR
  96. #ifndef NOMINMAX
  97. #define NOMINMAX
  98. #endif // NOMINMAX
  99. #include <io.h>
  100. #include <winsock2.h>
  101. #include <wincrypt.h>
  102. #include <ws2tcpip.h>
  103. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  104. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  105. #endif
  106. #ifdef _MSC_VER
  107. #pragma comment(lib, "ws2_32.lib")
  108. #pragma comment(lib, "crypt32.lib")
  109. #pragma comment(lib, "cryptui.lib")
  110. #endif
  111. #ifndef strcasecmp
  112. #define strcasecmp _stricmp
  113. #endif // strcasecmp
  114. using socket_t = SOCKET;
  115. #ifdef CPPHTTPLIB_USE_POLL
  116. #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
  117. #endif
  118. #else // not _WIN32
  119. #include <arpa/inet.h>
  120. #include <cstring>
  121. #include <ifaddrs.h>
  122. #include <netdb.h>
  123. #include <netinet/in.h>
  124. #ifdef __linux__
  125. #include <resolv.h>
  126. #endif
  127. #include <netinet/tcp.h>
  128. #ifdef CPPHTTPLIB_USE_POLL
  129. #include <poll.h>
  130. #endif
  131. #include <csignal>
  132. #include <pthread.h>
  133. #include <sys/select.h>
  134. #include <sys/socket.h>
  135. #include <unistd.h>
  136. using socket_t = int;
  137. #define INVALID_SOCKET (-1)
  138. #endif //_WIN32
  139. #include <array>
  140. #include <atomic>
  141. #include <cassert>
  142. #include <climits>
  143. #include <condition_variable>
  144. #include <errno.h>
  145. #include <fcntl.h>
  146. #include <fstream>
  147. #include <functional>
  148. #include <iostream>
  149. #include <list>
  150. #include <map>
  151. #include <memory>
  152. #include <mutex>
  153. #include <random>
  154. #include <regex>
  155. #include <string>
  156. #include <sys/stat.h>
  157. #include <thread>
  158. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  159. #include <openssl/err.h>
  160. #include <openssl/md5.h>
  161. #include <openssl/ssl.h>
  162. #include <openssl/x509v3.h>
  163. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  164. #include <openssl/applink.c>
  165. #endif
  166. #include <iomanip>
  167. #include <iostream>
  168. #include <sstream>
  169. // It seems this was added to deprecate support of versions of OPENSSL that are no longer supported by the OPENSSL team
  170. // But the code to support older versions was not removed, so disabling this here for now
  171. // If we have issues with old versions of OPENSSL we can fix ourselves
  172. //
  173. //#if OPENSSL_VERSION_NUMBER < 0x1010100fL
  174. //#error Sorry, OpenSSL versions prior to 1.1.1 are not supported
  175. //#endif
  176. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  177. #include <openssl/crypto.h>
  178. inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
  179. return M_ASN1_STRING_data(asn1);
  180. }
  181. #endif
  182. #endif
  183. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  184. #include <zlib.h>
  185. #endif
  186. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  187. #include <brotli/decode.h>
  188. #include <brotli/encode.h>
  189. #endif
  190. /*
  191. * Declaration
  192. */
  193. namespace httplib {
  194. namespace detail {
  195. struct ci {
  196. bool operator()(const std::string &s1, const std::string &s2) const {
  197. return std::lexicographical_compare(
  198. s1.begin(), s1.end(), s2.begin(), s2.end(),
  199. [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
  200. }
  201. };
  202. } // namespace detail
  203. using Headers = std::multimap<std::string, std::string, detail::ci>;
  204. using Params = std::multimap<std::string, std::string>;
  205. using Match = std::smatch;
  206. using Progress = std::function<bool(uint64_t current, uint64_t total)>;
  207. struct Response;
  208. using ResponseHandler = std::function<bool(const Response &response)>;
  209. struct MultipartFormData {
  210. std::string name;
  211. std::string content;
  212. std::string filename;
  213. std::string content_type;
  214. };
  215. using MultipartFormDataItems = std::vector<MultipartFormData>;
  216. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  217. class DataSink {
  218. public:
  219. DataSink() : os(&sb_), sb_(*this) {}
  220. DataSink(const DataSink &) = delete;
  221. DataSink &operator=(const DataSink &) = delete;
  222. DataSink(DataSink &&) = delete;
  223. DataSink &operator=(DataSink &&) = delete;
  224. std::function<void(const char *data, size_t data_len)> write;
  225. std::function<void()> done;
  226. std::function<bool()> is_writable;
  227. std::ostream os;
  228. private:
  229. class data_sink_streambuf : public std::streambuf {
  230. public:
  231. data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  232. protected:
  233. std::streamsize xsputn(const char *s, std::streamsize n) {
  234. sink_.write(s, static_cast<size_t>(n));
  235. return n;
  236. }
  237. private:
  238. DataSink &sink_;
  239. };
  240. data_sink_streambuf sb_;
  241. };
  242. using ContentProvider =
  243. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  244. using ContentProviderWithoutLength =
  245. std::function<bool(size_t offset, DataSink &sink)>;
  246. using ContentReceiver =
  247. std::function<bool(const char *data, size_t data_length)>;
  248. using MultipartContentHeader =
  249. std::function<bool(const MultipartFormData &file)>;
  250. class ContentReader {
  251. public:
  252. using Reader = std::function<bool(ContentReceiver receiver)>;
  253. using MultipartReader = std::function<bool(MultipartContentHeader header,
  254. ContentReceiver receiver)>;
  255. ContentReader(Reader reader, MultipartReader multipart_reader)
  256. : reader_(reader), multipart_reader_(multipart_reader) {}
  257. bool operator()(MultipartContentHeader header,
  258. ContentReceiver receiver) const {
  259. return multipart_reader_(header, receiver);
  260. }
  261. bool operator()(ContentReceiver receiver) const { return reader_(receiver); }
  262. Reader reader_;
  263. MultipartReader multipart_reader_;
  264. };
  265. using Range = std::pair<ssize_t, ssize_t>;
  266. using Ranges = std::vector<Range>;
  267. struct Request {
  268. std::string method;
  269. std::string path;
  270. Headers headers;
  271. std::string body;
  272. std::string remote_addr;
  273. int remote_port = -1;
  274. // for server
  275. std::string version;
  276. std::string target;
  277. Params params;
  278. MultipartFormDataMap files;
  279. Ranges ranges;
  280. Match matches;
  281. // for client
  282. size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  283. ResponseHandler response_handler;
  284. ContentReceiver content_receiver;
  285. size_t content_length = 0;
  286. ContentProvider content_provider;
  287. Progress progress;
  288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  289. const SSL *ssl;
  290. #endif
  291. bool has_header(const char *key) const;
  292. std::string get_header_value(const char *key, size_t id = 0) const;
  293. template <typename T>
  294. T get_header_value(const char *key, size_t id = 0) const;
  295. size_t get_header_value_count(const char *key) const;
  296. void set_header(const char *key, const char *val);
  297. void set_header(const char *key, const std::string &val);
  298. bool has_param(const char *key) const;
  299. std::string get_param_value(const char *key, size_t id = 0) const;
  300. size_t get_param_value_count(const char *key) const;
  301. bool is_multipart_form_data() const;
  302. bool has_file(const char *key) const;
  303. MultipartFormData get_file_value(const char *key) const;
  304. // private members...
  305. size_t authorization_count_ = 0;
  306. };
  307. struct Response {
  308. std::string version;
  309. int status = -1;
  310. Headers headers;
  311. std::string body;
  312. bool has_header(const char *key) const;
  313. std::string get_header_value(const char *key, size_t id = 0) const;
  314. template <typename T>
  315. T get_header_value(const char *key, size_t id = 0) const;
  316. size_t get_header_value_count(const char *key) const;
  317. void set_header(const char *key, const char *val);
  318. void set_header(const char *key, const std::string &val);
  319. void set_redirect(const char *url, int status = 302);
  320. void set_redirect(const std::string &url, int status = 302);
  321. void set_content(const char *s, size_t n, const char *content_type);
  322. void set_content(std::string s, const char *content_type);
  323. void set_content_provider(
  324. size_t length, const char *content_type, ContentProvider provider,
  325. std::function<void()> resource_releaser = [] {});
  326. void set_content_provider(
  327. const char *content_type, ContentProviderWithoutLength provider,
  328. std::function<void()> resource_releaser = [] {});
  329. void set_chunked_content_provider(
  330. const char *content_type, ContentProviderWithoutLength provider,
  331. std::function<void()> resource_releaser = [] {});
  332. Response() = default;
  333. Response(const Response &) = default;
  334. Response &operator=(const Response &) = default;
  335. Response(Response &&) = default;
  336. Response &operator=(Response &&) = default;
  337. ~Response() {
  338. if (content_provider_resource_releaser_) {
  339. content_provider_resource_releaser_();
  340. }
  341. }
  342. // private members...
  343. size_t content_length_ = 0;
  344. ContentProvider content_provider_;
  345. std::function<void()> content_provider_resource_releaser_;
  346. bool is_chunked_content_provider = false;
  347. };
  348. class Stream {
  349. public:
  350. virtual ~Stream() = default;
  351. virtual bool is_readable() const = 0;
  352. virtual bool is_writable() const = 0;
  353. virtual ssize_t read(char *ptr, size_t size) = 0;
  354. virtual ssize_t write(const char *ptr, size_t size) = 0;
  355. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  356. template <typename... Args>
  357. ssize_t write_format(const char *fmt, const Args &... args);
  358. ssize_t write(const char *ptr);
  359. ssize_t write(const std::string &s);
  360. };
  361. class TaskQueue {
  362. public:
  363. TaskQueue() = default;
  364. virtual ~TaskQueue() = default;
  365. virtual void enqueue(std::function<void()> fn) = 0;
  366. virtual void shutdown() = 0;
  367. virtual void on_idle(){};
  368. };
  369. class ThreadPool : public TaskQueue {
  370. public:
  371. explicit ThreadPool(size_t n) : shutdown_(false) {
  372. while (n) {
  373. threads_.emplace_back(worker(*this));
  374. n--;
  375. }
  376. }
  377. ThreadPool(const ThreadPool &) = delete;
  378. ~ThreadPool() override = default;
  379. void enqueue(std::function<void()> fn) override {
  380. std::unique_lock<std::mutex> lock(mutex_);
  381. jobs_.push_back(fn);
  382. cond_.notify_one();
  383. }
  384. void shutdown() override {
  385. // Stop all worker threads...
  386. {
  387. std::unique_lock<std::mutex> lock(mutex_);
  388. shutdown_ = true;
  389. }
  390. cond_.notify_all();
  391. // Join...
  392. for (auto &t : threads_) {
  393. t.join();
  394. }
  395. }
  396. private:
  397. struct worker {
  398. explicit worker(ThreadPool &pool) : pool_(pool) {}
  399. void operator()() {
  400. for (;;) {
  401. std::function<void()> fn;
  402. {
  403. std::unique_lock<std::mutex> lock(pool_.mutex_);
  404. pool_.cond_.wait(
  405. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  406. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  407. fn = pool_.jobs_.front();
  408. pool_.jobs_.pop_front();
  409. }
  410. assert(true == static_cast<bool>(fn));
  411. fn();
  412. }
  413. }
  414. ThreadPool &pool_;
  415. };
  416. friend struct worker;
  417. std::vector<std::thread> threads_;
  418. std::list<std::function<void()>> jobs_;
  419. bool shutdown_;
  420. std::condition_variable cond_;
  421. std::mutex mutex_;
  422. };
  423. using Logger = std::function<void(const Request &, const Response &)>;
  424. using SocketOptions = std::function<void(socket_t sock)>;
  425. inline void default_socket_options(socket_t sock) {
  426. int yes = 1;
  427. #ifdef _WIN32
  428. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
  429. sizeof(yes));
  430. setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  431. reinterpret_cast<char *>(&yes), sizeof(yes));
  432. #else
  433. #ifdef SO_REUSEPORT
  434. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<void *>(&yes),
  435. sizeof(yes));
  436. #else
  437. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void *>(&yes),
  438. sizeof(yes));
  439. #endif
  440. #endif
  441. }
  442. class Server {
  443. public:
  444. using Handler = std::function<void(const Request &, Response &)>;
  445. using HandlerWithContentReader = std::function<void(
  446. const Request &, Response &, const ContentReader &content_reader)>;
  447. using Expect100ContinueHandler =
  448. std::function<int(const Request &, Response &)>;
  449. Server();
  450. virtual ~Server();
  451. virtual bool is_valid() const;
  452. Server &Get(const char *pattern, Handler handler);
  453. Server &Post(const char *pattern, Handler handler);
  454. Server &Post(const char *pattern, HandlerWithContentReader handler);
  455. Server &Put(const char *pattern, Handler handler);
  456. Server &Put(const char *pattern, HandlerWithContentReader handler);
  457. Server &Patch(const char *pattern, Handler handler);
  458. Server &Patch(const char *pattern, HandlerWithContentReader handler);
  459. Server &Delete(const char *pattern, Handler handler);
  460. Server &Delete(const char *pattern, HandlerWithContentReader handler);
  461. Server &Options(const char *pattern, Handler handler);
  462. bool set_base_dir(const char *dir, const char *mount_point = nullptr);
  463. bool set_mount_point(const char *mount_point, const char *dir);
  464. bool remove_mount_point(const char *mount_point);
  465. void set_file_extension_and_mimetype_mapping(const char *ext,
  466. const char *mime);
  467. void set_file_request_handler(Handler handler);
  468. void set_error_handler(Handler handler);
  469. void set_expect_100_continue_handler(Expect100ContinueHandler handler);
  470. void set_logger(Logger logger);
  471. void set_tcp_nodelay(bool on);
  472. void set_socket_options(SocketOptions socket_options);
  473. void set_keep_alive_max_count(size_t count);
  474. void set_read_timeout(time_t sec, time_t usec = 0);
  475. void set_write_timeout(time_t sec, time_t usec = 0);
  476. void set_idle_interval(time_t sec, time_t usec = 0);
  477. void set_payload_max_length(size_t length);
  478. bool bind_to_port(const char *host, int port, int socket_flags = 0);
  479. int bind_to_any_port(const char *host, int socket_flags = 0);
  480. bool listen_after_bind();
  481. bool listen(const char *host, int port, int socket_flags = 0);
  482. bool is_running() const;
  483. void stop();
  484. std::function<TaskQueue *(void)> new_task_queue;
  485. protected:
  486. bool process_request(Stream &strm, bool close_connection,
  487. bool &connection_closed,
  488. const std::function<void(Request &)> &setup_request);
  489. std::atomic<socket_t> svr_sock_;
  490. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  491. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  492. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  493. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  494. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  495. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  496. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  497. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  498. private:
  499. using Handlers = std::vector<std::pair<std::regex, Handler>>;
  500. using HandlersForContentReader =
  501. std::vector<std::pair<std::regex, HandlerWithContentReader>>;
  502. socket_t create_server_socket(const char *host, int port, int socket_flags,
  503. SocketOptions socket_options) const;
  504. int bind_internal(const char *host, int port, int socket_flags);
  505. bool listen_internal();
  506. bool routing(Request &req, Response &res, Stream &strm);
  507. bool handle_file_request(Request &req, Response &res, bool head = false);
  508. bool dispatch_request(Request &req, Response &res, Handlers &handlers);
  509. bool dispatch_request_for_content_reader(Request &req, Response &res,
  510. ContentReader content_reader,
  511. HandlersForContentReader &handlers);
  512. bool parse_request_line(const char *s, Request &req);
  513. bool write_response(Stream &strm, bool close_connection, const Request &req,
  514. Response &res);
  515. bool write_content_with_provider(Stream &strm, const Request &req,
  516. Response &res, const std::string &boundary,
  517. const std::string &content_type);
  518. bool read_content(Stream &strm, Request &req, Response &res);
  519. bool
  520. read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
  521. ContentReceiver receiver,
  522. MultipartContentHeader multipart_header,
  523. ContentReceiver multipart_receiver);
  524. bool read_content_core(Stream &strm, Request &req, Response &res,
  525. ContentReceiver receiver,
  526. MultipartContentHeader mulitpart_header,
  527. ContentReceiver multipart_receiver);
  528. virtual bool process_and_close_socket(socket_t sock);
  529. std::atomic<bool> is_running_;
  530. std::vector<std::pair<std::string, std::string>> base_dirs_;
  531. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  532. Handler file_request_handler_;
  533. Handlers get_handlers_;
  534. Handlers post_handlers_;
  535. HandlersForContentReader post_handlers_for_content_reader_;
  536. Handlers put_handlers_;
  537. HandlersForContentReader put_handlers_for_content_reader_;
  538. Handlers patch_handlers_;
  539. HandlersForContentReader patch_handlers_for_content_reader_;
  540. Handlers delete_handlers_;
  541. HandlersForContentReader delete_handlers_for_content_reader_;
  542. Handlers options_handlers_;
  543. Handler error_handler_;
  544. Logger logger_;
  545. Expect100ContinueHandler expect_100_continue_handler_;
  546. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  547. SocketOptions socket_options_ = default_socket_options;
  548. };
  549. enum Error {
  550. Success = 0,
  551. Unknown,
  552. Connection,
  553. BindIPAddress,
  554. Read,
  555. Write,
  556. ExceedRedirectCount,
  557. Canceled,
  558. SSLConnection,
  559. SSLLoadingCerts,
  560. SSLServerVerification
  561. };
  562. class Result {
  563. public:
  564. Result(std::shared_ptr<Response> res, Error err) : res_(res), err_(err) {}
  565. operator bool() const { return res_ != nullptr; }
  566. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  567. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  568. const Response &value() const { return *res_; }
  569. const Response &operator*() const { return *res_; }
  570. const Response *operator->() const { return res_.get(); }
  571. Error error() const { return err_; }
  572. private:
  573. std::shared_ptr<Response> res_;
  574. Error err_;
  575. };
  576. class ClientImpl {
  577. public:
  578. explicit ClientImpl(const std::string &host);
  579. explicit ClientImpl(const std::string &host, int port);
  580. explicit ClientImpl(const std::string &host, int port,
  581. const std::string &client_cert_path,
  582. const std::string &client_key_path);
  583. virtual ~ClientImpl();
  584. virtual bool is_valid() const;
  585. Result Get(const char *path);
  586. Result Get(const char *path, const Headers &headers);
  587. Result Get(const char *path, Progress progress);
  588. Result Get(const char *path, const Headers &headers, Progress progress);
  589. Result Get(const char *path, ContentReceiver content_receiver);
  590. Result Get(const char *path, const Headers &headers,
  591. ContentReceiver content_receiver);
  592. Result Get(const char *path, ContentReceiver content_receiver,
  593. Progress progress);
  594. Result Get(const char *path, const Headers &headers,
  595. ContentReceiver content_receiver, Progress progress);
  596. Result Get(const char *path, ResponseHandler response_handler,
  597. ContentReceiver content_receiver);
  598. Result Get(const char *path, const Headers &headers,
  599. ResponseHandler response_handler,
  600. ContentReceiver content_receiver);
  601. Result Get(const char *path, ResponseHandler response_handler,
  602. ContentReceiver content_receiver, Progress progress);
  603. Result Get(const char *path, const Headers &headers,
  604. ResponseHandler response_handler, ContentReceiver content_receiver,
  605. Progress progress);
  606. Result Head(const char *path);
  607. Result Head(const char *path, const Headers &headers);
  608. Result Post(const char *path);
  609. Result Post(const char *path, const std::string &body,
  610. const char *content_type);
  611. Result Post(const char *path, const Headers &headers, const std::string &body,
  612. const char *content_type);
  613. Result Post(const char *path, size_t content_length,
  614. ContentProvider content_provider, const char *content_type);
  615. Result Post(const char *path, const Headers &headers, size_t content_length,
  616. ContentProvider content_provider, const char *content_type);
  617. Result Post(const char *path, const Params &params);
  618. Result Post(const char *path, const Headers &headers, const Params &params);
  619. Result Post(const char *path, const MultipartFormDataItems &items);
  620. Result Post(const char *path, const Headers &headers,
  621. const MultipartFormDataItems &items);
  622. Result Put(const char *path);
  623. Result Put(const char *path, const std::string &body,
  624. const char *content_type);
  625. Result Put(const char *path, const Headers &headers, const std::string &body,
  626. const char *content_type);
  627. Result Put(const char *path, size_t content_length,
  628. ContentProvider content_provider, const char *content_type);
  629. Result Put(const char *path, const Headers &headers, size_t content_length,
  630. ContentProvider content_provider, const char *content_type);
  631. Result Put(const char *path, const Params &params);
  632. Result Put(const char *path, const Headers &headers, const Params &params);
  633. Result Patch(const char *path, const std::string &body,
  634. const char *content_type);
  635. Result Patch(const char *path, const Headers &headers,
  636. const std::string &body, const char *content_type);
  637. Result Patch(const char *path, size_t content_length,
  638. ContentProvider content_provider, const char *content_type);
  639. Result Patch(const char *path, const Headers &headers, size_t content_length,
  640. ContentProvider content_provider, const char *content_type);
  641. Result Delete(const char *path);
  642. Result Delete(const char *path, const std::string &body,
  643. const char *content_type);
  644. Result Delete(const char *path, const Headers &headers);
  645. Result Delete(const char *path, const Headers &headers,
  646. const std::string &body, const char *content_type);
  647. Result Options(const char *path);
  648. Result Options(const char *path, const Headers &headers);
  649. bool send(const Request &req, Response &res);
  650. size_t is_socket_open() const;
  651. void stop();
  652. void set_default_headers(Headers headers);
  653. void set_tcp_nodelay(bool on);
  654. void set_socket_options(SocketOptions socket_options);
  655. void set_connection_timeout(time_t sec, time_t usec = 0);
  656. void set_read_timeout(time_t sec, time_t usec = 0);
  657. void set_write_timeout(time_t sec, time_t usec = 0);
  658. void set_basic_auth(const char *username, const char *password);
  659. void set_bearer_token_auth(const char *token);
  660. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  661. void set_digest_auth(const char *username, const char *password);
  662. #endif
  663. void set_keep_alive(bool on);
  664. void set_follow_location(bool on);
  665. void set_compress(bool on);
  666. void set_decompress(bool on);
  667. void set_interface(const char *intf);
  668. void set_proxy(const char *host, int port);
  669. void set_proxy_basic_auth(const char *username, const char *password);
  670. void set_proxy_bearer_token_auth(const char *token);
  671. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  672. void set_proxy_digest_auth(const char *username, const char *password);
  673. #endif
  674. void set_logger(Logger logger);
  675. protected:
  676. struct Socket {
  677. socket_t sock = INVALID_SOCKET;
  678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  679. SSL *ssl = nullptr;
  680. #endif
  681. bool is_open() const { return sock != INVALID_SOCKET; }
  682. };
  683. virtual bool create_and_connect_socket(Socket &socket);
  684. virtual void close_socket(Socket &socket, bool process_socket_ret);
  685. bool process_request(Stream &strm, const Request &req, Response &res,
  686. bool close_connection);
  687. Error get_last_error() const;
  688. // Error state
  689. mutable Error error_ = Error::Success;
  690. // Socket endoint information
  691. const std::string host_;
  692. const int port_;
  693. const std::string host_and_port_;
  694. // Current open socket
  695. Socket socket_;
  696. mutable std::mutex socket_mutex_;
  697. std::recursive_mutex request_mutex_;
  698. // Default headers
  699. Headers default_headers_;
  700. // Settings
  701. std::string client_cert_path_;
  702. std::string client_key_path_;
  703. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  704. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  705. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  706. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  707. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  708. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  709. std::string basic_auth_username_;
  710. std::string basic_auth_password_;
  711. std::string bearer_token_auth_token_;
  712. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  713. std::string digest_auth_username_;
  714. std::string digest_auth_password_;
  715. #endif
  716. bool keep_alive_ = false;
  717. bool follow_location_ = false;
  718. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  719. SocketOptions socket_options_ = nullptr;
  720. bool compress_ = false;
  721. bool decompress_ = true;
  722. std::string interface_;
  723. std::string proxy_host_;
  724. int proxy_port_;
  725. std::string proxy_basic_auth_username_;
  726. std::string proxy_basic_auth_password_;
  727. std::string proxy_bearer_token_auth_token_;
  728. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  729. std::string proxy_digest_auth_username_;
  730. std::string proxy_digest_auth_password_;
  731. #endif
  732. Logger logger_;
  733. void copy_settings(const ClientImpl &rhs) {
  734. client_cert_path_ = rhs.client_cert_path_;
  735. client_key_path_ = rhs.client_key_path_;
  736. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  737. read_timeout_sec_ = rhs.read_timeout_sec_;
  738. read_timeout_usec_ = rhs.read_timeout_usec_;
  739. write_timeout_sec_ = rhs.write_timeout_sec_;
  740. write_timeout_usec_ = rhs.write_timeout_usec_;
  741. basic_auth_username_ = rhs.basic_auth_username_;
  742. basic_auth_password_ = rhs.basic_auth_password_;
  743. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  744. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  745. digest_auth_username_ = rhs.digest_auth_username_;
  746. digest_auth_password_ = rhs.digest_auth_password_;
  747. #endif
  748. keep_alive_ = rhs.keep_alive_;
  749. follow_location_ = rhs.follow_location_;
  750. tcp_nodelay_ = rhs.tcp_nodelay_;
  751. socket_options_ = rhs.socket_options_;
  752. compress_ = rhs.compress_;
  753. decompress_ = rhs.decompress_;
  754. interface_ = rhs.interface_;
  755. proxy_host_ = rhs.proxy_host_;
  756. proxy_port_ = rhs.proxy_port_;
  757. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  758. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  759. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  761. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  762. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  763. #endif
  764. logger_ = rhs.logger_;
  765. }
  766. private:
  767. socket_t create_client_socket() const;
  768. bool read_response_line(Stream &strm, Response &res);
  769. bool write_request(Stream &strm, const Request &req, bool close_connection);
  770. bool redirect(const Request &req, Response &res);
  771. bool handle_request(Stream &strm, const Request &req, Response &res,
  772. bool close_connection);
  773. void stop_core();
  774. std::shared_ptr<Response> send_with_content_provider(
  775. const char *method, const char *path, const Headers &headers,
  776. const std::string &body, size_t content_length,
  777. ContentProvider content_provider, const char *content_type);
  778. virtual bool process_socket(Socket &socket,
  779. std::function<bool(Stream &strm)> callback);
  780. virtual bool is_ssl() const;
  781. };
  782. class Client {
  783. public:
  784. // Universal interface
  785. explicit Client(const char *scheme_host_port);
  786. explicit Client(const char *scheme_host_port,
  787. const std::string &client_cert_path,
  788. const std::string &client_key_path);
  789. // HTTP only interface
  790. explicit Client(const std::string &host, int port);
  791. explicit Client(const std::string &host, int port,
  792. const std::string &client_cert_path,
  793. const std::string &client_key_path);
  794. ~Client();
  795. bool is_valid() const;
  796. Result Get(const char *path);
  797. Result Get(const char *path, const Headers &headers);
  798. Result Get(const char *path, Progress progress);
  799. Result Get(const char *path, const Headers &headers, Progress progress);
  800. Result Get(const char *path, ContentReceiver content_receiver);
  801. Result Get(const char *path, const Headers &headers,
  802. ContentReceiver content_receiver);
  803. Result Get(const char *path, ContentReceiver content_receiver,
  804. Progress progress);
  805. Result Get(const char *path, const Headers &headers,
  806. ContentReceiver content_receiver, Progress progress);
  807. Result Get(const char *path, ResponseHandler response_handler,
  808. ContentReceiver content_receiver);
  809. Result Get(const char *path, const Headers &headers,
  810. ResponseHandler response_handler,
  811. ContentReceiver content_receiver);
  812. Result Get(const char *path, const Headers &headers,
  813. ResponseHandler response_handler, ContentReceiver content_receiver,
  814. Progress progress);
  815. Result Get(const char *path, ResponseHandler response_handler,
  816. ContentReceiver content_receiver, Progress progress);
  817. Result Head(const char *path);
  818. Result Head(const char *path, const Headers &headers);
  819. Result Post(const char *path);
  820. Result Post(const char *path, const std::string &body,
  821. const char *content_type);
  822. Result Post(const char *path, const Headers &headers, const std::string &body,
  823. const char *content_type);
  824. Result Post(const char *path, size_t content_length,
  825. ContentProvider content_provider, const char *content_type);
  826. Result Post(const char *path, const Headers &headers, size_t content_length,
  827. ContentProvider content_provider, const char *content_type);
  828. Result Post(const char *path, const Params &params);
  829. Result Post(const char *path, const Headers &headers, const Params &params);
  830. Result Post(const char *path, const MultipartFormDataItems &items);
  831. Result Post(const char *path, const Headers &headers,
  832. const MultipartFormDataItems &items);
  833. Result Put(const char *path);
  834. Result Put(const char *path, const std::string &body,
  835. const char *content_type);
  836. Result Put(const char *path, const Headers &headers, const std::string &body,
  837. const char *content_type);
  838. Result Put(const char *path, size_t content_length,
  839. ContentProvider content_provider, const char *content_type);
  840. Result Put(const char *path, const Headers &headers, size_t content_length,
  841. ContentProvider content_provider, const char *content_type);
  842. Result Put(const char *path, const Params &params);
  843. Result Put(const char *path, const Headers &headers, const Params &params);
  844. Result Patch(const char *path, const std::string &body,
  845. const char *content_type);
  846. Result Patch(const char *path, const Headers &headers,
  847. const std::string &body, const char *content_type);
  848. Result Patch(const char *path, size_t content_length,
  849. ContentProvider content_provider, const char *content_type);
  850. Result Patch(const char *path, const Headers &headers, size_t content_length,
  851. ContentProvider content_provider, const char *content_type);
  852. Result Delete(const char *path);
  853. Result Delete(const char *path, const std::string &body,
  854. const char *content_type);
  855. Result Delete(const char *path, const Headers &headers);
  856. Result Delete(const char *path, const Headers &headers,
  857. const std::string &body, const char *content_type);
  858. Result Options(const char *path);
  859. Result Options(const char *path, const Headers &headers);
  860. bool send(const Request &req, Response &res);
  861. size_t is_socket_open() const;
  862. void stop();
  863. void set_default_headers(Headers headers);
  864. void set_tcp_nodelay(bool on);
  865. void set_socket_options(SocketOptions socket_options);
  866. void set_connection_timeout(time_t sec, time_t usec = 0);
  867. void set_read_timeout(time_t sec, time_t usec = 0);
  868. void set_write_timeout(time_t sec, time_t usec = 0);
  869. void set_basic_auth(const char *username, const char *password);
  870. void set_bearer_token_auth(const char *token);
  871. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  872. void set_digest_auth(const char *username, const char *password);
  873. #endif
  874. void set_keep_alive(bool on);
  875. void set_follow_location(bool on);
  876. void set_compress(bool on);
  877. void set_decompress(bool on);
  878. void set_interface(const char *intf);
  879. void set_proxy(const char *host, int port);
  880. void set_proxy_basic_auth(const char *username, const char *password);
  881. void set_proxy_bearer_token_auth(const char *token);
  882. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  883. void set_proxy_digest_auth(const char *username, const char *password);
  884. #endif
  885. void set_logger(Logger logger);
  886. // SSL
  887. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  888. Client &set_ca_cert_path(const char *ca_cert_file_path,
  889. const char *ca_cert_dir_path = nullptr);
  890. Client &set_ca_cert_store(X509_STORE *ca_cert_store);
  891. Client &enable_server_certificate_verification(bool enabled);
  892. long get_openssl_verify_result() const;
  893. SSL_CTX *ssl_context() const;
  894. #endif
  895. private:
  896. std::shared_ptr<ClientImpl> cli_;
  897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  898. bool is_ssl_ = false;
  899. #endif
  900. }; // namespace httplib
  901. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  902. class SSLServer : public Server {
  903. public:
  904. SSLServer(const char *cert_path, const char *private_key_path,
  905. const char *client_ca_cert_file_path = nullptr,
  906. const char *client_ca_cert_dir_path = nullptr);
  907. SSLServer(X509 *cert, EVP_PKEY *private_key,
  908. X509_STORE *client_ca_cert_store = nullptr);
  909. ~SSLServer() override;
  910. bool is_valid() const override;
  911. private:
  912. bool process_and_close_socket(socket_t sock) override;
  913. SSL_CTX *ctx_;
  914. std::mutex ctx_mutex_;
  915. };
  916. class SSLClient : public ClientImpl {
  917. public:
  918. explicit SSLClient(const std::string &host);
  919. explicit SSLClient(const std::string &host, int port);
  920. explicit SSLClient(const std::string &host, int port,
  921. const std::string &client_cert_path,
  922. const std::string &client_key_path);
  923. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  924. EVP_PKEY *client_key);
  925. ~SSLClient() override;
  926. bool is_valid() const override;
  927. void set_ca_cert_path(const char *ca_cert_file_path,
  928. const char *ca_cert_dir_path = nullptr);
  929. void set_ca_cert_store(X509_STORE *ca_cert_store);
  930. void enable_server_certificate_verification(bool enabled);
  931. long get_openssl_verify_result() const;
  932. SSL_CTX *ssl_context() const;
  933. private:
  934. bool create_and_connect_socket(Socket &socket) override;
  935. void close_socket(Socket &socket, bool process_socket_ret) override;
  936. bool process_socket(Socket &socket,
  937. std::function<bool(Stream &strm)> callback) override;
  938. bool is_ssl() const override;
  939. bool connect_with_proxy(Socket &sock, Response &res, bool &success);
  940. bool initialize_ssl(Socket &socket);
  941. bool load_certs();
  942. bool verify_host(X509 *server_cert) const;
  943. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  944. bool verify_host_with_common_name(X509 *server_cert) const;
  945. bool check_host_name(const char *pattern, size_t pattern_len) const;
  946. SSL_CTX *ctx_;
  947. std::mutex ctx_mutex_;
  948. std::once_flag initialize_cert_;
  949. std::vector<std::string> host_components_;
  950. std::string ca_cert_file_path_;
  951. std::string ca_cert_dir_path_;
  952. X509_STORE *ca_cert_store_ = nullptr;
  953. bool server_certificate_verification_ = true;
  954. long verify_result_ = 0;
  955. friend class ClientImpl;
  956. };
  957. #endif
  958. // ----------------------------------------------------------------------------
  959. /*
  960. * Implementation
  961. */
  962. namespace detail {
  963. inline bool is_hex(char c, int &v) {
  964. if (0x20 <= c && isdigit(c)) {
  965. v = c - '0';
  966. return true;
  967. } else if ('A' <= c && c <= 'F') {
  968. v = c - 'A' + 10;
  969. return true;
  970. } else if ('a' <= c && c <= 'f') {
  971. v = c - 'a' + 10;
  972. return true;
  973. }
  974. return false;
  975. }
  976. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  977. int &val) {
  978. if (i >= s.size()) { return false; }
  979. val = 0;
  980. for (; cnt; i++, cnt--) {
  981. if (!s[i]) { return false; }
  982. int v = 0;
  983. if (is_hex(s[i], v)) {
  984. val = val * 16 + v;
  985. } else {
  986. return false;
  987. }
  988. }
  989. return true;
  990. }
  991. inline std::string from_i_to_hex(size_t n) {
  992. const char *charset = "0123456789abcdef";
  993. std::string ret;
  994. do {
  995. ret = charset[n & 15] + ret;
  996. n >>= 4;
  997. } while (n > 0);
  998. return ret;
  999. }
  1000. inline size_t to_utf8(int code, char *buff) {
  1001. if (code < 0x0080) {
  1002. buff[0] = (code & 0x7F);
  1003. return 1;
  1004. } else if (code < 0x0800) {
  1005. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  1006. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  1007. return 2;
  1008. } else if (code < 0xD800) {
  1009. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  1010. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1011. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  1012. return 3;
  1013. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  1014. return 0;
  1015. } else if (code < 0x10000) {
  1016. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  1017. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1018. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  1019. return 3;
  1020. } else if (code < 0x110000) {
  1021. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  1022. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  1023. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1024. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  1025. return 4;
  1026. }
  1027. // NOTREACHED
  1028. return 0;
  1029. }
  1030. // NOTE: This code came up with the following stackoverflow post:
  1031. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  1032. inline std::string base64_encode(const std::string &in) {
  1033. static const auto lookup =
  1034. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1035. std::string out;
  1036. out.reserve(in.size());
  1037. int val = 0;
  1038. int valb = -6;
  1039. for (auto c : in) {
  1040. val = (val << 8) + static_cast<uint8_t>(c);
  1041. valb += 8;
  1042. while (valb >= 0) {
  1043. out.push_back(lookup[(val >> valb) & 0x3F]);
  1044. valb -= 6;
  1045. }
  1046. }
  1047. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  1048. while (out.size() % 4) {
  1049. out.push_back('=');
  1050. }
  1051. return out;
  1052. }
  1053. inline bool is_file(const std::string &path) {
  1054. struct stat st;
  1055. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  1056. }
  1057. inline bool is_dir(const std::string &path) {
  1058. struct stat st;
  1059. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  1060. }
  1061. inline bool is_valid_path(const std::string &path) {
  1062. size_t level = 0;
  1063. size_t i = 0;
  1064. // Skip slash
  1065. while (i < path.size() && path[i] == '/') {
  1066. i++;
  1067. }
  1068. while (i < path.size()) {
  1069. // Read component
  1070. auto beg = i;
  1071. while (i < path.size() && path[i] != '/') {
  1072. i++;
  1073. }
  1074. auto len = i - beg;
  1075. assert(len > 0);
  1076. if (!path.compare(beg, len, ".")) {
  1077. ;
  1078. } else if (!path.compare(beg, len, "..")) {
  1079. if (level == 0) { return false; }
  1080. level--;
  1081. } else {
  1082. level++;
  1083. }
  1084. // Skip slash
  1085. while (i < path.size() && path[i] == '/') {
  1086. i++;
  1087. }
  1088. }
  1089. return true;
  1090. }
  1091. inline std::string encode_url(const std::string &s) {
  1092. std::string result;
  1093. for (size_t i = 0; s[i]; i++) {
  1094. switch (s[i]) {
  1095. case ' ': result += "%20"; break;
  1096. case '+': result += "%2B"; break;
  1097. case '\r': result += "%0D"; break;
  1098. case '\n': result += "%0A"; break;
  1099. case '\'': result += "%27"; break;
  1100. case ',': result += "%2C"; break;
  1101. // case ':': result += "%3A"; break; // ok? probably...
  1102. case ';': result += "%3B"; break;
  1103. default:
  1104. auto c = static_cast<uint8_t>(s[i]);
  1105. if (c >= 0x80) {
  1106. result += '%';
  1107. char hex[4];
  1108. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  1109. assert(len == 2);
  1110. result.append(hex, static_cast<size_t>(len));
  1111. } else {
  1112. result += s[i];
  1113. }
  1114. break;
  1115. }
  1116. }
  1117. return result;
  1118. }
  1119. inline std::string decode_url(const std::string &s,
  1120. bool convert_plus_to_space) {
  1121. std::string result;
  1122. for (size_t i = 0; i < s.size(); i++) {
  1123. if (s[i] == '%' && i + 1 < s.size()) {
  1124. if (s[i + 1] == 'u') {
  1125. int val = 0;
  1126. if (from_hex_to_i(s, i + 2, 4, val)) {
  1127. // 4 digits Unicode codes
  1128. char buff[4];
  1129. size_t len = to_utf8(val, buff);
  1130. if (len > 0) { result.append(buff, len); }
  1131. i += 5; // 'u0000'
  1132. } else {
  1133. result += s[i];
  1134. }
  1135. } else {
  1136. int val = 0;
  1137. if (from_hex_to_i(s, i + 1, 2, val)) {
  1138. // 2 digits hex codes
  1139. result += static_cast<char>(val);
  1140. i += 2; // '00'
  1141. } else {
  1142. result += s[i];
  1143. }
  1144. }
  1145. } else if (convert_plus_to_space && s[i] == '+') {
  1146. result += ' ';
  1147. } else {
  1148. result += s[i];
  1149. }
  1150. }
  1151. return result;
  1152. }
  1153. inline void read_file(const std::string &path, std::string &out) {
  1154. std::ifstream fs(path, std::ios_base::binary);
  1155. fs.seekg(0, std::ios_base::end);
  1156. auto size = fs.tellg();
  1157. fs.seekg(0);
  1158. out.resize(static_cast<size_t>(size));
  1159. fs.read(&out[0], static_cast<std::streamsize>(size));
  1160. }
  1161. inline std::string file_extension(const std::string &path) {
  1162. std::smatch m;
  1163. static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  1164. if (std::regex_search(path, m, re)) { return m[1].str(); }
  1165. return std::string();
  1166. }
  1167. inline std::pair<int, int> trim(const char *b, const char *e, int left,
  1168. int right) {
  1169. while (b + left < e && b[left] == ' ') {
  1170. left++;
  1171. }
  1172. while (right - 1 >= 0 && b[right - 1] == ' ') {
  1173. right--;
  1174. }
  1175. return std::make_pair(left, right);
  1176. }
  1177. template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
  1178. int i = 0;
  1179. int beg = 0;
  1180. while (e ? (b + i != e) : (b[i] != '\0')) {
  1181. if (b[i] == d) {
  1182. auto r = trim(b, e, beg, i);
  1183. fn(&b[r.first], &b[r.second]);
  1184. beg = i + 1;
  1185. }
  1186. i++;
  1187. }
  1188. if (i) {
  1189. auto r = trim(b, e, beg, i);
  1190. fn(&b[r.first], &b[r.second]);
  1191. }
  1192. }
  1193. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  1194. // to store data. The call can set memory on stack for performance.
  1195. class stream_line_reader {
  1196. public:
  1197. stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
  1198. : strm_(strm), fixed_buffer_(fixed_buffer),
  1199. fixed_buffer_size_(fixed_buffer_size) {}
  1200. const char *ptr() const {
  1201. if (glowable_buffer_.empty()) {
  1202. return fixed_buffer_;
  1203. } else {
  1204. return glowable_buffer_.data();
  1205. }
  1206. }
  1207. size_t size() const {
  1208. if (glowable_buffer_.empty()) {
  1209. return fixed_buffer_used_size_;
  1210. } else {
  1211. return glowable_buffer_.size();
  1212. }
  1213. }
  1214. bool end_with_crlf() const {
  1215. auto end = ptr() + size();
  1216. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  1217. }
  1218. bool getline() {
  1219. fixed_buffer_used_size_ = 0;
  1220. glowable_buffer_.clear();
  1221. for (size_t i = 0;; i++) {
  1222. char byte;
  1223. auto n = strm_.read(&byte, 1);
  1224. if (n < 0) {
  1225. return false;
  1226. } else if (n == 0) {
  1227. if (i == 0) {
  1228. return false;
  1229. } else {
  1230. break;
  1231. }
  1232. }
  1233. append(byte);
  1234. if (byte == '\n') { break; }
  1235. }
  1236. return true;
  1237. }
  1238. private:
  1239. void append(char c) {
  1240. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  1241. fixed_buffer_[fixed_buffer_used_size_++] = c;
  1242. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  1243. } else {
  1244. if (glowable_buffer_.empty()) {
  1245. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  1246. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  1247. }
  1248. glowable_buffer_ += c;
  1249. }
  1250. }
  1251. Stream &strm_;
  1252. char *fixed_buffer_;
  1253. const size_t fixed_buffer_size_;
  1254. size_t fixed_buffer_used_size_ = 0;
  1255. std::string glowable_buffer_;
  1256. };
  1257. inline int close_socket(socket_t sock) {
  1258. #ifdef _WIN32
  1259. return closesocket(sock);
  1260. #else
  1261. return close(sock);
  1262. #endif
  1263. }
  1264. template <typename T> inline ssize_t handle_EINTR(T fn) {
  1265. ssize_t res = false;
  1266. while (true) {
  1267. res = fn();
  1268. if (res < 0 && errno == EINTR) { continue; }
  1269. break;
  1270. }
  1271. return res;
  1272. }
  1273. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  1274. #ifdef CPPHTTPLIB_USE_POLL
  1275. struct pollfd pfd_read;
  1276. pfd_read.fd = sock;
  1277. pfd_read.events = POLLIN;
  1278. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1279. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1280. #else
  1281. fd_set fds;
  1282. FD_ZERO(&fds);
  1283. FD_SET(sock, &fds);
  1284. timeval tv;
  1285. tv.tv_sec = static_cast<long>(sec);
  1286. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1287. return handle_EINTR([&]() {
  1288. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  1289. });
  1290. #endif
  1291. }
  1292. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  1293. #ifdef CPPHTTPLIB_USE_POLL
  1294. struct pollfd pfd_read;
  1295. pfd_read.fd = sock;
  1296. pfd_read.events = POLLOUT;
  1297. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1298. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1299. #else
  1300. fd_set fds;
  1301. FD_ZERO(&fds);
  1302. FD_SET(sock, &fds);
  1303. timeval tv;
  1304. tv.tv_sec = static_cast<long>(sec);
  1305. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1306. return handle_EINTR([&]() {
  1307. return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
  1308. });
  1309. #endif
  1310. }
  1311. inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
  1312. #ifdef CPPHTTPLIB_USE_POLL
  1313. struct pollfd pfd_read;
  1314. pfd_read.fd = sock;
  1315. pfd_read.events = POLLIN | POLLOUT;
  1316. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1317. auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1318. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  1319. int error = 0;
  1320. socklen_t len = sizeof(error);
  1321. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1322. reinterpret_cast<char *>(&error), &len);
  1323. return res >= 0 && !error;
  1324. }
  1325. return false;
  1326. #else
  1327. fd_set fdsr;
  1328. FD_ZERO(&fdsr);
  1329. FD_SET(sock, &fdsr);
  1330. auto fdsw = fdsr;
  1331. auto fdse = fdsr;
  1332. timeval tv;
  1333. tv.tv_sec = static_cast<long>(sec);
  1334. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1335. auto ret = handle_EINTR([&]() {
  1336. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv);
  1337. });
  1338. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  1339. int error = 0;
  1340. socklen_t len = sizeof(error);
  1341. return getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1342. reinterpret_cast<char *>(&error), &len) >= 0 &&
  1343. !error;
  1344. }
  1345. return false;
  1346. #endif
  1347. }
  1348. class SocketStream : public Stream {
  1349. public:
  1350. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  1351. time_t write_timeout_sec, time_t write_timeout_usec);
  1352. ~SocketStream() override;
  1353. bool is_readable() const override;
  1354. bool is_writable() const override;
  1355. ssize_t read(char *ptr, size_t size) override;
  1356. ssize_t write(const char *ptr, size_t size) override;
  1357. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1358. private:
  1359. socket_t sock_;
  1360. time_t read_timeout_sec_;
  1361. time_t read_timeout_usec_;
  1362. time_t write_timeout_sec_;
  1363. time_t write_timeout_usec_;
  1364. };
  1365. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1366. class SSLSocketStream : public Stream {
  1367. public:
  1368. SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
  1369. time_t read_timeout_usec, time_t write_timeout_sec,
  1370. time_t write_timeout_usec);
  1371. ~SSLSocketStream() override;
  1372. bool is_readable() const override;
  1373. bool is_writable() const override;
  1374. ssize_t read(char *ptr, size_t size) override;
  1375. ssize_t write(const char *ptr, size_t size) override;
  1376. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1377. private:
  1378. socket_t sock_;
  1379. SSL *ssl_;
  1380. time_t read_timeout_sec_;
  1381. time_t read_timeout_usec_;
  1382. time_t write_timeout_sec_;
  1383. time_t write_timeout_usec_;
  1384. };
  1385. #endif
  1386. class BufferStream : public Stream {
  1387. public:
  1388. BufferStream() = default;
  1389. ~BufferStream() override = default;
  1390. bool is_readable() const override;
  1391. bool is_writable() const override;
  1392. ssize_t read(char *ptr, size_t size) override;
  1393. ssize_t write(const char *ptr, size_t size) override;
  1394. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1395. const std::string &get_buffer() const;
  1396. private:
  1397. std::string buffer;
  1398. size_t position = 0;
  1399. };
  1400. inline bool keep_alive(socket_t sock) {
  1401. using namespace std::chrono;
  1402. auto start = steady_clock::now();
  1403. while (true) {
  1404. auto val = select_read(sock, 0, 10000);
  1405. if (val < 0) {
  1406. return false;
  1407. } else if (val == 0) {
  1408. auto current = steady_clock::now();
  1409. auto duration = duration_cast<milliseconds>(current - start);
  1410. auto timeout = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND * 1000 +
  1411. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND / 1000;
  1412. if (duration.count() > timeout) { return false; }
  1413. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1414. } else {
  1415. return true;
  1416. }
  1417. }
  1418. }
  1419. template <typename T>
  1420. inline bool process_server_socket_core(socket_t sock,
  1421. size_t keep_alive_max_count,
  1422. T callback) {
  1423. assert(keep_alive_max_count > 0);
  1424. auto ret = false;
  1425. auto count = keep_alive_max_count;
  1426. while (count > 0 && keep_alive(sock)) {
  1427. auto close_connection = count == 1;
  1428. auto connection_closed = false;
  1429. ret = callback(close_connection, connection_closed);
  1430. if (!ret || connection_closed) { break; }
  1431. count--;
  1432. }
  1433. return ret;
  1434. }
  1435. template <typename T>
  1436. inline bool process_server_socket(socket_t sock, size_t keep_alive_max_count,
  1437. time_t read_timeout_sec,
  1438. time_t read_timeout_usec,
  1439. time_t write_timeout_sec,
  1440. time_t write_timeout_usec, T callback) {
  1441. return process_server_socket_core(
  1442. sock, keep_alive_max_count,
  1443. [&](bool close_connection, bool connection_closed) {
  1444. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  1445. write_timeout_sec, write_timeout_usec);
  1446. return callback(strm, close_connection, connection_closed);
  1447. });
  1448. }
  1449. template <typename T>
  1450. inline bool process_client_socket(socket_t sock, time_t read_timeout_sec,
  1451. time_t read_timeout_usec,
  1452. time_t write_timeout_sec,
  1453. time_t write_timeout_usec, T callback) {
  1454. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  1455. write_timeout_sec, write_timeout_usec);
  1456. return callback(strm);
  1457. }
  1458. inline int shutdown_socket(socket_t sock) {
  1459. #ifdef _WIN32
  1460. return shutdown(sock, SD_BOTH);
  1461. #else
  1462. return shutdown(sock, SHUT_RDWR);
  1463. #endif
  1464. }
  1465. template <typename BindOrConnect>
  1466. socket_t create_socket(const char *host, int port, int socket_flags,
  1467. bool tcp_nodelay, SocketOptions socket_options,
  1468. BindOrConnect bind_or_connect) {
  1469. // Get address info
  1470. struct addrinfo hints;
  1471. struct addrinfo *result;
  1472. memset(&hints, 0, sizeof(struct addrinfo));
  1473. hints.ai_family = AF_UNSPEC;
  1474. hints.ai_socktype = SOCK_STREAM;
  1475. hints.ai_flags = socket_flags;
  1476. hints.ai_protocol = 0;
  1477. auto service = std::to_string(port);
  1478. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  1479. #ifdef __linux__
  1480. res_init();
  1481. #endif
  1482. return INVALID_SOCKET;
  1483. }
  1484. for (auto rp = result; rp; rp = rp->ai_next) {
  1485. // Create a socket
  1486. #ifdef _WIN32
  1487. auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  1488. nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
  1489. /**
  1490. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  1491. * and above the socket creation fails on older Windows Systems.
  1492. *
  1493. * Let's try to create a socket the old way in this case.
  1494. *
  1495. * Reference:
  1496. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  1497. *
  1498. * WSA_FLAG_NO_HANDLE_INHERIT:
  1499. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  1500. * SP1, and later
  1501. *
  1502. */
  1503. if (sock == INVALID_SOCKET) {
  1504. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1505. }
  1506. #else
  1507. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1508. #endif
  1509. if (sock == INVALID_SOCKET) { continue; }
  1510. #ifndef _WIN32
  1511. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
  1512. #endif
  1513. if (tcp_nodelay) {
  1514. int yes = 1;
  1515. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&yes),
  1516. sizeof(yes));
  1517. }
  1518. if (socket_options) { socket_options(sock); }
  1519. if (rp->ai_family == AF_INET6) {
  1520. int no = 0;
  1521. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char *>(&no),
  1522. sizeof(no));
  1523. }
  1524. // bind or connect
  1525. if (bind_or_connect(sock, *rp)) {
  1526. freeaddrinfo(result);
  1527. return sock;
  1528. }
  1529. close_socket(sock);
  1530. }
  1531. freeaddrinfo(result);
  1532. return INVALID_SOCKET;
  1533. }
  1534. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  1535. #ifdef _WIN32
  1536. auto flags = nonblocking ? 1UL : 0UL;
  1537. ioctlsocket(sock, FIONBIO, &flags);
  1538. #else
  1539. auto flags = fcntl(sock, F_GETFL, 0);
  1540. fcntl(sock, F_SETFL,
  1541. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  1542. #endif
  1543. }
  1544. inline bool is_connection_error() {
  1545. #ifdef _WIN32
  1546. return WSAGetLastError() != WSAEWOULDBLOCK;
  1547. #else
  1548. return errno != EINPROGRESS;
  1549. #endif
  1550. }
  1551. inline bool bind_ip_address(socket_t sock, const char *host) {
  1552. struct addrinfo hints;
  1553. struct addrinfo *result;
  1554. memset(&hints, 0, sizeof(struct addrinfo));
  1555. hints.ai_family = AF_UNSPEC;
  1556. hints.ai_socktype = SOCK_STREAM;
  1557. hints.ai_protocol = 0;
  1558. if (getaddrinfo(host, "0", &hints, &result)) { return false; }
  1559. auto ret = false;
  1560. for (auto rp = result; rp; rp = rp->ai_next) {
  1561. const auto &ai = *rp;
  1562. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  1563. ret = true;
  1564. break;
  1565. }
  1566. }
  1567. freeaddrinfo(result);
  1568. return ret;
  1569. }
  1570. #ifndef _WIN32
  1571. inline std::string if2ip(const std::string &ifn) {
  1572. struct ifaddrs *ifap;
  1573. getifaddrs(&ifap);
  1574. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1575. if (ifa->ifa_addr && ifn == ifa->ifa_name) {
  1576. if (ifa->ifa_addr->sa_family == AF_INET) {
  1577. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  1578. char buf[INET_ADDRSTRLEN];
  1579. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  1580. freeifaddrs(ifap);
  1581. return std::string(buf, INET_ADDRSTRLEN);
  1582. }
  1583. }
  1584. }
  1585. }
  1586. freeifaddrs(ifap);
  1587. return std::string();
  1588. }
  1589. #endif
  1590. inline socket_t create_client_socket(const char *host, int port,
  1591. bool tcp_nodelay,
  1592. SocketOptions socket_options,
  1593. time_t timeout_sec, time_t timeout_usec,
  1594. const std::string &intf, Error &error) {
  1595. auto sock = create_socket(
  1596. host, port, 0, tcp_nodelay, socket_options,
  1597. [&](socket_t sock, struct addrinfo &ai) -> bool {
  1598. if (!intf.empty()) {
  1599. #ifndef _WIN32
  1600. auto ip = if2ip(intf);
  1601. if (ip.empty()) { ip = intf; }
  1602. if (!bind_ip_address(sock, ip.c_str())) {
  1603. error = Error::BindIPAddress;
  1604. return false;
  1605. }
  1606. #endif
  1607. }
  1608. set_nonblocking(sock, true);
  1609. auto ret =
  1610. ::connect(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  1611. if (ret < 0) {
  1612. if (is_connection_error() ||
  1613. !wait_until_socket_is_ready(sock, timeout_sec, timeout_usec)) {
  1614. close_socket(sock);
  1615. error = Error::Connection;
  1616. return false;
  1617. }
  1618. }
  1619. set_nonblocking(sock, false);
  1620. error = Error::Success;
  1621. return true;
  1622. });
  1623. if (sock != INVALID_SOCKET) {
  1624. if (error != Error::Success) { error = Error::Success; }
  1625. } else {
  1626. if (error == Error::Success) { error = Error::Connection; }
  1627. }
  1628. return sock;
  1629. }
  1630. inline void get_remote_ip_and_port(const struct sockaddr_storage &addr,
  1631. socklen_t addr_len, std::string &ip,
  1632. int &port) {
  1633. if (addr.ss_family == AF_INET) {
  1634. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  1635. } else if (addr.ss_family == AF_INET6) {
  1636. port =
  1637. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  1638. }
  1639. std::array<char, NI_MAXHOST> ipstr{};
  1640. if (!getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  1641. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  1642. 0, NI_NUMERICHOST)) {
  1643. ip = ipstr.data();
  1644. }
  1645. }
  1646. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  1647. struct sockaddr_storage addr;
  1648. socklen_t addr_len = sizeof(addr);
  1649. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  1650. &addr_len)) {
  1651. get_remote_ip_and_port(addr, addr_len, ip, port);
  1652. }
  1653. }
  1654. inline const char *
  1655. find_content_type(const std::string &path,
  1656. const std::map<std::string, std::string> &user_data) {
  1657. auto ext = file_extension(path);
  1658. auto it = user_data.find(ext);
  1659. if (it != user_data.end()) { return it->second.c_str(); }
  1660. if (ext == "txt") {
  1661. return "text/plain";
  1662. } else if (ext == "html" || ext == "htm") {
  1663. return "text/html";
  1664. } else if (ext == "css") {
  1665. return "text/css";
  1666. } else if (ext == "jpeg" || ext == "jpg") {
  1667. return "image/jpg";
  1668. } else if (ext == "png") {
  1669. return "image/png";
  1670. } else if (ext == "gif") {
  1671. return "image/gif";
  1672. } else if (ext == "svg") {
  1673. return "image/svg+xml";
  1674. } else if (ext == "ico") {
  1675. return "image/x-icon";
  1676. } else if (ext == "json") {
  1677. return "application/json";
  1678. } else if (ext == "pdf") {
  1679. return "application/pdf";
  1680. } else if (ext == "js") {
  1681. return "application/javascript";
  1682. } else if (ext == "wasm") {
  1683. return "application/wasm";
  1684. } else if (ext == "xml") {
  1685. return "application/xml";
  1686. } else if (ext == "xhtml") {
  1687. return "application/xhtml+xml";
  1688. }
  1689. return nullptr;
  1690. }
  1691. inline const char *status_message(int status) {
  1692. switch (status) {
  1693. case 100: return "Continue";
  1694. case 101: return "Switching Protocol";
  1695. case 102: return "Processing";
  1696. case 103: return "Early Hints";
  1697. case 200: return "OK";
  1698. case 201: return "Created";
  1699. case 202: return "Accepted";
  1700. case 203: return "Non-Authoritative Information";
  1701. case 204: return "No Content";
  1702. case 205: return "Reset Content";
  1703. case 206: return "Partial Content";
  1704. case 207: return "Multi-Status";
  1705. case 208: return "Already Reported";
  1706. case 226: return "IM Used";
  1707. case 300: return "Multiple Choice";
  1708. case 301: return "Moved Permanently";
  1709. case 302: return "Found";
  1710. case 303: return "See Other";
  1711. case 304: return "Not Modified";
  1712. case 305: return "Use Proxy";
  1713. case 306: return "unused";
  1714. case 307: return "Temporary Redirect";
  1715. case 308: return "Permanent Redirect";
  1716. case 400: return "Bad Request";
  1717. case 401: return "Unauthorized";
  1718. case 402: return "Payment Required";
  1719. case 403: return "Forbidden";
  1720. case 404: return "Not Found";
  1721. case 405: return "Method Not Allowed";
  1722. case 406: return "Not Acceptable";
  1723. case 407: return "Proxy Authentication Required";
  1724. case 408: return "Request Timeout";
  1725. case 409: return "Conflict";
  1726. case 410: return "Gone";
  1727. case 411: return "Length Required";
  1728. case 412: return "Precondition Failed";
  1729. case 413: return "Payload Too Large";
  1730. case 414: return "URI Too Long";
  1731. case 415: return "Unsupported Media Type";
  1732. case 416: return "Range Not Satisfiable";
  1733. case 417: return "Expectation Failed";
  1734. case 418: return "I'm a teapot";
  1735. case 421: return "Misdirected Request";
  1736. case 422: return "Unprocessable Entity";
  1737. case 423: return "Locked";
  1738. case 424: return "Failed Dependency";
  1739. case 425: return "Too Early";
  1740. case 426: return "Upgrade Required";
  1741. case 428: return "Precondition Required";
  1742. case 429: return "Too Many Requests";
  1743. case 431: return "Request Header Fields Too Large";
  1744. case 451: return "Unavailable For Legal Reasons";
  1745. case 501: return "Not Implemented";
  1746. case 502: return "Bad Gateway";
  1747. case 503: return "Service Unavailable";
  1748. case 504: return "Gateway Timeout";
  1749. case 505: return "HTTP Version Not Supported";
  1750. case 506: return "Variant Also Negotiates";
  1751. case 507: return "Insufficient Storage";
  1752. case 508: return "Loop Detected";
  1753. case 510: return "Not Extended";
  1754. case 511: return "Network Authentication Required";
  1755. default:
  1756. case 500: return "Internal Server Error";
  1757. }
  1758. }
  1759. inline bool can_compress_content_type(const std::string &content_type) {
  1760. return (!content_type.find("text/") && content_type != "text/event-stream") ||
  1761. content_type == "image/svg+xml" ||
  1762. content_type == "application/javascript" ||
  1763. content_type == "application/json" ||
  1764. content_type == "application/xml" ||
  1765. content_type == "application/xhtml+xml";
  1766. }
  1767. enum class EncodingType { None = 0, Gzip, Brotli };
  1768. inline EncodingType encoding_type(const Request &req, const Response &res) {
  1769. auto ret =
  1770. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  1771. if (!ret) { return EncodingType::None; }
  1772. const auto &s = req.get_header_value("Accept-Encoding");
  1773. (void)(s);
  1774. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1775. // TODO: 'Accept-Encoding' has br, not br;q=0
  1776. ret = s.find("br") != std::string::npos;
  1777. if (ret) { return EncodingType::Brotli; }
  1778. #endif
  1779. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1780. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  1781. ret = s.find("gzip") != std::string::npos;
  1782. if (ret) { return EncodingType::Gzip; }
  1783. #endif
  1784. return EncodingType::None;
  1785. }
  1786. class compressor {
  1787. public:
  1788. virtual ~compressor(){};
  1789. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1790. virtual bool compress(const char *data, size_t data_length, bool last,
  1791. Callback callback) = 0;
  1792. };
  1793. class decompressor {
  1794. public:
  1795. virtual ~decompressor() {}
  1796. virtual bool is_valid() const = 0;
  1797. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1798. virtual bool decompress(const char *data, size_t data_length,
  1799. Callback callback) = 0;
  1800. };
  1801. class nocompressor : public compressor {
  1802. public:
  1803. ~nocompressor(){};
  1804. bool compress(const char *data, size_t data_length, bool /*last*/,
  1805. Callback callback) override {
  1806. if (!data_length) { return true; }
  1807. return callback(data, data_length);
  1808. }
  1809. };
  1810. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1811. class gzip_compressor : public compressor {
  1812. public:
  1813. gzip_compressor() {
  1814. std::memset(&strm_, 0, sizeof(strm_));
  1815. strm_.zalloc = Z_NULL;
  1816. strm_.zfree = Z_NULL;
  1817. strm_.opaque = Z_NULL;
  1818. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  1819. Z_DEFAULT_STRATEGY) == Z_OK;
  1820. }
  1821. ~gzip_compressor() { deflateEnd(&strm_); }
  1822. bool compress(const char *data, size_t data_length, bool last,
  1823. Callback callback) override {
  1824. assert(is_valid_);
  1825. auto flush = last ? Z_FINISH : Z_NO_FLUSH;
  1826. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(data_length);
  1827. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1828. int ret = Z_OK;
  1829. std::array<char, 16384> buff{};
  1830. do {
  1831. strm_.avail_out = buff.size();
  1832. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  1833. ret = deflate(&strm_, flush);
  1834. assert(ret != Z_STREAM_ERROR);
  1835. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  1836. return false;
  1837. }
  1838. } while (strm_.avail_out == 0);
  1839. assert((last && ret == Z_STREAM_END) || (!last && ret == Z_OK));
  1840. assert(strm_.avail_in == 0);
  1841. return true;
  1842. }
  1843. private:
  1844. bool is_valid_ = false;
  1845. z_stream strm_;
  1846. };
  1847. class gzip_decompressor : public decompressor {
  1848. public:
  1849. gzip_decompressor() {
  1850. std::memset(&strm_, 0, sizeof(strm_));
  1851. strm_.zalloc = Z_NULL;
  1852. strm_.zfree = Z_NULL;
  1853. strm_.opaque = Z_NULL;
  1854. // 15 is the value of wbits, which should be at the maximum possible value
  1855. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  1856. // that the stream type should be automatically detected either gzip or
  1857. // deflate.
  1858. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  1859. }
  1860. ~gzip_decompressor() { inflateEnd(&strm_); }
  1861. bool is_valid() const override { return is_valid_; }
  1862. bool decompress(const char *data, size_t data_length,
  1863. Callback callback) override {
  1864. assert(is_valid_);
  1865. int ret = Z_OK;
  1866. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(data_length);
  1867. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1868. std::array<char, 16384> buff{};
  1869. do {
  1870. strm_.avail_out = buff.size();
  1871. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  1872. ret = inflate(&strm_, Z_NO_FLUSH);
  1873. assert(ret != Z_STREAM_ERROR);
  1874. switch (ret) {
  1875. case Z_NEED_DICT:
  1876. case Z_DATA_ERROR:
  1877. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  1878. }
  1879. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  1880. return false;
  1881. }
  1882. } while (strm_.avail_out == 0);
  1883. return ret == Z_OK || ret == Z_STREAM_END;
  1884. }
  1885. private:
  1886. bool is_valid_ = false;
  1887. z_stream strm_;
  1888. };
  1889. #endif
  1890. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1891. class brotli_compressor : public compressor {
  1892. public:
  1893. brotli_compressor() {
  1894. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  1895. }
  1896. ~brotli_compressor() { BrotliEncoderDestroyInstance(state_); }
  1897. bool compress(const char *data, size_t data_length, bool last,
  1898. Callback callback) override {
  1899. std::array<uint8_t, 16384> buff{};
  1900. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  1901. auto available_in = data_length;
  1902. auto next_in = reinterpret_cast<const uint8_t *>(data);
  1903. for (;;) {
  1904. if (last) {
  1905. if (BrotliEncoderIsFinished(state_)) { break; }
  1906. } else {
  1907. if (!available_in) { break; }
  1908. }
  1909. auto available_out = buff.size();
  1910. auto next_out = buff.data();
  1911. if (!BrotliEncoderCompressStream(state_, operation, &available_in,
  1912. &next_in, &available_out, &next_out,
  1913. nullptr)) {
  1914. return false;
  1915. }
  1916. auto output_bytes = buff.size() - available_out;
  1917. if (output_bytes) {
  1918. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  1919. }
  1920. }
  1921. return true;
  1922. }
  1923. private:
  1924. BrotliEncoderState *state_ = nullptr;
  1925. };
  1926. class brotli_decompressor : public decompressor {
  1927. public:
  1928. brotli_decompressor() {
  1929. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  1930. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  1931. : BROTLI_DECODER_RESULT_ERROR;
  1932. }
  1933. ~brotli_decompressor() {
  1934. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  1935. }
  1936. bool is_valid() const override { return decoder_s; }
  1937. bool decompress(const char *data, size_t data_length,
  1938. Callback callback) override {
  1939. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  1940. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  1941. return 0;
  1942. }
  1943. const uint8_t *next_in = (const uint8_t *)data;
  1944. size_t avail_in = data_length;
  1945. size_t total_out;
  1946. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  1947. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  1948. char output[1024];
  1949. char *next_out = output;
  1950. size_t avail_out = sizeof(output);
  1951. decoder_r = BrotliDecoderDecompressStream(
  1952. decoder_s, &avail_in, &next_in, &avail_out,
  1953. reinterpret_cast<unsigned char **>(&next_out), &total_out);
  1954. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  1955. if (!callback((const char *)output, sizeof(output) - avail_out)) {
  1956. return false;
  1957. }
  1958. }
  1959. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  1960. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  1961. }
  1962. private:
  1963. BrotliDecoderResult decoder_r;
  1964. BrotliDecoderState *decoder_s = nullptr;
  1965. };
  1966. #endif
  1967. inline bool has_header(const Headers &headers, const char *key) {
  1968. return headers.find(key) != headers.end();
  1969. }
  1970. inline const char *get_header_value(const Headers &headers, const char *key,
  1971. size_t id = 0, const char *def = nullptr) {
  1972. auto rng = headers.equal_range(key);
  1973. auto it = rng.first;
  1974. std::advance(it, static_cast<ssize_t>(id));
  1975. if (it != rng.second) { return it->second.c_str(); }
  1976. return def;
  1977. }
  1978. template <typename T>
  1979. inline T get_header_value(const Headers & /*headers*/, const char * /*key*/,
  1980. size_t /*id*/ = 0, uint64_t /*def*/ = 0) {}
  1981. template <>
  1982. inline uint64_t get_header_value<uint64_t>(const Headers &headers,
  1983. const char *key, size_t id,
  1984. uint64_t def) {
  1985. auto rng = headers.equal_range(key);
  1986. auto it = rng.first;
  1987. std::advance(it, static_cast<ssize_t>(id));
  1988. if (it != rng.second) {
  1989. return std::strtoull(it->second.data(), nullptr, 10);
  1990. }
  1991. return def;
  1992. }
  1993. inline void parse_header(const char *beg, const char *end, Headers &headers) {
  1994. auto p = beg;
  1995. while (p < end && *p != ':') {
  1996. p++;
  1997. }
  1998. if (p < end) {
  1999. auto key_end = p;
  2000. p++; // skip ':'
  2001. while (p < end && (*p == ' ' || *p == '\t')) {
  2002. p++;
  2003. }
  2004. if (p < end) {
  2005. auto val_begin = p;
  2006. while (p < end) {
  2007. p++;
  2008. }
  2009. headers.emplace(std::string(beg, key_end),
  2010. decode_url(std::string(val_begin, end), true));
  2011. }
  2012. }
  2013. }
  2014. inline bool read_headers(Stream &strm, Headers &headers) {
  2015. const auto bufsiz = 2048;
  2016. char buf[bufsiz];
  2017. stream_line_reader line_reader(strm, buf, bufsiz);
  2018. for (;;) {
  2019. if (!line_reader.getline()) { return false; }
  2020. // Check if the line ends with CRLF.
  2021. if (line_reader.end_with_crlf()) {
  2022. // Blank line indicates end of headers.
  2023. if (line_reader.size() == 2) { break; }
  2024. } else {
  2025. continue; // Skip invalid line.
  2026. }
  2027. // Skip trailing spaces and tabs.
  2028. auto end = line_reader.ptr() + line_reader.size() - 2;
  2029. while (line_reader.ptr() < end && (end[-1] == ' ' || end[-1] == '\t')) {
  2030. end--;
  2031. }
  2032. parse_header(line_reader.ptr(), end, headers);
  2033. }
  2034. return true;
  2035. }
  2036. inline bool read_content_with_length(Stream &strm, uint64_t len,
  2037. Progress progress, ContentReceiver out) {
  2038. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2039. uint64_t r = 0;
  2040. while (r < len) {
  2041. auto read_len = static_cast<size_t>(len - r);
  2042. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  2043. if (n <= 0) { return false; }
  2044. if (!out(buf, static_cast<size_t>(n))) { return false; }
  2045. r += static_cast<uint64_t>(n);
  2046. if (progress) {
  2047. if (!progress(r, len)) { return false; }
  2048. }
  2049. }
  2050. return true;
  2051. }
  2052. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  2053. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2054. uint64_t r = 0;
  2055. while (r < len) {
  2056. auto read_len = static_cast<size_t>(len - r);
  2057. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  2058. if (n <= 0) { return; }
  2059. r += static_cast<uint64_t>(n);
  2060. }
  2061. }
  2062. inline bool read_content_without_length(Stream &strm, ContentReceiver out) {
  2063. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2064. for (;;) {
  2065. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  2066. if (n < 0) {
  2067. return false;
  2068. } else if (n == 0) {
  2069. return true;
  2070. }
  2071. if (!out(buf, static_cast<size_t>(n))) { return false; }
  2072. }
  2073. return true;
  2074. }
  2075. inline bool read_content_chunked(Stream &strm, ContentReceiver out) {
  2076. const auto bufsiz = 16;
  2077. char buf[bufsiz];
  2078. stream_line_reader line_reader(strm, buf, bufsiz);
  2079. if (!line_reader.getline()) { return false; }
  2080. unsigned long chunk_len;
  2081. while (true) {
  2082. char *end_ptr;
  2083. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  2084. if (end_ptr == line_reader.ptr()) { return false; }
  2085. if (chunk_len == ULONG_MAX) { return false; }
  2086. if (chunk_len == 0) { break; }
  2087. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  2088. return false;
  2089. }
  2090. if (!line_reader.getline()) { return false; }
  2091. if (strcmp(line_reader.ptr(), "\r\n")) { break; }
  2092. if (!line_reader.getline()) { return false; }
  2093. }
  2094. if (chunk_len == 0) {
  2095. // Reader terminator after chunks
  2096. if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
  2097. return false;
  2098. }
  2099. return true;
  2100. }
  2101. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  2102. return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
  2103. "chunked");
  2104. }
  2105. template <typename T, typename U>
  2106. bool prepare_content_receiver(T &x, int &status, ContentReceiver receiver,
  2107. bool decompress, U callback) {
  2108. if (decompress) {
  2109. std::string encoding = x.get_header_value("Content-Encoding");
  2110. std::shared_ptr<decompressor> decompressor;
  2111. if (encoding.find("gzip") != std::string::npos ||
  2112. encoding.find("deflate") != std::string::npos) {
  2113. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2114. decompressor = std::make_shared<gzip_decompressor>();
  2115. #else
  2116. status = 415;
  2117. return false;
  2118. #endif
  2119. } else if (encoding.find("br") != std::string::npos) {
  2120. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2121. decompressor = std::make_shared<brotli_decompressor>();
  2122. #else
  2123. status = 415;
  2124. return false;
  2125. #endif
  2126. }
  2127. if (decompressor) {
  2128. if (decompressor->is_valid()) {
  2129. ContentReceiver out = [&](const char *buf, size_t n) {
  2130. return decompressor->decompress(
  2131. buf, n,
  2132. [&](const char *buf, size_t n) { return receiver(buf, n); });
  2133. };
  2134. return callback(out);
  2135. } else {
  2136. status = 500;
  2137. return false;
  2138. }
  2139. }
  2140. }
  2141. ContentReceiver out = [&](const char *buf, size_t n) {
  2142. return receiver(buf, n);
  2143. };
  2144. return callback(out);
  2145. }
  2146. template <typename T>
  2147. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  2148. Progress progress, ContentReceiver receiver,
  2149. bool decompress) {
  2150. return prepare_content_receiver(
  2151. x, status, receiver, decompress, [&](ContentReceiver &out) {
  2152. auto ret = true;
  2153. auto exceed_payload_max_length = false;
  2154. if (is_chunked_transfer_encoding(x.headers)) {
  2155. ret = read_content_chunked(strm, out);
  2156. } else if (!has_header(x.headers, "Content-Length")) {
  2157. ret = read_content_without_length(strm, out);
  2158. } else {
  2159. auto len = get_header_value<uint64_t>(x.headers, "Content-Length");
  2160. if (len > payload_max_length) {
  2161. exceed_payload_max_length = true;
  2162. skip_content_with_length(strm, len);
  2163. ret = false;
  2164. } else if (len > 0) {
  2165. ret = read_content_with_length(strm, len, progress, out);
  2166. }
  2167. }
  2168. if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
  2169. return ret;
  2170. });
  2171. }
  2172. template <typename T>
  2173. inline ssize_t write_headers(Stream &strm, const T &info,
  2174. const Headers &headers) {
  2175. ssize_t write_len = 0;
  2176. for (const auto &x : info.headers) {
  2177. if (x.first == "EXCEPTION_WHAT") { continue; }
  2178. auto len =
  2179. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  2180. if (len < 0) { return len; }
  2181. write_len += len;
  2182. }
  2183. for (const auto &x : headers) {
  2184. auto len =
  2185. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  2186. if (len < 0) { return len; }
  2187. write_len += len;
  2188. }
  2189. auto len = strm.write("\r\n");
  2190. if (len < 0) { return len; }
  2191. write_len += len;
  2192. return write_len;
  2193. }
  2194. inline bool write_data(Stream &strm, const char *d, size_t l) {
  2195. size_t offset = 0;
  2196. while (offset < l) {
  2197. auto length = strm.write(d + offset, l - offset);
  2198. if (length < 0) { return false; }
  2199. offset += static_cast<size_t>(length);
  2200. }
  2201. return true;
  2202. }
  2203. template <typename T>
  2204. inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
  2205. size_t offset, size_t length, T is_shutting_down) {
  2206. size_t begin_offset = offset;
  2207. size_t end_offset = offset + length;
  2208. auto ok = true;
  2209. DataSink data_sink;
  2210. data_sink.write = [&](const char *d, size_t l) {
  2211. if (ok) {
  2212. offset += l;
  2213. if (!write_data(strm, d, l)) { ok = false; }
  2214. }
  2215. };
  2216. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2217. while (offset < end_offset && !is_shutting_down()) {
  2218. if (!content_provider(offset, end_offset - offset, data_sink)) {
  2219. return -1;
  2220. }
  2221. if (!ok) { return -1; }
  2222. }
  2223. return static_cast<ssize_t>(offset - begin_offset);
  2224. }
  2225. template <typename T>
  2226. inline ssize_t write_content_without_length(Stream &strm,
  2227. ContentProvider content_provider,
  2228. T is_shutting_down) {
  2229. size_t offset = 0;
  2230. auto data_available = true;
  2231. auto ok = true;
  2232. DataSink data_sink;
  2233. data_sink.write = [&](const char *d, size_t l) {
  2234. if (ok) {
  2235. offset += l;
  2236. if (!write_data(strm, d, l)) { ok = false; }
  2237. }
  2238. };
  2239. data_sink.done = [&](void) { data_available = false; };
  2240. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2241. while (data_available && !is_shutting_down()) {
  2242. if (!content_provider(offset, 0, data_sink)) { return -1; }
  2243. if (!ok) { return -1; }
  2244. }
  2245. return static_cast<ssize_t>(offset);
  2246. }
  2247. template <typename T, typename U>
  2248. inline ssize_t write_content_chunked(Stream &strm,
  2249. ContentProvider content_provider,
  2250. T is_shutting_down, U &compressor) {
  2251. size_t offset = 0;
  2252. auto data_available = true;
  2253. ssize_t total_written_length = 0;
  2254. auto ok = true;
  2255. DataSink data_sink;
  2256. data_sink.write = [&](const char *d, size_t l) {
  2257. if (!ok) { return; }
  2258. data_available = l > 0;
  2259. offset += l;
  2260. std::string payload;
  2261. if (!compressor.compress(d, l, false,
  2262. [&](const char *data, size_t data_len) {
  2263. payload.append(data, data_len);
  2264. return true;
  2265. })) {
  2266. ok = false;
  2267. return;
  2268. }
  2269. if (!payload.empty()) {
  2270. // Emit chunked response header and footer for each chunk
  2271. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  2272. if (write_data(strm, chunk.data(), chunk.size())) {
  2273. total_written_length += chunk.size();
  2274. } else {
  2275. ok = false;
  2276. return;
  2277. }
  2278. }
  2279. };
  2280. data_sink.done = [&](void) {
  2281. if (!ok) { return; }
  2282. data_available = false;
  2283. std::string payload;
  2284. if (!compressor.compress(nullptr, 0, true,
  2285. [&](const char *data, size_t data_len) {
  2286. payload.append(data, data_len);
  2287. return true;
  2288. })) {
  2289. ok = false;
  2290. return;
  2291. }
  2292. if (!payload.empty()) {
  2293. // Emit chunked response header and footer for each chunk
  2294. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  2295. if (write_data(strm, chunk.data(), chunk.size())) {
  2296. total_written_length += chunk.size();
  2297. } else {
  2298. ok = false;
  2299. return;
  2300. }
  2301. }
  2302. static const std::string done_marker("0\r\n\r\n");
  2303. if (write_data(strm, done_marker.data(), done_marker.size())) {
  2304. total_written_length += done_marker.size();
  2305. } else {
  2306. ok = false;
  2307. }
  2308. };
  2309. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2310. while (data_available && !is_shutting_down()) {
  2311. if (!content_provider(offset, 0, data_sink)) { return -1; }
  2312. if (!ok) { return -1; }
  2313. }
  2314. return total_written_length;
  2315. }
  2316. template <typename T>
  2317. inline bool redirect(T &cli, const Request &req, Response &res,
  2318. const std::string &path) {
  2319. Request new_req = req;
  2320. new_req.path = path;
  2321. new_req.redirect_count -= 1;
  2322. if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) {
  2323. new_req.method = "GET";
  2324. new_req.body.clear();
  2325. new_req.headers.clear();
  2326. }
  2327. Response new_res;
  2328. auto ret = cli.send(new_req, new_res);
  2329. if (ret) { res = new_res; }
  2330. return ret;
  2331. }
  2332. inline std::string params_to_query_str(const Params &params) {
  2333. std::string query;
  2334. for (auto it = params.begin(); it != params.end(); ++it) {
  2335. if (it != params.begin()) { query += "&"; }
  2336. query += it->first;
  2337. query += "=";
  2338. query += encode_url(it->second);
  2339. }
  2340. return query;
  2341. }
  2342. inline void parse_query_text(const std::string &s, Params &params) {
  2343. split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
  2344. std::string key;
  2345. std::string val;
  2346. split(b, e, '=', [&](const char *b2, const char *e2) {
  2347. if (key.empty()) {
  2348. key.assign(b2, e2);
  2349. } else {
  2350. val.assign(b2, e2);
  2351. }
  2352. });
  2353. params.emplace(decode_url(key, true), decode_url(val, true));
  2354. });
  2355. }
  2356. inline bool parse_multipart_boundary(const std::string &content_type,
  2357. std::string &boundary) {
  2358. auto pos = content_type.find("boundary=");
  2359. if (pos == std::string::npos) { return false; }
  2360. boundary = content_type.substr(pos + 9);
  2361. if (boundary.length() >= 2 && boundary.front() == '"' &&
  2362. boundary.back() == '"') {
  2363. boundary = boundary.substr(1, boundary.size() - 2);
  2364. }
  2365. return !boundary.empty();
  2366. }
  2367. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  2368. static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  2369. std::smatch m;
  2370. if (std::regex_match(s, m, re_first_range)) {
  2371. auto pos = static_cast<size_t>(m.position(1));
  2372. auto len = static_cast<size_t>(m.length(1));
  2373. bool all_valid_ranges = true;
  2374. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  2375. if (!all_valid_ranges) return;
  2376. static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
  2377. std::cmatch cm;
  2378. if (std::regex_match(b, e, cm, re_another_range)) {
  2379. ssize_t first = -1;
  2380. if (!cm.str(1).empty()) {
  2381. first = static_cast<ssize_t>(std::stoll(cm.str(1)));
  2382. }
  2383. ssize_t last = -1;
  2384. if (!cm.str(2).empty()) {
  2385. last = static_cast<ssize_t>(std::stoll(cm.str(2)));
  2386. }
  2387. if (first != -1 && last != -1 && first > last) {
  2388. all_valid_ranges = false;
  2389. return;
  2390. }
  2391. ranges.emplace_back(std::make_pair(first, last));
  2392. }
  2393. });
  2394. return all_valid_ranges;
  2395. }
  2396. return false;
  2397. }
  2398. class MultipartFormDataParser {
  2399. public:
  2400. MultipartFormDataParser() = default;
  2401. void set_boundary(std::string &&boundary) { boundary_ = boundary; }
  2402. bool is_valid() const { return is_valid_; }
  2403. template <typename T, typename U>
  2404. bool parse(const char *buf, size_t n, T content_callback, U header_callback) {
  2405. static const std::regex re_content_type(R"(^Content-Type:\s*(.*?)\s*$)",
  2406. std::regex_constants::icase);
  2407. static const std::regex re_content_disposition(
  2408. "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
  2409. "\"(.*?)\")?\\s*$",
  2410. std::regex_constants::icase);
  2411. static const std::string dash_ = "--";
  2412. static const std::string crlf_ = "\r\n";
  2413. buf_.append(buf, n); // TODO: performance improvement
  2414. while (!buf_.empty()) {
  2415. switch (state_) {
  2416. case 0: { // Initial boundary
  2417. auto pattern = dash_ + boundary_ + crlf_;
  2418. if (pattern.size() > buf_.size()) { return true; }
  2419. auto pos = buf_.find(pattern);
  2420. if (pos != 0) { return false; }
  2421. buf_.erase(0, pattern.size());
  2422. off_ += pattern.size();
  2423. state_ = 1;
  2424. break;
  2425. }
  2426. case 1: { // New entry
  2427. clear_file_info();
  2428. state_ = 2;
  2429. break;
  2430. }
  2431. case 2: { // Headers
  2432. auto pos = buf_.find(crlf_);
  2433. while (pos != std::string::npos) {
  2434. // Empty line
  2435. if (pos == 0) {
  2436. if (!header_callback(file_)) {
  2437. is_valid_ = false;
  2438. return false;
  2439. }
  2440. buf_.erase(0, crlf_.size());
  2441. off_ += crlf_.size();
  2442. state_ = 3;
  2443. break;
  2444. }
  2445. auto header = buf_.substr(0, pos);
  2446. {
  2447. std::smatch m;
  2448. if (std::regex_match(header, m, re_content_type)) {
  2449. file_.content_type = m[1];
  2450. } else if (std::regex_match(header, m, re_content_disposition)) {
  2451. file_.name = m[1];
  2452. file_.filename = m[2];
  2453. }
  2454. }
  2455. buf_.erase(0, pos + crlf_.size());
  2456. off_ += pos + crlf_.size();
  2457. pos = buf_.find(crlf_);
  2458. }
  2459. if (state_ != 3) { return true; }
  2460. break;
  2461. }
  2462. case 3: { // Body
  2463. {
  2464. auto pattern = crlf_ + dash_;
  2465. if (pattern.size() > buf_.size()) { return true; }
  2466. auto pos = buf_.find(pattern);
  2467. if (pos == std::string::npos) {
  2468. pos = buf_.size();
  2469. while (pos > 0) {
  2470. auto c = buf_[pos - 1];
  2471. if (c != '\r' && c != '\n' && c != '-') { break; }
  2472. pos--;
  2473. }
  2474. }
  2475. if (!content_callback(buf_.data(), pos)) {
  2476. is_valid_ = false;
  2477. return false;
  2478. }
  2479. off_ += pos;
  2480. buf_.erase(0, pos);
  2481. }
  2482. {
  2483. auto pattern = crlf_ + dash_ + boundary_;
  2484. if (pattern.size() > buf_.size()) { return true; }
  2485. auto pos = buf_.find(pattern);
  2486. if (pos != std::string::npos) {
  2487. if (!content_callback(buf_.data(), pos)) {
  2488. is_valid_ = false;
  2489. return false;
  2490. }
  2491. off_ += pos + pattern.size();
  2492. buf_.erase(0, pos + pattern.size());
  2493. state_ = 4;
  2494. } else {
  2495. if (!content_callback(buf_.data(), pattern.size())) {
  2496. is_valid_ = false;
  2497. return false;
  2498. }
  2499. off_ += pattern.size();
  2500. buf_.erase(0, pattern.size());
  2501. }
  2502. }
  2503. break;
  2504. }
  2505. case 4: { // Boundary
  2506. if (crlf_.size() > buf_.size()) { return true; }
  2507. if (buf_.find(crlf_) == 0) {
  2508. buf_.erase(0, crlf_.size());
  2509. off_ += crlf_.size();
  2510. state_ = 1;
  2511. } else {
  2512. auto pattern = dash_ + crlf_;
  2513. if (pattern.size() > buf_.size()) { return true; }
  2514. if (buf_.find(pattern) == 0) {
  2515. buf_.erase(0, pattern.size());
  2516. off_ += pattern.size();
  2517. is_valid_ = true;
  2518. state_ = 5;
  2519. } else {
  2520. return true;
  2521. }
  2522. }
  2523. break;
  2524. }
  2525. case 5: { // Done
  2526. is_valid_ = false;
  2527. return false;
  2528. }
  2529. }
  2530. }
  2531. return true;
  2532. }
  2533. private:
  2534. void clear_file_info() {
  2535. file_.name.clear();
  2536. file_.filename.clear();
  2537. file_.content_type.clear();
  2538. }
  2539. std::string boundary_;
  2540. std::string buf_;
  2541. size_t state_ = 0;
  2542. bool is_valid_ = false;
  2543. size_t off_ = 0;
  2544. MultipartFormData file_;
  2545. };
  2546. inline std::string to_lower(const char *beg, const char *end) {
  2547. std::string out;
  2548. auto it = beg;
  2549. while (it != end) {
  2550. out += static_cast<char>(::tolower(*it));
  2551. it++;
  2552. }
  2553. return out;
  2554. }
  2555. inline std::string make_multipart_data_boundary() {
  2556. static const char data[] =
  2557. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2558. std::random_device seed_gen;
  2559. std::mt19937 engine(seed_gen());
  2560. std::string result = "--cpp-httplib-multipart-data-";
  2561. for (auto i = 0; i < 16; i++) {
  2562. result += data[engine() % (sizeof(data) - 1)];
  2563. }
  2564. return result;
  2565. }
  2566. inline std::pair<size_t, size_t>
  2567. get_range_offset_and_length(const Request &req, size_t content_length,
  2568. size_t index) {
  2569. auto r = req.ranges[index];
  2570. if (r.first == -1 && r.second == -1) {
  2571. return std::make_pair(0, content_length);
  2572. }
  2573. auto slen = static_cast<ssize_t>(content_length);
  2574. if (r.first == -1) {
  2575. r.first = slen - r.second;
  2576. r.second = slen - 1;
  2577. }
  2578. if (r.second == -1) { r.second = slen - 1; }
  2579. return std::make_pair(r.first, r.second - r.first + 1);
  2580. }
  2581. inline std::string make_content_range_header_field(size_t offset, size_t length,
  2582. size_t content_length) {
  2583. std::string field = "bytes ";
  2584. field += std::to_string(offset);
  2585. field += "-";
  2586. field += std::to_string(offset + length - 1);
  2587. field += "/";
  2588. field += std::to_string(content_length);
  2589. return field;
  2590. }
  2591. template <typename SToken, typename CToken, typename Content>
  2592. bool process_multipart_ranges_data(const Request &req, Response &res,
  2593. const std::string &boundary,
  2594. const std::string &content_type,
  2595. SToken stoken, CToken ctoken,
  2596. Content content) {
  2597. for (size_t i = 0; i < req.ranges.size(); i++) {
  2598. ctoken("--");
  2599. stoken(boundary);
  2600. ctoken("\r\n");
  2601. if (!content_type.empty()) {
  2602. ctoken("Content-Type: ");
  2603. stoken(content_type);
  2604. ctoken("\r\n");
  2605. }
  2606. auto offsets = get_range_offset_and_length(req, res.body.size(), i);
  2607. auto offset = offsets.first;
  2608. auto length = offsets.second;
  2609. ctoken("Content-Range: ");
  2610. stoken(make_content_range_header_field(offset, length, res.body.size()));
  2611. ctoken("\r\n");
  2612. ctoken("\r\n");
  2613. if (!content(offset, length)) { return false; }
  2614. ctoken("\r\n");
  2615. }
  2616. ctoken("--");
  2617. stoken(boundary);
  2618. ctoken("--\r\n");
  2619. return true;
  2620. }
  2621. inline std::string make_multipart_ranges_data(const Request &req, Response &res,
  2622. const std::string &boundary,
  2623. const std::string &content_type) {
  2624. std::string data;
  2625. process_multipart_ranges_data(
  2626. req, res, boundary, content_type,
  2627. [&](const std::string &token) { data += token; },
  2628. [&](const char *token) { data += token; },
  2629. [&](size_t offset, size_t length) {
  2630. data += res.body.substr(offset, length);
  2631. return true;
  2632. });
  2633. return data;
  2634. }
  2635. inline size_t
  2636. get_multipart_ranges_data_length(const Request &req, Response &res,
  2637. const std::string &boundary,
  2638. const std::string &content_type) {
  2639. size_t data_length = 0;
  2640. process_multipart_ranges_data(
  2641. req, res, boundary, content_type,
  2642. [&](const std::string &token) { data_length += token.size(); },
  2643. [&](const char *token) { data_length += strlen(token); },
  2644. [&](size_t /*offset*/, size_t length) {
  2645. data_length += length;
  2646. return true;
  2647. });
  2648. return data_length;
  2649. }
  2650. template <typename T>
  2651. inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
  2652. Response &res,
  2653. const std::string &boundary,
  2654. const std::string &content_type,
  2655. T is_shutting_down) {
  2656. return process_multipart_ranges_data(
  2657. req, res, boundary, content_type,
  2658. [&](const std::string &token) { strm.write(token); },
  2659. [&](const char *token) { strm.write(token); },
  2660. [&](size_t offset, size_t length) {
  2661. return write_content(strm, res.content_provider_, offset, length,
  2662. is_shutting_down) >= 0;
  2663. });
  2664. }
  2665. inline std::pair<size_t, size_t>
  2666. get_range_offset_and_length(const Request &req, const Response &res,
  2667. size_t index) {
  2668. auto r = req.ranges[index];
  2669. if (r.second == -1) {
  2670. r.second = static_cast<ssize_t>(res.content_length_) - 1;
  2671. }
  2672. return std::make_pair(r.first, r.second - r.first + 1);
  2673. }
  2674. inline bool expect_content(const Request &req) {
  2675. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  2676. req.method == "PRI" || req.method == "DELETE") {
  2677. return true;
  2678. }
  2679. // TODO: check if Content-Length is set
  2680. return false;
  2681. }
  2682. inline bool has_crlf(const char *s) {
  2683. auto p = s;
  2684. while (*p) {
  2685. if (*p == '\r' || *p == '\n') { return true; }
  2686. p++;
  2687. }
  2688. return false;
  2689. }
  2690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2691. template <typename CTX, typename Init, typename Update, typename Final>
  2692. inline std::string message_digest(const std::string &s, Init init,
  2693. Update update, Final final,
  2694. size_t digest_length) {
  2695. using namespace std;
  2696. std::vector<unsigned char> md(digest_length, 0);
  2697. CTX ctx;
  2698. init(&ctx);
  2699. update(&ctx, s.data(), s.size());
  2700. final(md.data(), &ctx);
  2701. stringstream ss;
  2702. for (auto c : md) {
  2703. ss << setfill('0') << setw(2) << hex << (unsigned int)c;
  2704. }
  2705. return ss.str();
  2706. }
  2707. inline std::string MD5(const std::string &s) {
  2708. return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
  2709. MD5_DIGEST_LENGTH);
  2710. }
  2711. inline std::string SHA_256(const std::string &s) {
  2712. return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
  2713. SHA256_DIGEST_LENGTH);
  2714. }
  2715. inline std::string SHA_512(const std::string &s) {
  2716. return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
  2717. SHA512_DIGEST_LENGTH);
  2718. }
  2719. #endif
  2720. #ifdef _WIN32
  2721. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2722. // NOTE: This code came up with the following stackoverflow post:
  2723. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  2724. inline bool load_system_certs_on_windows(X509_STORE *store) {
  2725. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  2726. if (!hStore) { return false; }
  2727. PCCERT_CONTEXT pContext = NULL;
  2728. while (pContext = CertEnumCertificatesInStore(hStore, pContext)) {
  2729. auto encoded_cert =
  2730. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  2731. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  2732. if (x509) {
  2733. X509_STORE_add_cert(store, x509);
  2734. X509_free(x509);
  2735. }
  2736. }
  2737. CertFreeCertificateContext(pContext);
  2738. CertCloseStore(hStore, 0);
  2739. return true;
  2740. }
  2741. #endif
  2742. class WSInit {
  2743. public:
  2744. WSInit() {
  2745. WSADATA wsaData;
  2746. WSAStartup(0x0002, &wsaData);
  2747. }
  2748. ~WSInit() { WSACleanup(); }
  2749. };
  2750. static WSInit wsinit_;
  2751. #endif
  2752. } // namespace detail
  2753. // Header utilities
  2754. inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
  2755. std::string field = "bytes=";
  2756. auto i = 0;
  2757. for (auto r : ranges) {
  2758. if (i != 0) { field += ", "; }
  2759. if (r.first != -1) { field += std::to_string(r.first); }
  2760. field += '-';
  2761. if (r.second != -1) { field += std::to_string(r.second); }
  2762. i++;
  2763. }
  2764. return std::make_pair("Range", field);
  2765. }
  2766. inline std::pair<std::string, std::string>
  2767. make_basic_authentication_header(const std::string &username,
  2768. const std::string &password,
  2769. bool is_proxy = false) {
  2770. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  2771. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2772. return std::make_pair(key, field);
  2773. }
  2774. inline std::pair<std::string, std::string>
  2775. make_bearer_token_authentication_header(const std::string &token,
  2776. bool is_proxy = false) {
  2777. auto field = "Bearer " + token;
  2778. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2779. return std::make_pair(key, field);
  2780. }
  2781. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2782. inline std::pair<std::string, std::string> make_digest_authentication_header(
  2783. const Request &req, const std::map<std::string, std::string> &auth,
  2784. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  2785. const std::string &password, bool is_proxy = false) {
  2786. using namespace std;
  2787. string nc;
  2788. {
  2789. stringstream ss;
  2790. ss << setfill('0') << setw(8) << hex << cnonce_count;
  2791. nc = ss.str();
  2792. }
  2793. auto qop = auth.at("qop");
  2794. if (qop.find("auth-int") != std::string::npos) {
  2795. qop = "auth-int";
  2796. } else {
  2797. qop = "auth";
  2798. }
  2799. std::string algo = "MD5";
  2800. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  2801. string response;
  2802. {
  2803. auto H = algo == "SHA-256"
  2804. ? detail::SHA_256
  2805. : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
  2806. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  2807. auto A2 = req.method + ":" + req.path;
  2808. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  2809. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  2810. ":" + qop + ":" + H(A2));
  2811. }
  2812. auto field = "Digest username=\"" + username + "\", realm=\"" +
  2813. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  2814. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  2815. ", qop=" + qop + ", nc=\"" + nc + "\", cnonce=\"" + cnonce +
  2816. "\", response=\"" + response + "\"";
  2817. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2818. return std::make_pair(key, field);
  2819. }
  2820. #endif
  2821. inline bool parse_www_authenticate(const Response &res,
  2822. std::map<std::string, std::string> &auth,
  2823. bool is_proxy) {
  2824. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  2825. if (res.has_header(auth_key)) {
  2826. static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  2827. auto s = res.get_header_value(auth_key);
  2828. auto pos = s.find(' ');
  2829. if (pos != std::string::npos) {
  2830. auto type = s.substr(0, pos);
  2831. if (type == "Basic") {
  2832. return false;
  2833. } else if (type == "Digest") {
  2834. s = s.substr(pos + 1);
  2835. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  2836. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  2837. auto m = *i;
  2838. auto key = s.substr(static_cast<size_t>(m.position(1)),
  2839. static_cast<size_t>(m.length(1)));
  2840. auto val = m.length(2) > 0
  2841. ? s.substr(static_cast<size_t>(m.position(2)),
  2842. static_cast<size_t>(m.length(2)))
  2843. : s.substr(static_cast<size_t>(m.position(3)),
  2844. static_cast<size_t>(m.length(3)));
  2845. auth[key] = val;
  2846. }
  2847. return true;
  2848. }
  2849. }
  2850. }
  2851. return false;
  2852. }
  2853. // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
  2854. inline std::string random_string(size_t length) {
  2855. auto randchar = []() -> char {
  2856. const char charset[] = "0123456789"
  2857. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2858. "abcdefghijklmnopqrstuvwxyz";
  2859. const size_t max_index = (sizeof(charset) - 1);
  2860. return charset[static_cast<size_t>(rand()) % max_index];
  2861. };
  2862. std::string str(length, 0);
  2863. std::generate_n(str.begin(), length, randchar);
  2864. return str;
  2865. }
  2866. // Request implementation
  2867. inline bool Request::has_header(const char *key) const {
  2868. return detail::has_header(headers, key);
  2869. }
  2870. inline std::string Request::get_header_value(const char *key, size_t id) const {
  2871. return detail::get_header_value(headers, key, id, "");
  2872. }
  2873. template <typename T>
  2874. inline T Request::get_header_value(const char *key, size_t id) const {
  2875. return detail::get_header_value<T>(headers, key, id, 0);
  2876. }
  2877. inline size_t Request::get_header_value_count(const char *key) const {
  2878. auto r = headers.equal_range(key);
  2879. return static_cast<size_t>(std::distance(r.first, r.second));
  2880. }
  2881. inline void Request::set_header(const char *key, const char *val) {
  2882. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  2883. headers.emplace(key, val);
  2884. }
  2885. }
  2886. inline void Request::set_header(const char *key, const std::string &val) {
  2887. if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
  2888. headers.emplace(key, val);
  2889. }
  2890. }
  2891. inline bool Request::has_param(const char *key) const {
  2892. return params.find(key) != params.end();
  2893. }
  2894. inline std::string Request::get_param_value(const char *key, size_t id) const {
  2895. auto rng = params.equal_range(key);
  2896. auto it = rng.first;
  2897. std::advance(it, static_cast<ssize_t>(id));
  2898. if (it != rng.second) { return it->second; }
  2899. return std::string();
  2900. }
  2901. inline size_t Request::get_param_value_count(const char *key) const {
  2902. auto r = params.equal_range(key);
  2903. return static_cast<size_t>(std::distance(r.first, r.second));
  2904. }
  2905. inline bool Request::is_multipart_form_data() const {
  2906. const auto &content_type = get_header_value("Content-Type");
  2907. return !content_type.find("multipart/form-data");
  2908. }
  2909. inline bool Request::has_file(const char *key) const {
  2910. return files.find(key) != files.end();
  2911. }
  2912. inline MultipartFormData Request::get_file_value(const char *key) const {
  2913. auto it = files.find(key);
  2914. if (it != files.end()) { return it->second; }
  2915. return MultipartFormData();
  2916. }
  2917. // Response implementation
  2918. inline bool Response::has_header(const char *key) const {
  2919. return headers.find(key) != headers.end();
  2920. }
  2921. inline std::string Response::get_header_value(const char *key,
  2922. size_t id) const {
  2923. return detail::get_header_value(headers, key, id, "");
  2924. }
  2925. template <typename T>
  2926. inline T Response::get_header_value(const char *key, size_t id) const {
  2927. return detail::get_header_value<T>(headers, key, id, 0);
  2928. }
  2929. inline size_t Response::get_header_value_count(const char *key) const {
  2930. auto r = headers.equal_range(key);
  2931. return static_cast<size_t>(std::distance(r.first, r.second));
  2932. }
  2933. inline void Response::set_header(const char *key, const char *val) {
  2934. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  2935. headers.emplace(key, val);
  2936. }
  2937. }
  2938. inline void Response::set_header(const char *key, const std::string &val) {
  2939. if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
  2940. headers.emplace(key, val);
  2941. }
  2942. }
  2943. inline void Response::set_redirect(const char *url, int stat) {
  2944. if (!detail::has_crlf(url)) {
  2945. set_header("Location", url);
  2946. if (300 <= stat && stat < 400) {
  2947. this->status = stat;
  2948. } else {
  2949. this->status = 302;
  2950. }
  2951. }
  2952. }
  2953. inline void Response::set_redirect(const std::string &url, int stat) {
  2954. set_redirect(url.c_str(), stat);
  2955. }
  2956. inline void Response::set_content(const char *s, size_t n,
  2957. const char *content_type) {
  2958. body.assign(s, n);
  2959. set_header("Content-Type", content_type);
  2960. }
  2961. inline void Response::set_content(std::string s, const char *content_type) {
  2962. body = std::move(s);
  2963. set_header("Content-Type", content_type);
  2964. }
  2965. inline void
  2966. Response::set_content_provider(size_t in_length, const char *content_type,
  2967. ContentProvider provider,
  2968. std::function<void()> resource_releaser) {
  2969. assert(in_length > 0);
  2970. set_header("Content-Type", content_type);
  2971. content_length_ = in_length;
  2972. content_provider_ = [provider](size_t offset, size_t length, DataSink &sink) {
  2973. return provider(offset, length, sink);
  2974. };
  2975. content_provider_resource_releaser_ = resource_releaser;
  2976. is_chunked_content_provider = false;
  2977. }
  2978. inline void Response::set_content_provider(
  2979. const char *content_type, ContentProviderWithoutLength provider,
  2980. std::function<void()> resource_releaser) {
  2981. set_header("Content-Type", content_type);
  2982. content_length_ = 0;
  2983. content_provider_ = [provider](size_t offset, size_t, DataSink &sink) {
  2984. return provider(offset, sink);
  2985. };
  2986. content_provider_resource_releaser_ = resource_releaser;
  2987. is_chunked_content_provider = false;
  2988. }
  2989. inline void Response::set_chunked_content_provider(
  2990. const char *content_type, ContentProviderWithoutLength provider,
  2991. std::function<void()> resource_releaser) {
  2992. set_header("Content-Type", content_type);
  2993. content_length_ = 0;
  2994. content_provider_ = [provider](size_t offset, size_t, DataSink &sink) {
  2995. return provider(offset, sink);
  2996. };
  2997. content_provider_resource_releaser_ = resource_releaser;
  2998. is_chunked_content_provider = true;
  2999. }
  3000. // Rstream implementation
  3001. inline ssize_t Stream::write(const char *ptr) {
  3002. return write(ptr, strlen(ptr));
  3003. }
  3004. inline ssize_t Stream::write(const std::string &s) {
  3005. return write(s.data(), s.size());
  3006. }
  3007. template <typename... Args>
  3008. inline ssize_t Stream::write_format(const char *fmt, const Args &... args) {
  3009. const auto bufsiz = 2048;
  3010. std::array<char, bufsiz> buf;
  3011. #if defined(_MSC_VER) && _MSC_VER < 1900
  3012. auto sn = _snprintf_s(buf.data(), bufsiz - 1, buf.size() - 1, fmt, args...);
  3013. #else
  3014. auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...);
  3015. #endif
  3016. if (sn <= 0) { return sn; }
  3017. auto n = static_cast<size_t>(sn);
  3018. if (n >= buf.size() - 1) {
  3019. std::vector<char> glowable_buf(buf.size());
  3020. while (n >= glowable_buf.size() - 1) {
  3021. glowable_buf.resize(glowable_buf.size() * 2);
  3022. #if defined(_MSC_VER) && _MSC_VER < 1900
  3023. n = static_cast<size_t>(_snprintf_s(&glowable_buf[0], glowable_buf.size(),
  3024. glowable_buf.size() - 1, fmt,
  3025. args...));
  3026. #else
  3027. n = static_cast<size_t>(
  3028. snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...));
  3029. #endif
  3030. }
  3031. return write(&glowable_buf[0], n);
  3032. } else {
  3033. return write(buf.data(), n);
  3034. }
  3035. }
  3036. namespace detail {
  3037. // Socket stream implementation
  3038. inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
  3039. time_t read_timeout_usec,
  3040. time_t write_timeout_sec,
  3041. time_t write_timeout_usec)
  3042. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  3043. read_timeout_usec_(read_timeout_usec),
  3044. write_timeout_sec_(write_timeout_sec),
  3045. write_timeout_usec_(write_timeout_usec) {}
  3046. inline SocketStream::~SocketStream() {}
  3047. inline bool SocketStream::is_readable() const {
  3048. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  3049. }
  3050. inline bool SocketStream::is_writable() const {
  3051. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  3052. }
  3053. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  3054. if (!is_readable()) { return -1; }
  3055. #ifdef _WIN32
  3056. if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
  3057. return -1;
  3058. }
  3059. return recv(sock_, ptr, static_cast<int>(size), 0);
  3060. #else
  3061. return handle_EINTR([&]() { return recv(sock_, ptr, size, 0); });
  3062. #endif
  3063. }
  3064. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  3065. if (!is_writable()) { return -1; }
  3066. #ifdef _WIN32
  3067. if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
  3068. return -1;
  3069. }
  3070. return send(sock_, ptr, static_cast<int>(size), 0);
  3071. #else
  3072. return handle_EINTR([&]() { return send(sock_, ptr, size, 0); });
  3073. #endif
  3074. }
  3075. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  3076. int &port) const {
  3077. return detail::get_remote_ip_and_port(sock_, ip, port);
  3078. }
  3079. // Buffer stream implementation
  3080. inline bool BufferStream::is_readable() const { return true; }
  3081. inline bool BufferStream::is_writable() const { return true; }
  3082. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  3083. #if defined(_MSC_VER) && _MSC_VER <= 1900
  3084. auto len_read = buffer._Copy_s(ptr, size, size, position);
  3085. #else
  3086. auto len_read = buffer.copy(ptr, size, position);
  3087. #endif
  3088. position += static_cast<size_t>(len_read);
  3089. return static_cast<ssize_t>(len_read);
  3090. }
  3091. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  3092. buffer.append(ptr, size);
  3093. return static_cast<ssize_t>(size);
  3094. }
  3095. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  3096. int & /*port*/) const {}
  3097. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  3098. } // namespace detail
  3099. // HTTP server implementation
  3100. inline Server::Server() : svr_sock_(INVALID_SOCKET), is_running_(false) {
  3101. #ifndef _WIN32
  3102. signal(SIGPIPE, SIG_IGN);
  3103. #endif
  3104. new_task_queue = [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); };
  3105. }
  3106. inline Server::~Server() {}
  3107. inline Server &Server::Get(const char *pattern, Handler handler) {
  3108. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3109. return *this;
  3110. }
  3111. inline Server &Server::Post(const char *pattern, Handler handler) {
  3112. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3113. return *this;
  3114. }
  3115. inline Server &Server::Post(const char *pattern,
  3116. HandlerWithContentReader handler) {
  3117. post_handlers_for_content_reader_.push_back(
  3118. std::make_pair(std::regex(pattern), handler));
  3119. return *this;
  3120. }
  3121. inline Server &Server::Put(const char *pattern, Handler handler) {
  3122. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3123. return *this;
  3124. }
  3125. inline Server &Server::Put(const char *pattern,
  3126. HandlerWithContentReader handler) {
  3127. put_handlers_for_content_reader_.push_back(
  3128. std::make_pair(std::regex(pattern), handler));
  3129. return *this;
  3130. }
  3131. inline Server &Server::Patch(const char *pattern, Handler handler) {
  3132. patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3133. return *this;
  3134. }
  3135. inline Server &Server::Patch(const char *pattern,
  3136. HandlerWithContentReader handler) {
  3137. patch_handlers_for_content_reader_.push_back(
  3138. std::make_pair(std::regex(pattern), handler));
  3139. return *this;
  3140. }
  3141. inline Server &Server::Delete(const char *pattern, Handler handler) {
  3142. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3143. return *this;
  3144. }
  3145. inline Server &Server::Delete(const char *pattern,
  3146. HandlerWithContentReader handler) {
  3147. delete_handlers_for_content_reader_.push_back(
  3148. std::make_pair(std::regex(pattern), handler));
  3149. return *this;
  3150. }
  3151. inline Server &Server::Options(const char *pattern, Handler handler) {
  3152. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3153. return *this;
  3154. }
  3155. inline bool Server::set_base_dir(const char *dir, const char *mount_point) {
  3156. return set_mount_point(mount_point, dir);
  3157. }
  3158. inline bool Server::set_mount_point(const char *mount_point, const char *dir) {
  3159. if (detail::is_dir(dir)) {
  3160. std::string mnt = mount_point ? mount_point : "/";
  3161. if (!mnt.empty() && mnt[0] == '/') {
  3162. base_dirs_.emplace_back(mnt, dir);
  3163. return true;
  3164. }
  3165. }
  3166. return false;
  3167. }
  3168. inline bool Server::remove_mount_point(const char *mount_point) {
  3169. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  3170. if (it->first == mount_point) {
  3171. base_dirs_.erase(it);
  3172. return true;
  3173. }
  3174. }
  3175. return false;
  3176. }
  3177. inline void Server::set_file_extension_and_mimetype_mapping(const char *ext,
  3178. const char *mime) {
  3179. file_extension_and_mimetype_map_[ext] = mime;
  3180. }
  3181. inline void Server::set_file_request_handler(Handler handler) {
  3182. file_request_handler_ = std::move(handler);
  3183. }
  3184. inline void Server::set_error_handler(Handler handler) {
  3185. error_handler_ = std::move(handler);
  3186. }
  3187. inline void Server::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  3188. inline void Server::set_socket_options(SocketOptions socket_options) {
  3189. socket_options_ = socket_options;
  3190. }
  3191. inline void Server::set_logger(Logger logger) { logger_ = std::move(logger); }
  3192. inline void
  3193. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  3194. expect_100_continue_handler_ = std::move(handler);
  3195. }
  3196. inline void Server::set_keep_alive_max_count(size_t count) {
  3197. keep_alive_max_count_ = count;
  3198. }
  3199. inline void Server::set_read_timeout(time_t sec, time_t usec) {
  3200. read_timeout_sec_ = sec;
  3201. read_timeout_usec_ = usec;
  3202. }
  3203. inline void Server::set_write_timeout(time_t sec, time_t usec) {
  3204. write_timeout_sec_ = sec;
  3205. write_timeout_usec_ = usec;
  3206. }
  3207. inline void Server::set_idle_interval(time_t sec, time_t usec) {
  3208. idle_interval_sec_ = sec;
  3209. idle_interval_usec_ = usec;
  3210. }
  3211. inline void Server::set_payload_max_length(size_t length) {
  3212. payload_max_length_ = length;
  3213. }
  3214. inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
  3215. if (bind_internal(host, port, socket_flags) < 0) return false;
  3216. return true;
  3217. }
  3218. inline int Server::bind_to_any_port(const char *host, int socket_flags) {
  3219. return bind_internal(host, 0, socket_flags);
  3220. }
  3221. inline bool Server::listen_after_bind() { return listen_internal(); }
  3222. inline bool Server::listen(const char *host, int port, int socket_flags) {
  3223. return bind_to_port(host, port, socket_flags) && listen_internal();
  3224. }
  3225. inline bool Server::is_running() const { return is_running_; }
  3226. inline void Server::stop() {
  3227. if (is_running_) {
  3228. assert(svr_sock_ != INVALID_SOCKET);
  3229. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  3230. detail::shutdown_socket(sock);
  3231. detail::close_socket(sock);
  3232. }
  3233. }
  3234. inline bool Server::parse_request_line(const char *s, Request &req) {
  3235. const static std::regex re(
  3236. "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) "
  3237. "(([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])\r\n");
  3238. std::cmatch m;
  3239. if (std::regex_match(s, m, re)) {
  3240. req.version = std::string(m[5]);
  3241. req.method = std::string(m[1]);
  3242. req.target = std::string(m[2]);
  3243. req.path = detail::decode_url(m[3], false);
  3244. // Parse query text
  3245. auto len = std::distance(m[4].first, m[4].second);
  3246. if (len > 0) { detail::parse_query_text(m[4], req.params); }
  3247. return true;
  3248. }
  3249. return false;
  3250. }
  3251. inline bool Server::write_response(Stream &strm, bool close_connection,
  3252. const Request &req, Response &res) {
  3253. assert(res.status != -1);
  3254. if (400 <= res.status && error_handler_) { error_handler_(req, res); }
  3255. detail::BufferStream bstrm;
  3256. // Response line
  3257. if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  3258. detail::status_message(res.status))) {
  3259. return false;
  3260. }
  3261. // Headers
  3262. if (close_connection || req.get_header_value("Connection") == "close") {
  3263. res.set_header("Connection", "close");
  3264. }
  3265. if (!close_connection && req.get_header_value("Connection") == "Keep-Alive") {
  3266. res.set_header("Connection", "Keep-Alive");
  3267. }
  3268. if (!res.has_header("Content-Type") &&
  3269. (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) {
  3270. res.set_header("Content-Type", "text/plain");
  3271. }
  3272. if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
  3273. res.set_header("Accept-Ranges", "bytes");
  3274. }
  3275. std::string content_type;
  3276. std::string boundary;
  3277. if (req.ranges.size() > 1) {
  3278. boundary = detail::make_multipart_data_boundary();
  3279. auto it = res.headers.find("Content-Type");
  3280. if (it != res.headers.end()) {
  3281. content_type = it->second;
  3282. res.headers.erase(it);
  3283. }
  3284. res.headers.emplace("Content-Type",
  3285. "multipart/byteranges; boundary=" + boundary);
  3286. }
  3287. auto type = detail::encoding_type(req, res);
  3288. if (res.body.empty()) {
  3289. if (res.content_length_ > 0) {
  3290. size_t length = 0;
  3291. if (req.ranges.empty()) {
  3292. length = res.content_length_;
  3293. } else if (req.ranges.size() == 1) {
  3294. auto offsets =
  3295. detail::get_range_offset_and_length(req, res.content_length_, 0);
  3296. auto offset = offsets.first;
  3297. length = offsets.second;
  3298. auto content_range = detail::make_content_range_header_field(
  3299. offset, length, res.content_length_);
  3300. res.set_header("Content-Range", content_range);
  3301. } else {
  3302. length = detail::get_multipart_ranges_data_length(req, res, boundary,
  3303. content_type);
  3304. }
  3305. res.set_header("Content-Length", std::to_string(length));
  3306. } else {
  3307. if (res.content_provider_) {
  3308. if (res.is_chunked_content_provider) {
  3309. res.set_header("Transfer-Encoding", "chunked");
  3310. if (type == detail::EncodingType::Gzip) {
  3311. res.set_header("Content-Encoding", "gzip");
  3312. } else if (type == detail::EncodingType::Brotli) {
  3313. res.set_header("Content-Encoding", "br");
  3314. }
  3315. }
  3316. } else {
  3317. res.set_header("Content-Length", "0");
  3318. }
  3319. }
  3320. } else {
  3321. if (req.ranges.empty()) {
  3322. ;
  3323. } else if (req.ranges.size() == 1) {
  3324. auto offsets =
  3325. detail::get_range_offset_and_length(req, res.body.size(), 0);
  3326. auto offset = offsets.first;
  3327. auto length = offsets.second;
  3328. auto content_range = detail::make_content_range_header_field(
  3329. offset, length, res.body.size());
  3330. res.set_header("Content-Range", content_range);
  3331. res.body = res.body.substr(offset, length);
  3332. } else {
  3333. res.body =
  3334. detail::make_multipart_ranges_data(req, res, boundary, content_type);
  3335. }
  3336. if (type != detail::EncodingType::None) {
  3337. std::shared_ptr<detail::compressor> compressor;
  3338. if (type == detail::EncodingType::Gzip) {
  3339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3340. compressor = std::make_shared<detail::gzip_compressor>();
  3341. res.set_header("Content-Encoding", "gzip");
  3342. #endif
  3343. } else if (type == detail::EncodingType::Brotli) {
  3344. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3345. compressor = std::make_shared<detail::brotli_compressor>();
  3346. res.set_header("Content-Encoding", "brotli");
  3347. #endif
  3348. }
  3349. if (compressor) {
  3350. std::string compressed;
  3351. if (!compressor->compress(res.body.data(), res.body.size(), true,
  3352. [&](const char *data, size_t data_len) {
  3353. compressed.append(data, data_len);
  3354. return true;
  3355. })) {
  3356. return false;
  3357. }
  3358. res.body.swap(compressed);
  3359. }
  3360. }
  3361. auto length = std::to_string(res.body.size());
  3362. res.set_header("Content-Length", length);
  3363. }
  3364. if (!detail::write_headers(bstrm, res, Headers())) { return false; }
  3365. // Flush buffer
  3366. auto &data = bstrm.get_buffer();
  3367. strm.write(data.data(), data.size());
  3368. // Body
  3369. auto ret = true;
  3370. if (req.method != "HEAD") {
  3371. if (!res.body.empty()) {
  3372. if (!strm.write(res.body)) { ret = false; }
  3373. } else if (res.content_provider_) {
  3374. if (!write_content_with_provider(strm, req, res, boundary,
  3375. content_type)) {
  3376. ret = false;
  3377. }
  3378. }
  3379. }
  3380. // Log
  3381. if (logger_) { logger_(req, res); }
  3382. return ret;
  3383. }
  3384. inline bool
  3385. Server::write_content_with_provider(Stream &strm, const Request &req,
  3386. Response &res, const std::string &boundary,
  3387. const std::string &content_type) {
  3388. auto is_shutting_down = [this]() {
  3389. return this->svr_sock_ == INVALID_SOCKET;
  3390. };
  3391. if (res.content_length_ > 0) {
  3392. if (req.ranges.empty()) {
  3393. if (detail::write_content(strm, res.content_provider_, 0,
  3394. res.content_length_, is_shutting_down) < 0) {
  3395. return false;
  3396. }
  3397. } else if (req.ranges.size() == 1) {
  3398. auto offsets =
  3399. detail::get_range_offset_and_length(req, res.content_length_, 0);
  3400. auto offset = offsets.first;
  3401. auto length = offsets.second;
  3402. if (detail::write_content(strm, res.content_provider_, offset, length,
  3403. is_shutting_down) < 0) {
  3404. return false;
  3405. }
  3406. } else {
  3407. if (!detail::write_multipart_ranges_data(
  3408. strm, req, res, boundary, content_type, is_shutting_down)) {
  3409. return false;
  3410. }
  3411. }
  3412. } else {
  3413. if (res.is_chunked_content_provider) {
  3414. auto type = detail::encoding_type(req, res);
  3415. std::shared_ptr<detail::compressor> compressor;
  3416. if (type == detail::EncodingType::Gzip) {
  3417. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3418. compressor = std::make_shared<detail::gzip_compressor>();
  3419. #endif
  3420. } else if (type == detail::EncodingType::Brotli) {
  3421. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3422. compressor = std::make_shared<detail::brotli_compressor>();
  3423. #endif
  3424. } else {
  3425. compressor = std::make_shared<detail::nocompressor>();
  3426. }
  3427. assert(compressor != nullptr);
  3428. if (detail::write_content_chunked(strm, res.content_provider_,
  3429. is_shutting_down, *compressor) < 0) {
  3430. return false;
  3431. }
  3432. } else {
  3433. if (detail::write_content_without_length(strm, res.content_provider_,
  3434. is_shutting_down) < 0) {
  3435. return false;
  3436. }
  3437. }
  3438. }
  3439. return true;
  3440. }
  3441. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  3442. MultipartFormDataMap::iterator cur;
  3443. if (read_content_core(
  3444. strm, req, res,
  3445. // Regular
  3446. [&](const char *buf, size_t n) {
  3447. if (req.body.size() + n > req.body.max_size()) { return false; }
  3448. req.body.append(buf, n);
  3449. return true;
  3450. },
  3451. // Multipart
  3452. [&](const MultipartFormData &file) {
  3453. cur = req.files.emplace(file.name, file);
  3454. return true;
  3455. },
  3456. [&](const char *buf, size_t n) {
  3457. auto &content = cur->second.content;
  3458. if (content.size() + n > content.max_size()) { return false; }
  3459. content.append(buf, n);
  3460. return true;
  3461. })) {
  3462. const auto &content_type = req.get_header_value("Content-Type");
  3463. if (!content_type.find("application/x-www-form-urlencoded")) {
  3464. detail::parse_query_text(req.body, req.params);
  3465. }
  3466. return true;
  3467. }
  3468. return false;
  3469. }
  3470. inline bool Server::read_content_with_content_receiver(
  3471. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  3472. MultipartContentHeader multipart_header,
  3473. ContentReceiver multipart_receiver) {
  3474. return read_content_core(strm, req, res, receiver, multipart_header,
  3475. multipart_receiver);
  3476. }
  3477. inline bool Server::read_content_core(Stream &strm, Request &req, Response &res,
  3478. ContentReceiver receiver,
  3479. MultipartContentHeader mulitpart_header,
  3480. ContentReceiver multipart_receiver) {
  3481. detail::MultipartFormDataParser multipart_form_data_parser;
  3482. ContentReceiver out;
  3483. if (req.is_multipart_form_data()) {
  3484. const auto &content_type = req.get_header_value("Content-Type");
  3485. std::string boundary;
  3486. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  3487. res.status = 400;
  3488. return false;
  3489. }
  3490. multipart_form_data_parser.set_boundary(std::move(boundary));
  3491. out = [&](const char *buf, size_t n) {
  3492. /* For debug
  3493. size_t pos = 0;
  3494. while (pos < n) {
  3495. auto read_size = std::min<size_t>(1, n - pos);
  3496. auto ret = multipart_form_data_parser.parse(
  3497. buf + pos, read_size, multipart_receiver, mulitpart_header);
  3498. if (!ret) { return false; }
  3499. pos += read_size;
  3500. }
  3501. return true;
  3502. */
  3503. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  3504. mulitpart_header);
  3505. };
  3506. } else {
  3507. out = receiver;
  3508. }
  3509. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  3510. return true;
  3511. }
  3512. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  3513. out, true)) {
  3514. return false;
  3515. }
  3516. if (req.is_multipart_form_data()) {
  3517. if (!multipart_form_data_parser.is_valid()) {
  3518. res.status = 400;
  3519. return false;
  3520. }
  3521. }
  3522. return true;
  3523. }
  3524. inline bool Server::handle_file_request(Request &req, Response &res,
  3525. bool head) {
  3526. for (const auto &kv : base_dirs_) {
  3527. const auto &mount_point = kv.first;
  3528. const auto &base_dir = kv.second;
  3529. // Prefix match
  3530. if (!req.path.find(mount_point)) {
  3531. std::string sub_path = "/" + req.path.substr(mount_point.size());
  3532. if (detail::is_valid_path(sub_path)) {
  3533. auto path = base_dir + sub_path;
  3534. if (path.back() == '/') { path += "index.html"; }
  3535. if (detail::is_file(path)) {
  3536. detail::read_file(path, res.body);
  3537. auto type =
  3538. detail::find_content_type(path, file_extension_and_mimetype_map_);
  3539. if (type) { res.set_header("Content-Type", type); }
  3540. res.status = 200;
  3541. if (!head && file_request_handler_) {
  3542. file_request_handler_(req, res);
  3543. }
  3544. return true;
  3545. }
  3546. }
  3547. }
  3548. }
  3549. return false;
  3550. }
  3551. inline socket_t
  3552. Server::create_server_socket(const char *host, int port, int socket_flags,
  3553. SocketOptions socket_options) const {
  3554. return detail::create_socket(
  3555. host, port, socket_flags, tcp_nodelay_, socket_options,
  3556. [](socket_t sock, struct addrinfo &ai) -> bool {
  3557. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  3558. return false;
  3559. }
  3560. if (::listen(sock, 5)) { // Listen through 5 channels
  3561. return false;
  3562. }
  3563. return true;
  3564. });
  3565. }
  3566. inline int Server::bind_internal(const char *host, int port, int socket_flags) {
  3567. if (!is_valid()) { return -1; }
  3568. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  3569. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  3570. if (port == 0) {
  3571. struct sockaddr_storage addr;
  3572. socklen_t addr_len = sizeof(addr);
  3573. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  3574. &addr_len) == -1) {
  3575. return -1;
  3576. }
  3577. if (addr.ss_family == AF_INET) {
  3578. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  3579. } else if (addr.ss_family == AF_INET6) {
  3580. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  3581. } else {
  3582. return -1;
  3583. }
  3584. } else {
  3585. return port;
  3586. }
  3587. }
  3588. inline bool Server::listen_internal() {
  3589. auto ret = true;
  3590. is_running_ = true;
  3591. {
  3592. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  3593. while (svr_sock_ != INVALID_SOCKET) {
  3594. #ifndef _WIN32
  3595. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  3596. #endif
  3597. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  3598. idle_interval_usec_);
  3599. if (val == 0) { // Timeout
  3600. task_queue->on_idle();
  3601. continue;
  3602. }
  3603. #ifndef _WIN32
  3604. }
  3605. #endif
  3606. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  3607. if (sock == INVALID_SOCKET) {
  3608. if (errno == EMFILE) {
  3609. // The per-process limit of open file descriptors has been reached.
  3610. // Try to accept new connections after a short sleep.
  3611. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3612. continue;
  3613. }
  3614. if (svr_sock_ != INVALID_SOCKET) {
  3615. detail::close_socket(svr_sock_);
  3616. ret = false;
  3617. } else {
  3618. ; // The server socket was closed by user.
  3619. }
  3620. break;
  3621. }
  3622. #if __cplusplus > 201703L
  3623. task_queue->enqueue([=, this]() { process_and_close_socket(sock); });
  3624. #else
  3625. task_queue->enqueue([=]() { process_and_close_socket(sock); });
  3626. #endif
  3627. }
  3628. task_queue->shutdown();
  3629. }
  3630. is_running_ = false;
  3631. return ret;
  3632. }
  3633. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  3634. // File handler
  3635. bool is_head_request = req.method == "HEAD";
  3636. if ((req.method == "GET" || is_head_request) &&
  3637. handle_file_request(req, res, is_head_request)) {
  3638. return true;
  3639. }
  3640. if (detail::expect_content(req)) {
  3641. // Content reader handler
  3642. {
  3643. ContentReader reader(
  3644. [&](ContentReceiver receiver) {
  3645. return read_content_with_content_receiver(strm, req, res, receiver,
  3646. nullptr, nullptr);
  3647. },
  3648. [&](MultipartContentHeader header, ContentReceiver receiver) {
  3649. return read_content_with_content_receiver(strm, req, res, nullptr,
  3650. header, receiver);
  3651. });
  3652. if (req.method == "POST") {
  3653. if (dispatch_request_for_content_reader(
  3654. req, res, reader, post_handlers_for_content_reader_)) {
  3655. return true;
  3656. }
  3657. } else if (req.method == "PUT") {
  3658. if (dispatch_request_for_content_reader(
  3659. req, res, reader, put_handlers_for_content_reader_)) {
  3660. return true;
  3661. }
  3662. } else if (req.method == "PATCH") {
  3663. if (dispatch_request_for_content_reader(
  3664. req, res, reader, patch_handlers_for_content_reader_)) {
  3665. return true;
  3666. }
  3667. } else if (req.method == "DELETE") {
  3668. if (dispatch_request_for_content_reader(
  3669. req, res, reader, delete_handlers_for_content_reader_)) {
  3670. return true;
  3671. }
  3672. }
  3673. }
  3674. // Read content into `req.body`
  3675. if (!read_content(strm, req, res)) { return false; }
  3676. }
  3677. // Regular handler
  3678. if (req.method == "GET" || req.method == "HEAD") {
  3679. return dispatch_request(req, res, get_handlers_);
  3680. } else if (req.method == "POST") {
  3681. return dispatch_request(req, res, post_handlers_);
  3682. } else if (req.method == "PUT") {
  3683. return dispatch_request(req, res, put_handlers_);
  3684. } else if (req.method == "DELETE") {
  3685. return dispatch_request(req, res, delete_handlers_);
  3686. } else if (req.method == "OPTIONS") {
  3687. return dispatch_request(req, res, options_handlers_);
  3688. } else if (req.method == "PATCH") {
  3689. return dispatch_request(req, res, patch_handlers_);
  3690. }
  3691. res.status = 400;
  3692. return false;
  3693. }
  3694. inline bool Server::dispatch_request(Request &req, Response &res,
  3695. Handlers &handlers) {
  3696. try {
  3697. for (const auto &x : handlers) {
  3698. const auto &pattern = x.first;
  3699. const auto &handler = x.second;
  3700. if (std::regex_match(req.path, req.matches, pattern)) {
  3701. handler(req, res);
  3702. return true;
  3703. }
  3704. }
  3705. } catch (const std::exception &ex) {
  3706. res.status = 500;
  3707. res.set_header("EXCEPTION_WHAT", ex.what());
  3708. } catch (...) {
  3709. res.status = 500;
  3710. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  3711. }
  3712. return false;
  3713. }
  3714. inline bool Server::dispatch_request_for_content_reader(
  3715. Request &req, Response &res, ContentReader content_reader,
  3716. HandlersForContentReader &handlers) {
  3717. for (const auto &x : handlers) {
  3718. const auto &pattern = x.first;
  3719. const auto &handler = x.second;
  3720. if (std::regex_match(req.path, req.matches, pattern)) {
  3721. handler(req, res, content_reader);
  3722. return true;
  3723. }
  3724. }
  3725. return false;
  3726. }
  3727. inline bool
  3728. Server::process_request(Stream &strm, bool close_connection,
  3729. bool &connection_closed,
  3730. const std::function<void(Request &)> &setup_request) {
  3731. std::array<char, 2048> buf{};
  3732. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  3733. // Connection has been closed on client
  3734. if (!line_reader.getline()) { return false; }
  3735. Request req;
  3736. Response res;
  3737. res.version = "HTTP/1.1";
  3738. // Check if the request URI doesn't exceed the limit
  3739. if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  3740. Headers dummy;
  3741. detail::read_headers(strm, dummy);
  3742. res.status = 414;
  3743. return write_response(strm, close_connection, req, res);
  3744. }
  3745. // Request line and headers
  3746. if (!parse_request_line(line_reader.ptr(), req) ||
  3747. !detail::read_headers(strm, req.headers)) {
  3748. res.status = 400;
  3749. return write_response(strm, close_connection, req, res);
  3750. }
  3751. if (req.get_header_value("Connection") == "close") {
  3752. connection_closed = true;
  3753. }
  3754. if (req.version == "HTTP/1.0" &&
  3755. req.get_header_value("Connection") != "Keep-Alive") {
  3756. connection_closed = true;
  3757. }
  3758. strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);
  3759. req.set_header("REMOTE_ADDR", req.remote_addr);
  3760. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  3761. if (req.has_header("Range")) {
  3762. const auto &range_header_value = req.get_header_value("Range");
  3763. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  3764. // TODO: error
  3765. }
  3766. }
  3767. if (setup_request) { setup_request(req); }
  3768. if (req.get_header_value("Expect") == "100-continue") {
  3769. auto status = 100;
  3770. if (expect_100_continue_handler_) {
  3771. status = expect_100_continue_handler_(req, res);
  3772. }
  3773. switch (status) {
  3774. case 100:
  3775. case 417:
  3776. strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
  3777. detail::status_message(status));
  3778. break;
  3779. default: return write_response(strm, close_connection, req, res);
  3780. }
  3781. }
  3782. // Rounting
  3783. if (routing(req, res, strm)) {
  3784. if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
  3785. } else {
  3786. if (res.status == -1) { res.status = 404; }
  3787. }
  3788. return write_response(strm, close_connection, req, res);
  3789. }
  3790. inline bool Server::is_valid() const { return true; }
  3791. inline bool Server::process_and_close_socket(socket_t sock) {
  3792. auto ret = detail::process_server_socket(
  3793. sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
  3794. write_timeout_sec_, write_timeout_usec_,
  3795. [this](Stream &strm, bool close_connection, bool &connection_closed) {
  3796. return process_request(strm, close_connection, connection_closed,
  3797. nullptr);
  3798. });
  3799. detail::shutdown_socket(sock);
  3800. detail::close_socket(sock);
  3801. return ret;
  3802. }
  3803. // HTTP client implementation
  3804. inline ClientImpl::ClientImpl(const std::string &host)
  3805. : ClientImpl(host, 80, std::string(), std::string()) {}
  3806. inline ClientImpl::ClientImpl(const std::string &host, int port)
  3807. : ClientImpl(host, port, std::string(), std::string()) {}
  3808. inline ClientImpl::ClientImpl(const std::string &host, int port,
  3809. const std::string &client_cert_path,
  3810. const std::string &client_key_path)
  3811. : host_(host), port_(port),
  3812. host_and_port_(host_ + ":" + std::to_string(port_)),
  3813. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  3814. inline ClientImpl::~ClientImpl() { stop_core(); }
  3815. inline bool ClientImpl::is_valid() const { return true; }
  3816. inline Error ClientImpl::get_last_error() const { return error_; }
  3817. inline socket_t ClientImpl::create_client_socket() const {
  3818. if (!proxy_host_.empty()) {
  3819. return detail::create_client_socket(
  3820. proxy_host_.c_str(), proxy_port_, tcp_nodelay_, socket_options_,
  3821. connection_timeout_sec_, connection_timeout_usec_, interface_, error_);
  3822. }
  3823. return detail::create_client_socket(
  3824. host_.c_str(), port_, tcp_nodelay_, socket_options_,
  3825. connection_timeout_sec_, connection_timeout_usec_, interface_, error_);
  3826. }
  3827. inline bool ClientImpl::create_and_connect_socket(Socket &socket) {
  3828. auto sock = create_client_socket();
  3829. if (sock == INVALID_SOCKET) { return false; }
  3830. socket.sock = sock;
  3831. return true;
  3832. }
  3833. inline void ClientImpl::close_socket(Socket &socket,
  3834. bool /*process_socket_ret*/) {
  3835. detail::close_socket(socket.sock);
  3836. socket_.sock = INVALID_SOCKET;
  3837. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3838. socket_.ssl = nullptr;
  3839. #endif
  3840. }
  3841. inline bool ClientImpl::read_response_line(Stream &strm, Response &res) {
  3842. std::array<char, 2048> buf;
  3843. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  3844. if (!line_reader.getline()) { return false; }
  3845. const static std::regex re("(HTTP/1\\.[01]) (\\d+).*?\r\n");
  3846. std::cmatch m;
  3847. if (std::regex_match(line_reader.ptr(), m, re)) {
  3848. res.version = std::string(m[1]);
  3849. res.status = std::stoi(std::string(m[2]));
  3850. }
  3851. return true;
  3852. }
  3853. inline bool ClientImpl::send(const Request &req, Response &res) {
  3854. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  3855. {
  3856. std::lock_guard<std::mutex> guard(socket_mutex_);
  3857. auto is_alive = false;
  3858. if (socket_.is_open()) {
  3859. is_alive = detail::select_write(socket_.sock, 0, 0) > 0;
  3860. if (!is_alive) { close_socket(socket_, false); }
  3861. }
  3862. if (!is_alive) {
  3863. if (!create_and_connect_socket(socket_)) { return false; }
  3864. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3865. // TODO: refactoring
  3866. if (is_ssl()) {
  3867. auto &scli = static_cast<SSLClient &>(*this);
  3868. if (!proxy_host_.empty()) {
  3869. bool success = false;
  3870. if (!scli.connect_with_proxy(socket_, res, success)) {
  3871. return success;
  3872. }
  3873. }
  3874. if (!scli.initialize_ssl(socket_)) { return false; }
  3875. }
  3876. #endif
  3877. }
  3878. }
  3879. auto close_connection = !keep_alive_;
  3880. auto ret = process_socket(socket_, [&](Stream &strm) {
  3881. return handle_request(strm, req, res, close_connection);
  3882. });
  3883. if (close_connection || !ret) { stop_core(); }
  3884. if (!ret) {
  3885. if (error_ == Error::Success) { error_ = Error::Unknown; }
  3886. }
  3887. return ret;
  3888. }
  3889. inline bool ClientImpl::handle_request(Stream &strm, const Request &req,
  3890. Response &res, bool close_connection) {
  3891. if (req.path.empty()) {
  3892. error_ = Error::Connection;
  3893. return false;
  3894. }
  3895. bool ret;
  3896. if (!is_ssl() && !proxy_host_.empty()) {
  3897. auto req2 = req;
  3898. req2.path = "http://" + host_and_port_ + req.path;
  3899. ret = process_request(strm, req2, res, close_connection);
  3900. } else {
  3901. ret = process_request(strm, req, res, close_connection);
  3902. }
  3903. if (!ret) { return false; }
  3904. if (300 < res.status && res.status < 400 && follow_location_) {
  3905. ret = redirect(req, res);
  3906. }
  3907. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3908. if ((res.status == 401 || res.status == 407) &&
  3909. req.authorization_count_ < 5) {
  3910. auto is_proxy = res.status == 407;
  3911. const auto &username =
  3912. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  3913. const auto &password =
  3914. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  3915. if (!username.empty() && !password.empty()) {
  3916. std::map<std::string, std::string> auth;
  3917. if (parse_www_authenticate(res, auth, is_proxy)) {
  3918. Request new_req = req;
  3919. new_req.authorization_count_ += 1;
  3920. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3921. new_req.headers.erase(key);
  3922. new_req.headers.insert(make_digest_authentication_header(
  3923. req, auth, new_req.authorization_count_, random_string(10),
  3924. username, password, is_proxy));
  3925. Response new_res;
  3926. ret = send(new_req, new_res);
  3927. if (ret) { res = new_res; }
  3928. }
  3929. }
  3930. }
  3931. #endif
  3932. return ret;
  3933. }
  3934. inline bool ClientImpl::redirect(const Request &req, Response &res) {
  3935. if (req.redirect_count == 0) {
  3936. error_ = Error::ExceedRedirectCount;
  3937. return false;
  3938. }
  3939. auto location = res.get_header_value("location");
  3940. if (location.empty()) { return false; }
  3941. const static std::regex re(
  3942. R"(^(?:(https?):)?(?://([^:/?#]*)(?::(\d+))?)?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
  3943. std::smatch m;
  3944. if (!std::regex_match(location, m, re)) { return false; }
  3945. auto scheme = is_ssl() ? "https" : "http";
  3946. auto next_scheme = m[1].str();
  3947. auto next_host = m[2].str();
  3948. auto port_str = m[3].str();
  3949. auto next_path = m[4].str();
  3950. auto next_port = port_;
  3951. if (!port_str.empty()) {
  3952. next_port = std::stoi(port_str);
  3953. } else if (!next_scheme.empty()) {
  3954. next_port = next_scheme == "https" ? 443 : 80;
  3955. }
  3956. if (next_scheme.empty()) { next_scheme = scheme; }
  3957. if (next_host.empty()) { next_host = host_; }
  3958. if (next_path.empty()) { next_path = "/"; }
  3959. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  3960. return detail::redirect(*this, req, res, next_path);
  3961. } else {
  3962. if (next_scheme == "https") {
  3963. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3964. SSLClient cli(next_host.c_str(), next_port);
  3965. cli.copy_settings(*this);
  3966. auto ret = detail::redirect(cli, req, res, next_path);
  3967. if (!ret) { error_ = cli.get_last_error(); }
  3968. return ret;
  3969. #else
  3970. return false;
  3971. #endif
  3972. } else {
  3973. ClientImpl cli(next_host.c_str(), next_port);
  3974. cli.copy_settings(*this);
  3975. auto ret = detail::redirect(cli, req, res, next_path);
  3976. if (!ret) { error_ = cli.get_last_error(); }
  3977. return ret;
  3978. }
  3979. }
  3980. }
  3981. inline bool ClientImpl::write_request(Stream &strm, const Request &req,
  3982. bool close_connection) {
  3983. detail::BufferStream bstrm;
  3984. // Request line
  3985. const auto &path = detail::encode_url(req.path);
  3986. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  3987. // Additonal headers
  3988. Headers headers;
  3989. if (close_connection) { headers.emplace("Connection", "close"); }
  3990. if (!req.has_header("Host")) {
  3991. if (is_ssl()) {
  3992. if (port_ == 443) {
  3993. headers.emplace("Host", host_);
  3994. } else {
  3995. headers.emplace("Host", host_and_port_);
  3996. }
  3997. } else {
  3998. if (port_ == 80) {
  3999. headers.emplace("Host", host_);
  4000. } else {
  4001. headers.emplace("Host", host_and_port_);
  4002. }
  4003. }
  4004. }
  4005. if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
  4006. if (!req.has_header("User-Agent")) {
  4007. headers.emplace("User-Agent", "cpp-httplib/0.7");
  4008. }
  4009. if (req.body.empty()) {
  4010. if (req.content_provider) {
  4011. auto length = std::to_string(req.content_length);
  4012. headers.emplace("Content-Length", length);
  4013. } else {
  4014. headers.emplace("Content-Length", "0");
  4015. }
  4016. } else {
  4017. if (!req.has_header("Content-Type")) {
  4018. headers.emplace("Content-Type", "text/plain");
  4019. }
  4020. if (!req.has_header("Content-Length")) {
  4021. auto length = std::to_string(req.body.size());
  4022. headers.emplace("Content-Length", length);
  4023. }
  4024. }
  4025. if (!basic_auth_username_.empty() && !basic_auth_password_.empty()) {
  4026. headers.insert(make_basic_authentication_header(
  4027. basic_auth_username_, basic_auth_password_, false));
  4028. }
  4029. if (!proxy_basic_auth_username_.empty() &&
  4030. !proxy_basic_auth_password_.empty()) {
  4031. headers.insert(make_basic_authentication_header(
  4032. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  4033. }
  4034. if (!bearer_token_auth_token_.empty()) {
  4035. headers.insert(make_bearer_token_authentication_header(
  4036. bearer_token_auth_token_, false));
  4037. }
  4038. if (!proxy_bearer_token_auth_token_.empty()) {
  4039. headers.insert(make_bearer_token_authentication_header(
  4040. proxy_bearer_token_auth_token_, true));
  4041. }
  4042. detail::write_headers(bstrm, req, headers);
  4043. // Flush buffer
  4044. auto &data = bstrm.get_buffer();
  4045. if (!detail::write_data(strm, data.data(), data.size())) {
  4046. error_ = Error::Write;
  4047. return false;
  4048. }
  4049. // Body
  4050. if (req.body.empty()) {
  4051. if (req.content_provider) {
  4052. size_t offset = 0;
  4053. size_t end_offset = req.content_length;
  4054. bool ok = true;
  4055. DataSink data_sink;
  4056. data_sink.write = [&](const char *d, size_t l) {
  4057. if (ok) {
  4058. if (detail::write_data(strm, d, l)) {
  4059. offset += l;
  4060. } else {
  4061. ok = false;
  4062. }
  4063. }
  4064. };
  4065. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  4066. while (offset < end_offset) {
  4067. if (!req.content_provider(offset, end_offset - offset, data_sink)) {
  4068. error_ = Error::Canceled;
  4069. return false;
  4070. }
  4071. if (!ok) {
  4072. error_ = Error::Write;
  4073. return false;
  4074. }
  4075. }
  4076. }
  4077. } else {
  4078. return detail::write_data(strm, req.body.data(), req.body.size());
  4079. }
  4080. return true;
  4081. }
  4082. inline std::shared_ptr<Response> ClientImpl::send_with_content_provider(
  4083. const char *method, const char *path, const Headers &headers,
  4084. const std::string &body, size_t content_length,
  4085. ContentProvider content_provider, const char *content_type) {
  4086. Request req;
  4087. req.method = method;
  4088. req.headers = default_headers_;
  4089. req.headers.insert(headers.begin(), headers.end());
  4090. req.path = path;
  4091. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  4092. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4093. if (compress_) {
  4094. detail::gzip_compressor compressor;
  4095. if (content_provider) {
  4096. auto ok = true;
  4097. size_t offset = 0;
  4098. DataSink data_sink;
  4099. data_sink.write = [&](const char *data, size_t data_len) {
  4100. if (ok) {
  4101. auto last = offset + data_len == content_length;
  4102. auto ret = compressor.compress(
  4103. data, data_len, last, [&](const char *data, size_t data_len) {
  4104. req.body.append(data, data_len);
  4105. return true;
  4106. });
  4107. if (ret) {
  4108. offset += data_len;
  4109. } else {
  4110. ok = false;
  4111. }
  4112. }
  4113. };
  4114. data_sink.is_writable = [&](void) { return ok && true; };
  4115. while (ok && offset < content_length) {
  4116. if (!content_provider(offset, content_length - offset, data_sink)) {
  4117. error_ = Error::Canceled;
  4118. return nullptr;
  4119. }
  4120. }
  4121. } else {
  4122. if (!compressor.compress(body.data(), body.size(), true,
  4123. [&](const char *data, size_t data_len) {
  4124. req.body.append(data, data_len);
  4125. return true;
  4126. })) {
  4127. return nullptr;
  4128. }
  4129. }
  4130. req.headers.emplace("Content-Encoding", "gzip");
  4131. } else
  4132. #endif
  4133. {
  4134. if (content_provider) {
  4135. req.content_length = content_length;
  4136. req.content_provider = content_provider;
  4137. } else {
  4138. req.body = body;
  4139. }
  4140. }
  4141. auto res = std::make_shared<Response>();
  4142. return send(req, *res) ? res : nullptr;
  4143. }
  4144. inline bool ClientImpl::process_request(Stream &strm, const Request &req,
  4145. Response &res, bool close_connection) {
  4146. // Send request
  4147. if (!write_request(strm, req, close_connection)) { return false; }
  4148. // Receive response and headers
  4149. if (!read_response_line(strm, res) ||
  4150. !detail::read_headers(strm, res.headers)) {
  4151. error_ = Error::Read;
  4152. return false;
  4153. }
  4154. if (req.response_handler) {
  4155. if (!req.response_handler(res)) {
  4156. error_ = Error::Canceled;
  4157. return false;
  4158. }
  4159. }
  4160. // Body
  4161. if (req.method != "HEAD" && req.method != "CONNECT") {
  4162. auto out =
  4163. req.content_receiver
  4164. ? static_cast<ContentReceiver>([&](const char *buf, size_t n) {
  4165. auto ret = req.content_receiver(buf, n);
  4166. if (!ret) { error_ = Error::Canceled; }
  4167. return ret;
  4168. })
  4169. : static_cast<ContentReceiver>([&](const char *buf, size_t n) {
  4170. if (res.body.size() + n > res.body.max_size()) { return false; }
  4171. res.body.append(buf, n);
  4172. return true;
  4173. });
  4174. auto progress = [&](uint64_t current, uint64_t total) {
  4175. if (!req.progress) { return true; }
  4176. auto ret = req.progress(current, total);
  4177. if (!ret) { error_ = Error::Canceled; }
  4178. return ret;
  4179. };
  4180. int dummy_status;
  4181. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  4182. dummy_status, progress, out, decompress_)) {
  4183. if (error_ != Error::Canceled) { error_ = Error::Read; }
  4184. return false;
  4185. }
  4186. }
  4187. if (res.get_header_value("Connection") == "close" ||
  4188. res.version == "HTTP/1.0") {
  4189. stop_core();
  4190. }
  4191. // Log
  4192. if (logger_) { logger_(req, res); }
  4193. return true;
  4194. }
  4195. inline bool
  4196. ClientImpl::process_socket(Socket &socket,
  4197. std::function<bool(Stream &strm)> callback) {
  4198. return detail::process_client_socket(socket.sock, read_timeout_sec_,
  4199. read_timeout_usec_, write_timeout_sec_,
  4200. write_timeout_usec_, callback);
  4201. }
  4202. inline bool ClientImpl::is_ssl() const { return false; }
  4203. inline Result ClientImpl::Get(const char *path) {
  4204. return Get(path, Headers(), Progress());
  4205. }
  4206. inline Result ClientImpl::Get(const char *path, Progress progress) {
  4207. return Get(path, Headers(), std::move(progress));
  4208. }
  4209. inline Result ClientImpl::Get(const char *path, const Headers &headers) {
  4210. return Get(path, headers, Progress());
  4211. }
  4212. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4213. Progress progress) {
  4214. Request req;
  4215. req.method = "GET";
  4216. req.path = path;
  4217. req.headers = default_headers_;
  4218. req.headers.insert(headers.begin(), headers.end());
  4219. req.progress = std::move(progress);
  4220. auto res = std::make_shared<Response>();
  4221. return Result{send(req, *res) ? res : nullptr, get_last_error()};
  4222. }
  4223. inline Result ClientImpl::Get(const char *path,
  4224. ContentReceiver content_receiver) {
  4225. return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr);
  4226. }
  4227. inline Result ClientImpl::Get(const char *path,
  4228. ContentReceiver content_receiver,
  4229. Progress progress) {
  4230. return Get(path, Headers(), nullptr, std::move(content_receiver),
  4231. std::move(progress));
  4232. }
  4233. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4234. ContentReceiver content_receiver) {
  4235. return Get(path, headers, nullptr, std::move(content_receiver), nullptr);
  4236. }
  4237. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4238. ContentReceiver content_receiver,
  4239. Progress progress) {
  4240. return Get(path, headers, nullptr, std::move(content_receiver),
  4241. std::move(progress));
  4242. }
  4243. inline Result ClientImpl::Get(const char *path,
  4244. ResponseHandler response_handler,
  4245. ContentReceiver content_receiver) {
  4246. return Get(path, Headers(), std::move(response_handler), content_receiver,
  4247. nullptr);
  4248. }
  4249. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4250. ResponseHandler response_handler,
  4251. ContentReceiver content_receiver) {
  4252. return Get(path, headers, std::move(response_handler), content_receiver,
  4253. nullptr);
  4254. }
  4255. inline Result ClientImpl::Get(const char *path,
  4256. ResponseHandler response_handler,
  4257. ContentReceiver content_receiver,
  4258. Progress progress) {
  4259. return Get(path, Headers(), std::move(response_handler), content_receiver,
  4260. progress);
  4261. }
  4262. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4263. ResponseHandler response_handler,
  4264. ContentReceiver content_receiver,
  4265. Progress progress) {
  4266. Request req;
  4267. req.method = "GET";
  4268. req.path = path;
  4269. req.headers = default_headers_;
  4270. req.headers.insert(headers.begin(), headers.end());
  4271. req.response_handler = std::move(response_handler);
  4272. req.content_receiver = std::move(content_receiver);
  4273. req.progress = std::move(progress);
  4274. auto res = std::make_shared<Response>();
  4275. return Result{send(req, *res) ? res : nullptr, get_last_error()};
  4276. }
  4277. inline Result ClientImpl::Head(const char *path) {
  4278. return Head(path, Headers());
  4279. }
  4280. inline Result ClientImpl::Head(const char *path, const Headers &headers) {
  4281. Request req;
  4282. req.method = "HEAD";
  4283. req.headers = default_headers_;
  4284. req.headers.insert(headers.begin(), headers.end());
  4285. req.path = path;
  4286. auto res = std::make_shared<Response>();
  4287. return Result{send(req, *res) ? res : nullptr, get_last_error()};
  4288. }
  4289. inline Result ClientImpl::Post(const char *path) {
  4290. return Post(path, std::string(), nullptr);
  4291. }
  4292. inline Result ClientImpl::Post(const char *path, const std::string &body,
  4293. const char *content_type) {
  4294. return Post(path, Headers(), body, content_type);
  4295. }
  4296. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4297. const std::string &body,
  4298. const char *content_type) {
  4299. return Result{send_with_content_provider("POST", path, headers, body, 0,
  4300. nullptr, content_type),
  4301. get_last_error()};
  4302. }
  4303. inline Result ClientImpl::Post(const char *path, const Params &params) {
  4304. return Post(path, Headers(), params);
  4305. }
  4306. inline Result ClientImpl::Post(const char *path, size_t content_length,
  4307. ContentProvider content_provider,
  4308. const char *content_type) {
  4309. return Post(path, Headers(), content_length, content_provider, content_type);
  4310. }
  4311. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4312. size_t content_length,
  4313. ContentProvider content_provider,
  4314. const char *content_type) {
  4315. return Result{send_with_content_provider("POST", path, headers, std::string(),
  4316. content_length, content_provider,
  4317. content_type),
  4318. get_last_error()};
  4319. }
  4320. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4321. const Params &params) {
  4322. auto query = detail::params_to_query_str(params);
  4323. return Post(path, headers, query, "application/x-www-form-urlencoded");
  4324. }
  4325. inline Result ClientImpl::Post(const char *path,
  4326. const MultipartFormDataItems &items) {
  4327. return Post(path, Headers(), items);
  4328. }
  4329. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4330. const MultipartFormDataItems &items) {
  4331. auto boundary = detail::make_multipart_data_boundary();
  4332. std::string body;
  4333. for (const auto &item : items) {
  4334. body += "--" + boundary + "\r\n";
  4335. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4336. if (!item.filename.empty()) {
  4337. body += "; filename=\"" + item.filename + "\"";
  4338. }
  4339. body += "\r\n";
  4340. if (!item.content_type.empty()) {
  4341. body += "Content-Type: " + item.content_type + "\r\n";
  4342. }
  4343. body += "\r\n";
  4344. body += item.content + "\r\n";
  4345. }
  4346. body += "--" + boundary + "--\r\n";
  4347. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4348. return Post(path, headers, body, content_type.c_str());
  4349. }
  4350. inline Result ClientImpl::Put(const char *path) {
  4351. return Put(path, std::string(), nullptr);
  4352. }
  4353. inline Result ClientImpl::Put(const char *path, const std::string &body,
  4354. const char *content_type) {
  4355. return Put(path, Headers(), body, content_type);
  4356. }
  4357. inline Result ClientImpl::Put(const char *path, const Headers &headers,
  4358. const std::string &body,
  4359. const char *content_type) {
  4360. return Result{send_with_content_provider("PUT", path, headers, body, 0,
  4361. nullptr, content_type),
  4362. get_last_error()};
  4363. }
  4364. inline Result ClientImpl::Put(const char *path, size_t content_length,
  4365. ContentProvider content_provider,
  4366. const char *content_type) {
  4367. return Put(path, Headers(), content_length, content_provider, content_type);
  4368. }
  4369. inline Result ClientImpl::Put(const char *path, const Headers &headers,
  4370. size_t content_length,
  4371. ContentProvider content_provider,
  4372. const char *content_type) {
  4373. return Result{send_with_content_provider("PUT", path, headers, std::string(),
  4374. content_length, content_provider,
  4375. content_type),
  4376. get_last_error()};
  4377. }
  4378. inline Result ClientImpl::Put(const char *path, const Params &params) {
  4379. return Put(path, Headers(), params);
  4380. }
  4381. inline Result ClientImpl::Put(const char *path, const Headers &headers,
  4382. const Params &params) {
  4383. auto query = detail::params_to_query_str(params);
  4384. return Put(path, headers, query, "application/x-www-form-urlencoded");
  4385. }
  4386. inline Result ClientImpl::Patch(const char *path, const std::string &body,
  4387. const char *content_type) {
  4388. return Patch(path, Headers(), body, content_type);
  4389. }
  4390. inline Result ClientImpl::Patch(const char *path, const Headers &headers,
  4391. const std::string &body,
  4392. const char *content_type) {
  4393. return Result{send_with_content_provider("PATCH", path, headers, body, 0,
  4394. nullptr, content_type),
  4395. get_last_error()};
  4396. }
  4397. inline Result ClientImpl::Patch(const char *path, size_t content_length,
  4398. ContentProvider content_provider,
  4399. const char *content_type) {
  4400. return Patch(path, Headers(), content_length, content_provider, content_type);
  4401. }
  4402. inline Result ClientImpl::Patch(const char *path, const Headers &headers,
  4403. size_t content_length,
  4404. ContentProvider content_provider,
  4405. const char *content_type) {
  4406. return Result{send_with_content_provider("PATCH", path, headers,
  4407. std::string(), content_length,
  4408. content_provider, content_type),
  4409. get_last_error()};
  4410. }
  4411. inline Result ClientImpl::Delete(const char *path) {
  4412. return Delete(path, Headers(), std::string(), nullptr);
  4413. }
  4414. inline Result ClientImpl::Delete(const char *path, const std::string &body,
  4415. const char *content_type) {
  4416. return Delete(path, Headers(), body, content_type);
  4417. }
  4418. inline Result ClientImpl::Delete(const char *path, const Headers &headers) {
  4419. return Delete(path, headers, std::string(), nullptr);
  4420. }
  4421. inline Result ClientImpl::Delete(const char *path, const Headers &headers,
  4422. const std::string &body,
  4423. const char *content_type) {
  4424. Request req;
  4425. req.method = "DELETE";
  4426. req.headers = default_headers_;
  4427. req.headers.insert(headers.begin(), headers.end());
  4428. req.path = path;
  4429. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  4430. req.body = body;
  4431. auto res = std::make_shared<Response>();
  4432. return Result{send(req, *res) ? res : nullptr, get_last_error()};
  4433. }
  4434. inline Result ClientImpl::Options(const char *path) {
  4435. return Options(path, Headers());
  4436. }
  4437. inline Result ClientImpl::Options(const char *path, const Headers &headers) {
  4438. Request req;
  4439. req.method = "OPTIONS";
  4440. req.headers = default_headers_;
  4441. req.headers.insert(headers.begin(), headers.end());
  4442. req.path = path;
  4443. auto res = std::make_shared<Response>();
  4444. return Result{send(req, *res) ? res : nullptr, get_last_error()};
  4445. }
  4446. inline size_t ClientImpl::is_socket_open() const {
  4447. std::lock_guard<std::mutex> guard(socket_mutex_);
  4448. return socket_.is_open();
  4449. }
  4450. inline void ClientImpl::stop() {
  4451. stop_core();
  4452. error_ = Error::Canceled;
  4453. }
  4454. inline void ClientImpl::stop_core() {
  4455. std::lock_guard<std::mutex> guard(socket_mutex_);
  4456. if (socket_.is_open()) {
  4457. detail::shutdown_socket(socket_.sock);
  4458. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4459. close_socket(socket_, true);
  4460. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4461. }
  4462. }
  4463. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  4464. connection_timeout_sec_ = sec;
  4465. connection_timeout_usec_ = usec;
  4466. }
  4467. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  4468. read_timeout_sec_ = sec;
  4469. read_timeout_usec_ = usec;
  4470. }
  4471. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  4472. write_timeout_sec_ = sec;
  4473. write_timeout_usec_ = usec;
  4474. }
  4475. inline void ClientImpl::set_basic_auth(const char *username,
  4476. const char *password) {
  4477. basic_auth_username_ = username;
  4478. basic_auth_password_ = password;
  4479. }
  4480. inline void ClientImpl::set_bearer_token_auth(const char *token) {
  4481. bearer_token_auth_token_ = token;
  4482. }
  4483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4484. inline void ClientImpl::set_digest_auth(const char *username,
  4485. const char *password) {
  4486. digest_auth_username_ = username;
  4487. digest_auth_password_ = password;
  4488. }
  4489. #endif
  4490. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  4491. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  4492. inline void ClientImpl::set_default_headers(Headers headers) {
  4493. default_headers_ = std::move(headers);
  4494. }
  4495. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  4496. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  4497. socket_options_ = socket_options;
  4498. }
  4499. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  4500. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  4501. inline void ClientImpl::set_interface(const char *intf) { interface_ = intf; }
  4502. inline void ClientImpl::set_proxy(const char *host, int port) {
  4503. proxy_host_ = host;
  4504. proxy_port_ = port;
  4505. }
  4506. inline void ClientImpl::set_proxy_basic_auth(const char *username,
  4507. const char *password) {
  4508. proxy_basic_auth_username_ = username;
  4509. proxy_basic_auth_password_ = password;
  4510. }
  4511. inline void ClientImpl::set_proxy_bearer_token_auth(const char *token) {
  4512. proxy_bearer_token_auth_token_ = token;
  4513. }
  4514. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4515. inline void ClientImpl::set_proxy_digest_auth(const char *username,
  4516. const char *password) {
  4517. proxy_digest_auth_username_ = username;
  4518. proxy_digest_auth_password_ = password;
  4519. }
  4520. #endif
  4521. inline void ClientImpl::set_logger(Logger logger) {
  4522. logger_ = std::move(logger);
  4523. }
  4524. /*
  4525. * SSL Implementation
  4526. */
  4527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4528. namespace detail {
  4529. template <typename U, typename V>
  4530. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  4531. U SSL_connect_or_accept, V setup) {
  4532. SSL *ssl = nullptr;
  4533. {
  4534. std::lock_guard<std::mutex> guard(ctx_mutex);
  4535. ssl = SSL_new(ctx);
  4536. }
  4537. if (ssl) {
  4538. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  4539. SSL_set_bio(ssl, bio, bio);
  4540. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  4541. SSL_shutdown(ssl);
  4542. {
  4543. std::lock_guard<std::mutex> guard(ctx_mutex);
  4544. SSL_free(ssl);
  4545. }
  4546. return nullptr;
  4547. }
  4548. }
  4549. return ssl;
  4550. }
  4551. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,
  4552. bool process_socket_ret) {
  4553. if (process_socket_ret) {
  4554. SSL_shutdown(ssl); // shutdown only if not already closed by remote
  4555. }
  4556. std::lock_guard<std::mutex> guard(ctx_mutex);
  4557. SSL_free(ssl);
  4558. }
  4559. template <typename T>
  4560. inline bool
  4561. process_server_socket_ssl(SSL *ssl, socket_t sock, size_t keep_alive_max_count,
  4562. time_t read_timeout_sec, time_t read_timeout_usec,
  4563. time_t write_timeout_sec, time_t write_timeout_usec,
  4564. T callback) {
  4565. return process_server_socket_core(
  4566. sock, keep_alive_max_count,
  4567. [&](bool close_connection, bool connection_closed) {
  4568. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  4569. write_timeout_sec, write_timeout_usec);
  4570. return callback(strm, close_connection, connection_closed);
  4571. });
  4572. }
  4573. template <typename T>
  4574. inline bool
  4575. process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec,
  4576. time_t read_timeout_usec, time_t write_timeout_sec,
  4577. time_t write_timeout_usec, T callback) {
  4578. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  4579. write_timeout_sec, write_timeout_usec);
  4580. return callback(strm);
  4581. }
  4582. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  4583. static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
  4584. class SSLThreadLocks {
  4585. public:
  4586. SSLThreadLocks() {
  4587. openSSL_locks_ =
  4588. std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
  4589. CRYPTO_set_locking_callback(locking_callback);
  4590. }
  4591. ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
  4592. private:
  4593. static void locking_callback(int mode, int type, const char * /*file*/,
  4594. int /*line*/) {
  4595. auto &lk = (*openSSL_locks_)[static_cast<size_t>(type)];
  4596. if (mode & CRYPTO_LOCK) {
  4597. lk.lock();
  4598. } else {
  4599. lk.unlock();
  4600. }
  4601. }
  4602. };
  4603. #endif
  4604. class SSLInit {
  4605. public:
  4606. SSLInit() {
  4607. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  4608. SSL_load_error_strings();
  4609. SSL_library_init();
  4610. #else
  4611. OPENSSL_init_ssl(
  4612. OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  4613. #endif
  4614. }
  4615. ~SSLInit() {
  4616. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  4617. ERR_free_strings();
  4618. #endif
  4619. }
  4620. private:
  4621. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  4622. SSLThreadLocks thread_init_;
  4623. #endif
  4624. };
  4625. // SSL socket stream implementation
  4626. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
  4627. time_t read_timeout_sec,
  4628. time_t read_timeout_usec,
  4629. time_t write_timeout_sec,
  4630. time_t write_timeout_usec)
  4631. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  4632. read_timeout_usec_(read_timeout_usec),
  4633. write_timeout_sec_(write_timeout_sec),
  4634. write_timeout_usec_(write_timeout_usec) {
  4635. {
  4636. timeval tv;
  4637. tv.tv_sec = static_cast<long>(read_timeout_sec);
  4638. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec);
  4639. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char *>(&tv),
  4640. sizeof(tv));
  4641. }
  4642. {
  4643. timeval tv;
  4644. tv.tv_sec = static_cast<long>(write_timeout_sec);
  4645. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec);
  4646. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<char *>(&tv),
  4647. sizeof(tv));
  4648. }
  4649. }
  4650. inline SSLSocketStream::~SSLSocketStream() {}
  4651. inline bool SSLSocketStream::is_readable() const {
  4652. return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  4653. }
  4654. inline bool SSLSocketStream::is_writable() const {
  4655. return detail::select_write(sock_, write_timeout_sec_, write_timeout_usec_) >
  4656. 0;
  4657. }
  4658. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  4659. if (SSL_pending(ssl_) > 0 || is_readable()) {
  4660. return SSL_read(ssl_, ptr, static_cast<int>(size));
  4661. }
  4662. return -1;
  4663. }
  4664. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  4665. if (is_writable()) { return SSL_write(ssl_, ptr, static_cast<int>(size)); }
  4666. return -1;
  4667. }
  4668. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  4669. int &port) const {
  4670. detail::get_remote_ip_and_port(sock_, ip, port);
  4671. }
  4672. static SSLInit sslinit_;
  4673. } // namespace detail
  4674. // SSL HTTP server implementation
  4675. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  4676. const char *client_ca_cert_file_path,
  4677. const char *client_ca_cert_dir_path) {
  4678. ctx_ = SSL_CTX_new(SSLv23_server_method());
  4679. if (ctx_) {
  4680. SSL_CTX_set_options(ctx_,
  4681. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  4682. SSL_OP_NO_COMPRESSION |
  4683. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4684. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  4685. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  4686. // EC_KEY_free(ecdh);
  4687. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  4688. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  4689. 1) {
  4690. SSL_CTX_free(ctx_);
  4691. ctx_ = nullptr;
  4692. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  4693. // if (client_ca_cert_file_path) {
  4694. // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
  4695. // SSL_CTX_set_client_CA_list(ctx_, list);
  4696. // }
  4697. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  4698. client_ca_cert_dir_path);
  4699. SSL_CTX_set_verify(
  4700. ctx_,
  4701. SSL_VERIFY_PEER |
  4702. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4703. nullptr);
  4704. }
  4705. }
  4706. }
  4707. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  4708. X509_STORE *client_ca_cert_store) {
  4709. ctx_ = SSL_CTX_new(SSLv23_server_method());
  4710. if (ctx_) {
  4711. SSL_CTX_set_options(ctx_,
  4712. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  4713. SSL_OP_NO_COMPRESSION |
  4714. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4715. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  4716. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  4717. SSL_CTX_free(ctx_);
  4718. ctx_ = nullptr;
  4719. } else if (client_ca_cert_store) {
  4720. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  4721. SSL_CTX_set_verify(
  4722. ctx_,
  4723. SSL_VERIFY_PEER |
  4724. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4725. nullptr);
  4726. }
  4727. }
  4728. }
  4729. inline SSLServer::~SSLServer() {
  4730. if (ctx_) { SSL_CTX_free(ctx_); }
  4731. }
  4732. inline bool SSLServer::is_valid() const { return ctx_; }
  4733. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  4734. auto ssl = detail::ssl_new(sock, ctx_, ctx_mutex_, SSL_accept,
  4735. [](SSL * /*ssl*/) { return true; });
  4736. if (ssl) {
  4737. auto ret = detail::process_server_socket_ssl(
  4738. ssl, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
  4739. write_timeout_sec_, write_timeout_usec_,
  4740. [this, ssl](Stream &strm, bool close_connection,
  4741. bool &connection_closed) {
  4742. return process_request(strm, close_connection, connection_closed,
  4743. [&](Request &req) { req.ssl = ssl; });
  4744. });
  4745. detail::ssl_delete(ctx_mutex_, ssl, ret);
  4746. return ret;
  4747. }
  4748. detail::close_socket(sock);
  4749. return false;
  4750. }
  4751. // SSL HTTP client implementation
  4752. inline SSLClient::SSLClient(const std::string &host)
  4753. : SSLClient(host, 443, std::string(), std::string()) {}
  4754. inline SSLClient::SSLClient(const std::string &host, int port)
  4755. : SSLClient(host, port, std::string(), std::string()) {}
  4756. inline SSLClient::SSLClient(const std::string &host, int port,
  4757. const std::string &client_cert_path,
  4758. const std::string &client_key_path)
  4759. : ClientImpl(host, port, client_cert_path, client_key_path) {
  4760. ctx_ = SSL_CTX_new(SSLv23_client_method());
  4761. detail::split(&host_[0], &host_[host_.size()], '.',
  4762. [&](const char *b, const char *e) {
  4763. host_components_.emplace_back(std::string(b, e));
  4764. });
  4765. if (!client_cert_path.empty() && !client_key_path.empty()) {
  4766. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  4767. SSL_FILETYPE_PEM) != 1 ||
  4768. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  4769. SSL_FILETYPE_PEM) != 1) {
  4770. SSL_CTX_free(ctx_);
  4771. ctx_ = nullptr;
  4772. }
  4773. }
  4774. }
  4775. inline SSLClient::SSLClient(const std::string &host, int port,
  4776. X509 *client_cert, EVP_PKEY *client_key)
  4777. : ClientImpl(host, port) {
  4778. ctx_ = SSL_CTX_new(SSLv23_client_method());
  4779. detail::split(&host_[0], &host_[host_.size()], '.',
  4780. [&](const char *b, const char *e) {
  4781. host_components_.emplace_back(std::string(b, e));
  4782. });
  4783. if (client_cert != nullptr && client_key != nullptr) {
  4784. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  4785. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  4786. SSL_CTX_free(ctx_);
  4787. ctx_ = nullptr;
  4788. }
  4789. }
  4790. }
  4791. inline SSLClient::~SSLClient() {
  4792. if (ctx_) { SSL_CTX_free(ctx_); }
  4793. }
  4794. inline bool SSLClient::is_valid() const { return ctx_; }
  4795. inline void SSLClient::set_ca_cert_path(const char *ca_cert_file_path,
  4796. const char *ca_cert_dir_path) {
  4797. if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
  4798. if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
  4799. }
  4800. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  4801. if (ca_cert_store) { ca_cert_store_ = ca_cert_store; }
  4802. }
  4803. inline void SSLClient::enable_server_certificate_verification(bool enabled) {
  4804. server_certificate_verification_ = enabled;
  4805. }
  4806. inline long SSLClient::get_openssl_verify_result() const {
  4807. return verify_result_;
  4808. }
  4809. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  4810. inline bool SSLClient::create_and_connect_socket(Socket &socket) {
  4811. return is_valid() && ClientImpl::create_and_connect_socket(socket);
  4812. }
  4813. inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res,
  4814. bool &success) {
  4815. success = true;
  4816. Response res2;
  4817. if (!detail::process_client_socket(
  4818. socket.sock, read_timeout_sec_, read_timeout_usec_,
  4819. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  4820. Request req2;
  4821. req2.method = "CONNECT";
  4822. req2.path = host_and_port_;
  4823. return process_request(strm, req2, res2, false);
  4824. })) {
  4825. close_socket(socket, true);
  4826. success = false;
  4827. return false;
  4828. }
  4829. if (res2.status == 407) {
  4830. if (!proxy_digest_auth_username_.empty() &&
  4831. !proxy_digest_auth_password_.empty()) {
  4832. std::map<std::string, std::string> auth;
  4833. if (parse_www_authenticate(res2, auth, true)) {
  4834. Response res3;
  4835. if (!detail::process_client_socket(
  4836. socket.sock, read_timeout_sec_, read_timeout_usec_,
  4837. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  4838. Request req3;
  4839. req3.method = "CONNECT";
  4840. req3.path = host_and_port_;
  4841. req3.headers.insert(make_digest_authentication_header(
  4842. req3, auth, 1, random_string(10),
  4843. proxy_digest_auth_username_, proxy_digest_auth_password_,
  4844. true));
  4845. return process_request(strm, req3, res3, false);
  4846. })) {
  4847. close_socket(socket, true);
  4848. success = false;
  4849. return false;
  4850. }
  4851. }
  4852. } else {
  4853. res = res2;
  4854. return false;
  4855. }
  4856. }
  4857. return true;
  4858. }
  4859. inline bool SSLClient::load_certs() {
  4860. bool ret = true;
  4861. std::call_once(initialize_cert_, [&]() {
  4862. std::lock_guard<std::mutex> guard(ctx_mutex_);
  4863. if (!ca_cert_file_path_.empty()) {
  4864. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  4865. nullptr)) {
  4866. ret = false;
  4867. }
  4868. } else if (!ca_cert_dir_path_.empty()) {
  4869. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  4870. ca_cert_dir_path_.c_str())) {
  4871. ret = false;
  4872. }
  4873. } else if (ca_cert_store_ != nullptr) {
  4874. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store_) {
  4875. SSL_CTX_set_cert_store(ctx_, ca_cert_store_);
  4876. }
  4877. } else {
  4878. #ifdef _WIN32
  4879. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  4880. #else
  4881. SSL_CTX_set_default_verify_paths(ctx_);
  4882. #endif
  4883. }
  4884. });
  4885. return ret;
  4886. }
  4887. inline bool SSLClient::initialize_ssl(Socket &socket) {
  4888. auto ssl = detail::ssl_new(
  4889. socket.sock, ctx_, ctx_mutex_,
  4890. [&](SSL *ssl) {
  4891. if (server_certificate_verification_) {
  4892. if (!load_certs()) {
  4893. error_ = Error::SSLLoadingCerts;
  4894. return false;
  4895. }
  4896. SSL_set_verify(ssl, SSL_VERIFY_NONE, nullptr);
  4897. }
  4898. if (SSL_connect(ssl) != 1) {
  4899. error_ = Error::SSLConnection;
  4900. return false;
  4901. }
  4902. if (server_certificate_verification_) {
  4903. verify_result_ = SSL_get_verify_result(ssl);
  4904. if (verify_result_ != X509_V_OK) {
  4905. error_ = Error::SSLServerVerification;
  4906. return false;
  4907. }
  4908. auto server_cert = SSL_get_peer_certificate(ssl);
  4909. if (server_cert == nullptr) {
  4910. error_ = Error::SSLServerVerification;
  4911. return false;
  4912. }
  4913. if (!verify_host(server_cert)) {
  4914. X509_free(server_cert);
  4915. error_ = Error::SSLServerVerification;
  4916. return false;
  4917. }
  4918. X509_free(server_cert);
  4919. }
  4920. return true;
  4921. },
  4922. [&](SSL *ssl) {
  4923. SSL_set_tlsext_host_name(ssl, host_.c_str());
  4924. return true;
  4925. });
  4926. if (ssl) {
  4927. socket.ssl = ssl;
  4928. return true;
  4929. }
  4930. close_socket(socket, false);
  4931. return false;
  4932. }
  4933. inline void SSLClient::close_socket(Socket &socket, bool process_socket_ret) {
  4934. detail::close_socket(socket.sock);
  4935. socket_.sock = INVALID_SOCKET;
  4936. if (socket.ssl) {
  4937. detail::ssl_delete(ctx_mutex_, socket.ssl, process_socket_ret);
  4938. socket_.ssl = nullptr;
  4939. }
  4940. }
  4941. inline bool
  4942. SSLClient::process_socket(Socket &socket,
  4943. std::function<bool(Stream &strm)> callback) {
  4944. assert(socket.ssl);
  4945. return detail::process_client_socket_ssl(
  4946. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  4947. write_timeout_sec_, write_timeout_usec_, callback);
  4948. }
  4949. inline bool SSLClient::is_ssl() const { return true; }
  4950. inline bool SSLClient::verify_host(X509 *server_cert) const {
  4951. /* Quote from RFC2818 section 3.1 "Server Identity"
  4952. If a subjectAltName extension of type dNSName is present, that MUST
  4953. be used as the identity. Otherwise, the (most specific) Common Name
  4954. field in the Subject field of the certificate MUST be used. Although
  4955. the use of the Common Name is existing practice, it is deprecated and
  4956. Certification Authorities are encouraged to use the dNSName instead.
  4957. Matching is performed using the matching rules specified by
  4958. [RFC2459]. If more than one identity of a given type is present in
  4959. the certificate (e.g., more than one dNSName name, a match in any one
  4960. of the set is considered acceptable.) Names may contain the wildcard
  4961. character * which is considered to match any single domain name
  4962. component or component fragment. E.g., *.a.com matches foo.a.com but
  4963. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  4964. In some cases, the URI is specified as an IP address rather than a
  4965. hostname. In this case, the iPAddress subjectAltName must be present
  4966. in the certificate and must exactly match the IP in the URI.
  4967. */
  4968. return verify_host_with_subject_alt_name(server_cert) ||
  4969. verify_host_with_common_name(server_cert);
  4970. }
  4971. inline bool
  4972. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  4973. auto ret = false;
  4974. auto type = GEN_DNS;
  4975. struct in6_addr addr6;
  4976. struct in_addr addr;
  4977. size_t addr_len = 0;
  4978. #ifndef __MINGW32__
  4979. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  4980. type = GEN_IPADD;
  4981. addr_len = sizeof(struct in6_addr);
  4982. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  4983. type = GEN_IPADD;
  4984. addr_len = sizeof(struct in_addr);
  4985. }
  4986. #endif
  4987. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  4988. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  4989. if (alt_names) {
  4990. auto dsn_matched = false;
  4991. auto ip_mached = false;
  4992. auto count = sk_GENERAL_NAME_num(alt_names);
  4993. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  4994. auto val = sk_GENERAL_NAME_value(alt_names, i);
  4995. if (val->type == type) {
  4996. auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
  4997. auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
  4998. if (strlen(name) == name_len) {
  4999. switch (type) {
  5000. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  5001. case GEN_IPADD:
  5002. if (!memcmp(&addr6, name, addr_len) ||
  5003. !memcmp(&addr, name, addr_len)) {
  5004. ip_mached = true;
  5005. }
  5006. break;
  5007. }
  5008. }
  5009. }
  5010. }
  5011. if (dsn_matched || ip_mached) { ret = true; }
  5012. }
  5013. GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
  5014. return ret;
  5015. }
  5016. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  5017. const auto subject_name = X509_get_subject_name(server_cert);
  5018. if (subject_name != nullptr) {
  5019. char name[BUFSIZ];
  5020. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5021. name, sizeof(name));
  5022. if (name_len != -1) {
  5023. return check_host_name(name, static_cast<size_t>(name_len));
  5024. }
  5025. }
  5026. return false;
  5027. }
  5028. inline bool SSLClient::check_host_name(const char *pattern,
  5029. size_t pattern_len) const {
  5030. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  5031. // Wildcard match
  5032. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  5033. std::vector<std::string> pattern_components;
  5034. detail::split(&pattern[0], &pattern[pattern_len], '.',
  5035. [&](const char *b, const char *e) {
  5036. pattern_components.emplace_back(std::string(b, e));
  5037. });
  5038. if (host_components_.size() != pattern_components.size()) { return false; }
  5039. auto itr = pattern_components.begin();
  5040. for (const auto &h : host_components_) {
  5041. auto &p = *itr;
  5042. if (p != h && p != "*") {
  5043. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  5044. !p.compare(0, p.size() - 1, h));
  5045. if (!partial_match) { return false; }
  5046. }
  5047. ++itr;
  5048. }
  5049. return true;
  5050. }
  5051. #endif
  5052. // Universal client implementation
  5053. inline Client::Client(const char *scheme_host_port)
  5054. : Client(scheme_host_port, std::string(), std::string()) {}
  5055. inline Client::Client(const char *scheme_host_port,
  5056. const std::string &client_cert_path,
  5057. const std::string &client_key_path) {
  5058. const static std::regex re(R"(^(?:([a-z]+)://)?([^:/?#]+)(?::(\d+))?)");
  5059. std::cmatch m;
  5060. if (std::regex_match(scheme_host_port, m, re)) {
  5061. auto scheme = m[1].str();
  5062. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5063. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  5064. #else
  5065. if (!scheme.empty() && scheme != "http") {
  5066. #endif
  5067. return;
  5068. }
  5069. auto is_ssl = scheme == "https";
  5070. auto host = m[2].str();
  5071. auto port_str = m[3].str();
  5072. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  5073. if (is_ssl) {
  5074. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5075. cli_ = std::make_shared<SSLClient>(host.c_str(), port, client_cert_path,
  5076. client_key_path);
  5077. is_ssl_ = is_ssl;
  5078. #endif
  5079. } else {
  5080. cli_ = std::make_shared<ClientImpl>(host.c_str(), port, client_cert_path,
  5081. client_key_path);
  5082. }
  5083. } else {
  5084. cli_ = std::make_shared<ClientImpl>(scheme_host_port, 80, client_cert_path,
  5085. client_key_path);
  5086. }
  5087. }
  5088. inline Client::Client(const std::string &host, int port)
  5089. : cli_(std::make_shared<ClientImpl>(host, port)) {}
  5090. inline Client::Client(const std::string &host, int port,
  5091. const std::string &client_cert_path,
  5092. const std::string &client_key_path)
  5093. : cli_(std::make_shared<ClientImpl>(host, port, client_cert_path,
  5094. client_key_path)) {}
  5095. inline Client::~Client() {}
  5096. inline bool Client::is_valid() const {
  5097. return cli_ != nullptr && cli_->is_valid();
  5098. }
  5099. inline Result Client::Get(const char *path) { return cli_->Get(path); }
  5100. inline Result Client::Get(const char *path, const Headers &headers) {
  5101. return cli_->Get(path, headers);
  5102. }
  5103. inline Result Client::Get(const char *path, Progress progress) {
  5104. return cli_->Get(path, progress);
  5105. }
  5106. inline Result Client::Get(const char *path, const Headers &headers,
  5107. Progress progress) {
  5108. return cli_->Get(path, headers, progress);
  5109. }
  5110. inline Result Client::Get(const char *path, ContentReceiver content_receiver) {
  5111. return cli_->Get(path, std::move(content_receiver));
  5112. }
  5113. inline Result Client::Get(const char *path, const Headers &headers,
  5114. ContentReceiver content_receiver) {
  5115. return cli_->Get(path, headers, std::move(content_receiver));
  5116. }
  5117. inline Result Client::Get(const char *path, ContentReceiver content_receiver,
  5118. Progress progress) {
  5119. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  5120. }
  5121. inline Result Client::Get(const char *path, const Headers &headers,
  5122. ContentReceiver content_receiver, Progress progress) {
  5123. return cli_->Get(path, headers, std::move(content_receiver),
  5124. std::move(progress));
  5125. }
  5126. inline Result Client::Get(const char *path, ResponseHandler response_handler,
  5127. ContentReceiver content_receiver) {
  5128. return cli_->Get(path, std::move(response_handler),
  5129. std::move(content_receiver));
  5130. }
  5131. inline Result Client::Get(const char *path, const Headers &headers,
  5132. ResponseHandler response_handler,
  5133. ContentReceiver content_receiver) {
  5134. return cli_->Get(path, headers, std::move(response_handler),
  5135. std::move(content_receiver));
  5136. }
  5137. inline Result Client::Get(const char *path, ResponseHandler response_handler,
  5138. ContentReceiver content_receiver, Progress progress) {
  5139. return cli_->Get(path, std::move(response_handler),
  5140. std::move(content_receiver), std::move(progress));
  5141. }
  5142. inline Result Client::Get(const char *path, const Headers &headers,
  5143. ResponseHandler response_handler,
  5144. ContentReceiver content_receiver, Progress progress) {
  5145. return cli_->Get(path, headers, response_handler, content_receiver, progress);
  5146. }
  5147. inline Result Client::Head(const char *path) { return cli_->Head(path); }
  5148. inline Result Client::Head(const char *path, const Headers &headers) {
  5149. return cli_->Head(path, headers);
  5150. }
  5151. inline Result Client::Post(const char *path) { return cli_->Post(path); }
  5152. inline Result Client::Post(const char *path, const std::string &body,
  5153. const char *content_type) {
  5154. return cli_->Post(path, body, content_type);
  5155. }
  5156. inline Result Client::Post(const char *path, const Headers &headers,
  5157. const std::string &body, const char *content_type) {
  5158. return cli_->Post(path, headers, body, content_type);
  5159. }
  5160. inline Result Client::Post(const char *path, size_t content_length,
  5161. ContentProvider content_provider,
  5162. const char *content_type) {
  5163. return cli_->Post(path, content_length, content_provider, content_type);
  5164. }
  5165. inline Result Client::Post(const char *path, const Headers &headers,
  5166. size_t content_length,
  5167. ContentProvider content_provider,
  5168. const char *content_type) {
  5169. return cli_->Post(path, headers, content_length, content_provider,
  5170. content_type);
  5171. }
  5172. inline Result Client::Post(const char *path, const Params &params) {
  5173. return cli_->Post(path, params);
  5174. }
  5175. inline Result Client::Post(const char *path, const Headers &headers,
  5176. const Params &params) {
  5177. return cli_->Post(path, headers, params);
  5178. }
  5179. inline Result Client::Post(const char *path,
  5180. const MultipartFormDataItems &items) {
  5181. return cli_->Post(path, items);
  5182. }
  5183. inline Result Client::Post(const char *path, const Headers &headers,
  5184. const MultipartFormDataItems &items) {
  5185. return cli_->Post(path, headers, items);
  5186. }
  5187. inline Result Client::Put(const char *path) { return cli_->Put(path); }
  5188. inline Result Client::Put(const char *path, const std::string &body,
  5189. const char *content_type) {
  5190. return cli_->Put(path, body, content_type);
  5191. }
  5192. inline Result Client::Put(const char *path, const Headers &headers,
  5193. const std::string &body, const char *content_type) {
  5194. return cli_->Put(path, headers, body, content_type);
  5195. }
  5196. inline Result Client::Put(const char *path, size_t content_length,
  5197. ContentProvider content_provider,
  5198. const char *content_type) {
  5199. return cli_->Put(path, content_length, content_provider, content_type);
  5200. }
  5201. inline Result Client::Put(const char *path, const Headers &headers,
  5202. size_t content_length,
  5203. ContentProvider content_provider,
  5204. const char *content_type) {
  5205. return cli_->Put(path, headers, content_length, content_provider,
  5206. content_type);
  5207. }
  5208. inline Result Client::Put(const char *path, const Params &params) {
  5209. return cli_->Put(path, params);
  5210. }
  5211. inline Result Client::Put(const char *path, const Headers &headers,
  5212. const Params &params) {
  5213. return cli_->Put(path, headers, params);
  5214. }
  5215. inline Result Client::Patch(const char *path, const std::string &body,
  5216. const char *content_type) {
  5217. return cli_->Patch(path, body, content_type);
  5218. }
  5219. inline Result Client::Patch(const char *path, const Headers &headers,
  5220. const std::string &body, const char *content_type) {
  5221. return cli_->Patch(path, headers, body, content_type);
  5222. }
  5223. inline Result Client::Patch(const char *path, size_t content_length,
  5224. ContentProvider content_provider,
  5225. const char *content_type) {
  5226. return cli_->Patch(path, content_length, content_provider, content_type);
  5227. }
  5228. inline Result Client::Patch(const char *path, const Headers &headers,
  5229. size_t content_length,
  5230. ContentProvider content_provider,
  5231. const char *content_type) {
  5232. return cli_->Patch(path, headers, content_length, content_provider,
  5233. content_type);
  5234. }
  5235. inline Result Client::Delete(const char *path) { return cli_->Delete(path); }
  5236. inline Result Client::Delete(const char *path, const std::string &body,
  5237. const char *content_type) {
  5238. return cli_->Delete(path, body, content_type);
  5239. }
  5240. inline Result Client::Delete(const char *path, const Headers &headers) {
  5241. return cli_->Delete(path, headers);
  5242. }
  5243. inline Result Client::Delete(const char *path, const Headers &headers,
  5244. const std::string &body,
  5245. const char *content_type) {
  5246. return cli_->Delete(path, headers, body, content_type);
  5247. }
  5248. inline Result Client::Options(const char *path) { return cli_->Options(path); }
  5249. inline Result Client::Options(const char *path, const Headers &headers) {
  5250. return cli_->Options(path, headers);
  5251. }
  5252. inline bool Client::send(const Request &req, Response &res) {
  5253. return cli_->send(req, res);
  5254. }
  5255. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  5256. inline void Client::stop() { cli_->stop(); }
  5257. inline void Client::set_default_headers(Headers headers) {
  5258. cli_->set_default_headers(std::move(headers));
  5259. }
  5260. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  5261. inline void Client::set_socket_options(SocketOptions socket_options) {
  5262. cli_->set_socket_options(socket_options);
  5263. }
  5264. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  5265. cli_->set_connection_timeout(sec, usec);
  5266. }
  5267. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  5268. cli_->set_read_timeout(sec, usec);
  5269. }
  5270. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  5271. cli_->set_write_timeout(sec, usec);
  5272. }
  5273. inline void Client::set_basic_auth(const char *username, const char *password) {
  5274. cli_->set_basic_auth(username, password);
  5275. }
  5276. inline void Client::set_bearer_token_auth(const char *token) {
  5277. cli_->set_bearer_token_auth(token);
  5278. }
  5279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5280. inline void Client::set_digest_auth(const char *username,
  5281. const char *password) {
  5282. cli_->set_digest_auth(username, password);
  5283. }
  5284. #endif
  5285. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  5286. inline void Client::set_follow_location(bool on) {
  5287. cli_->set_follow_location(on);
  5288. }
  5289. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  5290. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  5291. inline void Client::set_interface(const char *intf) {
  5292. cli_->set_interface(intf);
  5293. }
  5294. inline void Client::set_proxy(const char *host, int port) {
  5295. cli_->set_proxy(host, port);
  5296. }
  5297. inline void Client::set_proxy_basic_auth(const char *username,
  5298. const char *password) {
  5299. cli_->set_proxy_basic_auth(username, password);
  5300. }
  5301. inline void Client::set_proxy_bearer_token_auth(const char *token) {
  5302. cli_->set_proxy_bearer_token_auth(token);
  5303. }
  5304. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5305. inline void Client::set_proxy_digest_auth(const char *username,
  5306. const char *password) {
  5307. cli_->set_proxy_digest_auth(username, password);
  5308. }
  5309. #endif
  5310. inline void Client::set_logger(Logger logger) { cli_->set_logger(logger); }
  5311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5312. inline Client &Client::set_ca_cert_path(const char *ca_cert_file_path,
  5313. const char *ca_cert_dir_path) {
  5314. if (is_ssl_) {
  5315. static_cast<SSLClient &>(*cli_).set_ca_cert_path(ca_cert_file_path,
  5316. ca_cert_dir_path);
  5317. }
  5318. return *this;
  5319. }
  5320. inline Client &Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  5321. if (is_ssl_) {
  5322. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  5323. }
  5324. return *this;
  5325. }
  5326. inline Client &Client::enable_server_certificate_verification(bool enabled) {
  5327. if (is_ssl_) {
  5328. static_cast<SSLClient &>(*cli_).enable_server_certificate_verification(
  5329. enabled);
  5330. }
  5331. return *this;
  5332. }
  5333. inline long Client::get_openssl_verify_result() const {
  5334. if (is_ssl_) {
  5335. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  5336. }
  5337. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  5338. }
  5339. inline SSL_CTX *Client::ssl_context() const {
  5340. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  5341. return nullptr;
  5342. }
  5343. #endif
  5344. // ----------------------------------------------------------------------------
  5345. } // namespace httplib
  5346. #endif // CPPHTTPLIB_HTTPLIB_H