test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. #ifndef _WIN32
  253. TEST(SocketStream, wait_writable_UNIX) {
  254. int fds[2];
  255. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  256. const auto asSocketStream = [&](socket_t fd,
  257. std::function<bool(Stream &)> func) {
  258. return detail::process_client_socket(
  259. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  260. };
  261. asSocketStream(fds[0], [&](Stream &s0) {
  262. EXPECT_EQ(s0.socket(), fds[0]);
  263. EXPECT_TRUE(s0.wait_writable());
  264. EXPECT_TRUE(s0.is_peer_alive());
  265. EXPECT_EQ(0, close(fds[1]));
  266. EXPECT_FALSE(s0.is_peer_alive());
  267. return true;
  268. });
  269. EXPECT_EQ(0, close(fds[0]));
  270. }
  271. TEST(SocketStream, wait_writable_INET) {
  272. sockaddr_in addr;
  273. memset(&addr, 0, sizeof(addr));
  274. addr.sin_family = AF_INET;
  275. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  276. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  277. int disconnected_svr_sock = -1;
  278. std::thread svr{[&] {
  279. const int s = socket(AF_INET, SOCK_STREAM, 0);
  280. ASSERT_LE(0, s);
  281. // PORT + 1 is shared with the SSL redirect tests and with
  282. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  283. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  284. // because that happens on a worker thread the ASSERT does not stop the
  285. // test: it runs on and fails at the disconnected_svr_sock check instead.
  286. default_socket_options(s);
  287. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  288. ASSERT_EQ(0, listen(s, 1));
  289. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  290. ASSERT_EQ(0, close(s));
  291. }};
  292. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  293. std::thread cli{[&] {
  294. const int s = socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_LE(0, s);
  296. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  297. ASSERT_EQ(0, close(s));
  298. }};
  299. cli.join();
  300. svr.join();
  301. ASSERT_NE(disconnected_svr_sock, -1);
  302. const auto asSocketStream = [&](socket_t fd,
  303. std::function<bool(Stream &)> func) {
  304. return detail::process_client_socket(
  305. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  306. };
  307. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  308. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  309. // wait_writable() returns true because select_write() only checks if the
  310. // send buffer has space. Peer disconnection is detected later by send().
  311. EXPECT_TRUE(ss.wait_writable());
  312. return true;
  313. });
  314. ASSERT_EQ(0, close(disconnected_svr_sock));
  315. }
  316. #endif // #ifndef _WIN32
  317. TEST(SetSocketOptTest, TcpNoDelay) {
  318. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  319. ASSERT_NE(sock, INVALID_SOCKET);
  320. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  321. int val = 0;
  322. socklen_t len = sizeof(val);
  323. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  324. reinterpret_cast<char *>(&val), &len));
  325. EXPECT_NE(val, 0);
  326. detail::close_socket(sock);
  327. }
  328. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  329. // accept() reports failures through WSAGetLastError() on Windows and through
  330. // errno everywhere else. Asking the wrong one is what made the accept loop
  331. // treat every recoverable failure as fatal on Windows.
  332. struct Classification {
  333. bool resource;
  334. bool transient;
  335. };
  336. auto classify = [](int err) {
  337. #ifdef _WIN32
  338. WSASetLastError(err);
  339. #else
  340. errno = err;
  341. #endif
  342. // Read both before asserting: an assertion may clobber the error slot.
  343. Classification c;
  344. c.resource = detail::is_accept_resource_error();
  345. c.transient = detail::is_accept_transient_error();
  346. return c;
  347. };
  348. #ifdef _WIN32
  349. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  350. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  351. WSAECONNRESET, WSAECONNABORTED};
  352. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  353. #else
  354. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  355. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  356. ECONNABORTED};
  357. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  358. #endif
  359. for (auto err : resource_errors) {
  360. const auto c = classify(err);
  361. EXPECT_TRUE(c.resource) << "error " << err;
  362. EXPECT_FALSE(c.transient) << "error " << err;
  363. }
  364. for (auto err : transient_errors) {
  365. const auto c = classify(err);
  366. EXPECT_TRUE(c.transient) << "error " << err;
  367. EXPECT_FALSE(c.resource) << "error " << err;
  368. }
  369. for (auto err : fatal_errors) {
  370. const auto c = classify(err);
  371. EXPECT_FALSE(c.resource) << "error " << err;
  372. EXPECT_FALSE(c.transient) << "error " << err;
  373. }
  374. #ifdef _WIN32
  375. WSASetLastError(0);
  376. #else
  377. errno = 0;
  378. #endif
  379. }
  380. TEST(ClientTest, MoveConstructible) {
  381. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  382. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  383. }
  384. TEST(ClientTest, MoveAssignable) {
  385. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  386. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  387. }
  388. #ifdef _WIN32
  389. TEST(StartupTest, WSAStartup) {
  390. WSADATA wsaData;
  391. int ret = WSAStartup(0x0002, &wsaData);
  392. ASSERT_EQ(0, ret);
  393. }
  394. #endif
  395. TEST(DecodePathTest, PercentCharacter) {
  396. EXPECT_EQ(
  397. decode_path_component(
  398. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  399. U8("descrip=Gastos áéíóúñÑ 6"));
  400. }
  401. TEST(DecodePathTest, PercentCharacterNUL) {
  402. string expected;
  403. expected.push_back('x');
  404. expected.push_back('\0');
  405. expected.push_back('x');
  406. EXPECT_EQ(decode_path_component("x%00x"), expected);
  407. }
  408. TEST(DecodePathTest, UnicodeEncoding) {
  409. // %u0041 = 'A' (1-byte UTF-8)
  410. EXPECT_EQ("A", decode_path_component("%u0041"));
  411. // %u00E9 = 'é' (2-byte UTF-8)
  412. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  413. // %u3042 = 'あ' (3-byte UTF-8)
  414. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  415. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  416. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  417. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  418. // neighbours)
  419. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  420. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  421. }
  422. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  423. // A sign or whitespace inside the two-character escape window must not be
  424. // accepted as a valid percent-encoding; the sequence is passed through
  425. // literally, matching decode_uri_component / decode_path_component.
  426. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  427. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  428. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  429. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  430. // Well-formed escapes still decode.
  431. EXPECT_EQ("-", decode_query_component("%2D", false));
  432. EXPECT_EQ("A", decode_query_component("%41", false));
  433. }
  434. TEST(SanitizeFilenameTest, VariousPatterns) {
  435. // Path traversal
  436. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  437. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  438. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  439. // Normal and edge cases
  440. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  441. EXPECT_EQ("filename.txt",
  442. httplib::sanitize_filename("/path/to/filename.txt"));
  443. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  444. EXPECT_EQ("", httplib::sanitize_filename(".."));
  445. EXPECT_EQ("", httplib::sanitize_filename(""));
  446. // Null bytes stripped
  447. EXPECT_EQ("safe.txt",
  448. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  449. // Whitespace-only rejected
  450. EXPECT_EQ("", httplib::sanitize_filename(" "));
  451. }
  452. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  453. // before it is dropped; anywhere else it is an ordinary file name character.
  454. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  455. #ifdef _WIN32
  456. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  457. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  458. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  459. #else
  460. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  461. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  462. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  463. #endif
  464. }
  465. // Forward declaration (see the base64_encode note below): split builds move the
  466. // definition into httplib.cc, so re-declaring it here lets the test link.
  467. namespace httplib {
  468. namespace detail {
  469. bool is_chunked_transfer_encoding(const Headers &headers);
  470. } // namespace detail
  471. } // namespace httplib
  472. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  473. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  474. auto make = [](std::initializer_list<const char *> lines) {
  475. Headers h;
  476. for (auto te : lines) {
  477. if (te) { h.emplace("Transfer-Encoding", te); }
  478. }
  479. return h;
  480. };
  481. // Sole coding, matched case-insensitively.
  482. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  483. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  484. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  485. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  486. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  487. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  488. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  489. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  490. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  491. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  492. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  493. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  494. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  495. // were received, into one list. Headers preserves that order, so the answer
  496. // is decided by the last coding of the last line and the order the lines
  497. // arrived in is significant.
  498. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  499. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  500. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  501. // The split can fall anywhere in the list.
  502. EXPECT_TRUE(
  503. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  504. EXPECT_FALSE(
  505. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  506. // A trailing line naming no coding leaves the list ending in nothing, so it
  507. // must not inherit the chunked from the line before it.
  508. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  509. }
  510. // Forward declarations (see the base64_encode note below).
  511. namespace httplib {
  512. namespace detail {
  513. bool parse_status_line(const char *line, std::string &version, int &status,
  514. std::string &reason);
  515. std::string file_extension(const std::string &path);
  516. std::string
  517. find_content_type(const std::string &path,
  518. const std::map<std::string, std::string> &user_data,
  519. const std::string &default_content_type);
  520. bool can_compress_content_type(const std::string &content_type);
  521. bool is_prohibited_header_name(const std::string &name);
  522. bool is_valid_path(const std::string &path);
  523. #ifdef CPPHTTPLIB_SSL_ENABLED
  524. bool match_hostname(const std::string &pattern, const std::string &hostname);
  525. #endif
  526. } // namespace detail
  527. } // namespace httplib
  528. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  529. struct {
  530. const char *line;
  531. const char *version;
  532. int status;
  533. const char *reason;
  534. } cases[] = {
  535. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  536. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  537. // The reason phrase may be empty, or left out along with its space.
  538. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  539. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  540. };
  541. for (const auto &c : cases) {
  542. std::string version;
  543. int status = 0;
  544. std::string reason = "unset";
  545. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  546. << c.line;
  547. EXPECT_EQ(c.version, version);
  548. EXPECT_EQ(c.status, status);
  549. EXPECT_EQ(c.reason, reason);
  550. }
  551. }
  552. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  553. const char *lines[] = {
  554. "HTTP/2 200 OK\r\n",
  555. "HTTP/1.2 200 OK\r\n",
  556. "HTTP/1.1 20 OK\r\n",
  557. "HTTP/1.1 2000 OK\r\n",
  558. "HTTP/1.1 2x0 OK\r\n",
  559. "HTTP/1.1 200 OK\r\n",
  560. "HTTP/1.1 200OK\r\n",
  561. "HTTP/1.1 200 O\rK\r\n",
  562. "HTTP/1.1 200 OK",
  563. "HTTP/1.1 200 OK\r\nX",
  564. "",
  565. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  566. "HTTP/1.1 200 OK\n",
  567. #endif
  568. };
  569. for (auto line : lines) {
  570. std::string version;
  571. int status = 0;
  572. std::string reason;
  573. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  574. << line;
  575. }
  576. }
  577. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  578. // Long enough to overflow the stack when matched with std::regex.
  579. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  580. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  581. std::string version;
  582. int status = 0;
  583. std::string reason;
  584. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  585. EXPECT_EQ(200, status);
  586. EXPECT_EQ(long_reason, reason);
  587. }
  588. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  589. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  590. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  591. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  592. EXPECT_EQ("", detail::file_extension("noext"));
  593. EXPECT_EQ("", detail::file_extension("a."));
  594. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  595. EXPECT_EQ("", detail::file_extension("a.b-c"));
  596. // Long enough to overflow the stack when matched with std::regex.
  597. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  598. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  599. }
  600. #ifdef CPPHTTPLIB_SSL_ENABLED
  601. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  602. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  603. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  604. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  605. // A wildcard needs two labels after it, in the leftmost label only
  606. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  607. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  608. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  609. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  610. EXPECT_FALSE(
  611. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  612. // No name may have an empty label
  613. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  614. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  615. }
  616. #endif
  617. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  618. detail::case_ignore::hash hash;
  619. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  620. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  621. // Long enough to overflow the stack if hashed one call per character.
  622. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  623. }
  624. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  625. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  626. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  627. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  628. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  629. // Same 26-bit hash as html, svg and js.
  630. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  631. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  632. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  633. }
  634. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  635. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  636. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  637. }
  638. }
  639. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  640. // name anywhere else.
  641. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  642. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  643. #ifdef _WIN32
  644. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  645. #else
  646. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  647. #endif
  648. }
  649. }
  650. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  651. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  652. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  653. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  654. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  655. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  656. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  657. // Same 26-bit hash as application/json.
  658. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  659. }
  660. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  661. Request req;
  662. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  663. EXPECT_TRUE(req.is_multipart_form_data());
  664. std::string boundary;
  665. EXPECT_TRUE(detail::parse_multipart_boundary(
  666. req.get_header_value("Content-Type"), boundary));
  667. EXPECT_EQ("x", boundary);
  668. }
  669. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  670. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  671. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  672. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  673. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  674. // Same 26-bit hash as REMOTE_ADDR.
  675. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  676. }
  677. // Forward declaration: in split builds split.py strips `inline` and moves the
  678. // definition into httplib.cc, so detail::base64_encode is not visible from the
  679. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  680. // in both header-only and split builds.
  681. namespace httplib {
  682. namespace detail {
  683. std::string base64_encode(const std::string &in);
  684. } // namespace detail
  685. } // namespace httplib
  686. TEST(Base64EncodeTest, KnownAnswers) {
  687. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  688. // where the accumulator's top bit is already set before the next shift.
  689. EXPECT_EQ("", detail::base64_encode(""));
  690. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  691. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  692. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  693. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  694. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  695. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  696. // High bytes keep the top bit set across several rounds.
  697. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  698. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  699. }
  700. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  701. string unescapedCharacters = "-_.!~*'()";
  702. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  703. }
  704. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  705. string reservedCharacters = ";,/?:@&=+$";
  706. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  707. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  708. }
  709. TEST(ClientQueryOrder, PreserveOrder) {
  710. // This test reproduces Issue #2259: client may reorder query parameters
  711. // when sending a GET request. The expected behavior is that the client
  712. // preserves the original query string order when the caller supplied it
  713. // as part of the path.
  714. Server svr;
  715. svr.Get("/", [&](const Request &req, Response &res) {
  716. // Echo back the raw target so the test can assert ordering
  717. res.set_content(req.target, "text/plain");
  718. });
  719. std::thread t{[&] { svr.listen(HOST, PORT); }};
  720. auto se = detail::scope_exit([&] {
  721. svr.stop();
  722. t.join();
  723. ASSERT_FALSE(svr.is_running());
  724. });
  725. svr.wait_until_ready();
  726. Client cli(HOST, PORT);
  727. ASSERT_TRUE(cli.is_valid());
  728. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  729. auto res = cli.Get(original);
  730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  731. // Expect the echoed target to exactly match the original path (order
  732. // preserved)
  733. EXPECT_EQ(res->body, original);
  734. }
  735. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  736. string chineseCharacters = U8("中国語");
  737. string russianCharacters = U8("дом");
  738. string brazilianCharacters = U8("óculos");
  739. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  740. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  741. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  742. "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  746. string unescapedCharacters = "-_.!~*'()";
  747. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  748. }
  749. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  750. string reservedCharacters = ";,/?:@&=+$";
  751. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  752. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  753. }
  754. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  755. string chineseCharacters = U8("中国語");
  756. string russianCharacters = U8("дом");
  757. string brazilianCharacters = U8("óculos");
  758. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  759. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  760. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  761. "%D0%B4%D0%BE%D0%BC");
  762. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  763. }
  764. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  765. // Issue #2082 use case: encoding path component with ampersand
  766. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  767. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  768. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  769. }
  770. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  775. string reservedCharacters = ";,/?:@&=+$#";
  776. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  777. }
  778. TEST(EncodeUriTest, TestUTF8Characters) {
  779. string chineseCharacters = U8("中国語");
  780. string russianCharacters = U8("дом");
  781. string brazilianCharacters = U8("óculos");
  782. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  783. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  784. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  785. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  786. }
  787. TEST(EncodeUriTest, TestCompleteUri) {
  788. string uri =
  789. "https://example.com/path/to/resource?query=value&param=test#fragment";
  790. EXPECT_EQ(
  791. httplib::encode_uri(uri),
  792. "https://example.com/path/to/resource?query=value&param=test#fragment");
  793. }
  794. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  795. string uri =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. EXPECT_EQ(httplib::encode_uri(uri),
  798. "https://example.com/path%20with%20spaces/"
  799. "file%20name.html?q=hello%20world");
  800. }
  801. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  802. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  803. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  804. }
  805. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  806. string unescapedCharacters = "-_.!~*'()";
  807. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  808. }
  809. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  810. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  811. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  812. string encodedBrazilian = "%C3%B3culos";
  813. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  814. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  815. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  816. }
  817. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  818. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  819. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  820. "Piri Tommy Villiers - on & on");
  821. }
  822. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  823. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  824. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  825. }
  826. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  827. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  828. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  829. }
  830. TEST(DecodeUriTest, TestUTF8Characters) {
  831. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  832. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  833. string encodedBrazilian = "%C3%B3culos";
  834. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  835. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  836. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  837. }
  838. TEST(DecodeUriTest, TestCompleteUri) {
  839. string encodedUri = "https://example.com/path%20with%20spaces/"
  840. "file%20name.html?q=hello%20world";
  841. EXPECT_EQ(
  842. httplib::decode_uri(encodedUri),
  843. "https://example.com/path with spaces/file name.html?q=hello world");
  844. }
  845. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  846. string original =
  847. "https://example.com/path with spaces/file name.html?q=hello world";
  848. string encoded = httplib::encode_uri(original);
  849. string decoded = httplib::decode_uri(encoded);
  850. EXPECT_EQ(decoded, original);
  851. }
  852. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  853. // decode_uri is the inverse of encode_uri: an escaped reserved character
  854. // stays encoded so it is not promoted into a real delimiter, while
  855. // non-reserved escapes still decode (like JS decodeURI).
  856. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  857. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  858. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  859. "%3F%3A%40%26%3D%2B%24%2C%3B");
  860. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  861. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  862. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  863. "http://example.com/a%2Fb");
  864. // decode_uri_component still decodes the reserved character.
  865. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  866. }
  867. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  868. string original = "Piri Tommy Villiers - on & on";
  869. string encoded = httplib::encode_uri_component(original);
  870. string decoded = httplib::decode_uri_component(encoded);
  871. EXPECT_EQ(decoded, original);
  872. }
  873. TEST(TrimTests, TrimStringTests) {
  874. EXPECT_EQ("abc", detail::trim_copy("abc"));
  875. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  876. EXPECT_TRUE(detail::trim_copy("").empty());
  877. }
  878. TEST(AsciiTest, LocaleIndependentClassification) {
  879. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  880. // which consult the global C locale: std::isalnum(0xC5) can return true
  881. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  882. // helpers must classify every byte by the ASCII grammar alone.
  883. for (int i = 0; i < 256; i++) {
  884. auto c = static_cast<char>(i);
  885. auto is_digit = i >= '0' && i <= '9';
  886. auto is_upper = i >= 'A' && i <= 'Z';
  887. auto is_lower = i >= 'a' && i <= 'z';
  888. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  889. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  890. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  891. << "byte " << i;
  892. }
  893. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  894. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  895. // Non-ASCII bytes must be percent-encoded, never passed through as
  896. // alphanumeric.
  897. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  898. }
  899. TEST(FromCharsTest, Double) {
  900. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  901. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  902. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  903. auto parse = [](const std::string &s, double &v) {
  904. return detail::from_chars(s.data(), s.data() + s.size(), v);
  905. };
  906. double v = -1.0;
  907. // Representative quality values.
  908. EXPECT_EQ(parse("0", v).ec, std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse("1", v).ec, std::errc{});
  911. EXPECT_DOUBLE_EQ(v, 1.0);
  912. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  913. EXPECT_DOUBLE_EQ(v, 0.8);
  914. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  915. EXPECT_DOUBLE_EQ(v, 0.001);
  916. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  917. EXPECT_DOUBLE_EQ(v, 1.0);
  918. // A missing integer or fractional part is tolerated.
  919. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  920. EXPECT_DOUBLE_EQ(v, 0.5);
  921. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  922. EXPECT_DOUBLE_EQ(v, 5.0);
  923. // Values outside [0, 1] still parse; the caller range-checks them.
  924. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  925. EXPECT_DOUBLE_EQ(v, 123.456);
  926. // Stops at the first byte that is not part of the number and reports where.
  927. std::string trailing = "0.9, text/html";
  928. auto r = parse(trailing, v);
  929. EXPECT_EQ(r.ec, std::errc{});
  930. EXPECT_DOUBLE_EQ(v, 0.9);
  931. EXPECT_EQ(*r.ptr, ',');
  932. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  933. // outright, and an 'e'/'E' simply ends the number.
  934. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  935. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  936. std::string exp_input = "1.5e3";
  937. r = parse(exp_input, v);
  938. EXPECT_EQ(r.ec, std::errc{});
  939. EXPECT_DOUBLE_EQ(v, 1.5);
  940. EXPECT_EQ(*r.ptr, 'e');
  941. // Invalid inputs.
  942. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  943. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  944. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  945. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  946. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  947. // Pathological but well-formed inputs must stay bounded (no overflow, no
  948. // out-of-bounds table access) and stay within [0, 1] for the caller.
  949. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  950. std::errc{});
  951. EXPECT_DOUBLE_EQ(v, 0.0);
  952. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  953. std::errc{});
  954. EXPECT_GE(v, 0.0);
  955. EXPECT_LE(v, 1.0);
  956. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  957. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  958. }
  959. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  960. // Simple case without quality values
  961. std::vector<std::string> result1;
  962. EXPECT_TRUE(detail::parse_accept_header(
  963. "text/html,application/json,text/plain", result1));
  964. EXPECT_EQ(result1.size(), 3U);
  965. EXPECT_EQ(result1[0], "text/html");
  966. EXPECT_EQ(result1[1], "application/json");
  967. EXPECT_EQ(result1[2], "text/plain");
  968. // With quality values
  969. std::vector<std::string> result2;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  972. EXPECT_EQ(result2.size(), 3U);
  973. EXPECT_EQ(result2[0], "application/json"); // highest q value
  974. EXPECT_EQ(result2[1], "text/html");
  975. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  976. }
  977. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  978. // Mixed with and without quality values
  979. std::vector<std::string> result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  982. EXPECT_EQ(result.size(), 3U);
  983. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  984. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  985. EXPECT_EQ(result[2], "application/json"); // q=0.5
  986. }
  987. TEST(ParseAcceptHeaderTest, EdgeCases) {
  988. // Empty header
  989. std::vector<std::string> empty_result;
  990. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  991. EXPECT_TRUE(empty_result.empty());
  992. // Single type
  993. std::vector<std::string> single_result;
  994. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  995. EXPECT_EQ(single_result.size(), 1U);
  996. EXPECT_EQ(single_result[0], "application/json");
  997. // Wildcard types
  998. std::vector<std::string> wildcard_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1001. EXPECT_EQ(wildcard_result.size(), 3U);
  1002. EXPECT_EQ(wildcard_result[0], "application/json");
  1003. EXPECT_EQ(wildcard_result[1], "text/*");
  1004. EXPECT_EQ(wildcard_result[2], "*/*");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1007. // Common browser Accept header
  1008. std::vector<std::string> browser_result;
  1009. EXPECT_TRUE(
  1010. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1011. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1012. browser_result));
  1013. EXPECT_EQ(browser_result.size(), 6U);
  1014. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1015. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1016. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1017. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1018. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1019. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1020. // API client header
  1021. std::vector<std::string> api_result;
  1022. EXPECT_TRUE(detail::parse_accept_header(
  1023. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1024. api_result));
  1025. EXPECT_EQ(api_result.size(), 3U);
  1026. EXPECT_EQ(api_result[0], "application/json");
  1027. EXPECT_EQ(api_result[1], "application/xml");
  1028. EXPECT_EQ(api_result[2], "text/plain");
  1029. }
  1030. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1031. // Quality value with 3 decimal places
  1032. std::vector<std::string> decimal_result;
  1033. EXPECT_TRUE(detail::parse_accept_header(
  1034. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1035. EXPECT_EQ(decimal_result.size(), 2U);
  1036. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1037. EXPECT_EQ(decimal_result[1], "text/html");
  1038. // Zero quality (should still be included but with lowest priority)
  1039. std::vector<std::string> zero_q_result;
  1040. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1041. zero_q_result));
  1042. EXPECT_EQ(zero_q_result.size(), 2U);
  1043. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1044. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1045. // No spaces around commas
  1046. std::vector<std::string> no_space_result;
  1047. EXPECT_TRUE(detail::parse_accept_header(
  1048. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1049. no_space_result));
  1050. EXPECT_EQ(no_space_result.size(), 3U);
  1051. EXPECT_EQ(no_space_result[0], "text/html");
  1052. EXPECT_EQ(no_space_result[1], "application/json");
  1053. EXPECT_EQ(no_space_result[2], "text/plain");
  1054. }
  1055. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1056. // Quality values always use '.' as the decimal separator, so parsing must
  1057. // not depend on the process locale. An embedding application may have
  1058. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1059. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1060. std::string saved = cur ? cur : "C";
  1061. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1062. "fr_FR.UTF-8"};
  1063. bool switched = false;
  1064. for (const auto loc : comma_locales) {
  1065. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1066. std::localeconv()->decimal_point[0] == ',') {
  1067. switched = true;
  1068. break;
  1069. }
  1070. }
  1071. if (!switched) {
  1072. std::setlocale(LC_NUMERIC, saved.c_str());
  1073. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1074. }
  1075. // The higher-weighted type appears later in the list, so a correct parse
  1076. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1077. // sensitive parse reads both weights as 0 and leaves the original order.
  1078. std::vector<std::string> result;
  1079. EXPECT_TRUE(detail::parse_accept_header(
  1080. "application/json;q=0.1,text/html;q=0.9", result));
  1081. ASSERT_EQ(result.size(), 2U);
  1082. EXPECT_EQ(result[0], "text/html");
  1083. EXPECT_EQ(result[1], "application/json");
  1084. std::setlocale(LC_NUMERIC, saved.c_str());
  1085. }
  1086. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1087. std::vector<std::string> result;
  1088. // Invalid quality value (> 1.0)
  1089. EXPECT_FALSE(
  1090. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1091. // Invalid quality value (< 0.0)
  1092. EXPECT_FALSE(
  1093. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1094. // Invalid quality value (not a number)
  1095. EXPECT_FALSE(detail::parse_accept_header(
  1096. "text/html;q=invalid,application/json", result));
  1097. // A valid numeric prefix does not make the entire quality value valid.
  1098. EXPECT_FALSE(detail::parse_accept_header(
  1099. "text/html;q=0.5junk,application/json", result));
  1100. // Empty quality value
  1101. EXPECT_FALSE(
  1102. detail::parse_accept_header("text/html;q=,application/json", result));
  1103. // Invalid media type format (no slash and not wildcard)
  1104. EXPECT_FALSE(
  1105. detail::parse_accept_header("invalidtype,application/json", result));
  1106. // Valid cases should still work
  1107. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1108. EXPECT_EQ(result.size(), 1U);
  1109. EXPECT_EQ(result[0], "*/*");
  1110. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1111. EXPECT_EQ(result.size(), 1U);
  1112. EXPECT_EQ(result[0], "*");
  1113. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1114. EXPECT_EQ(result.size(), 1U);
  1115. EXPECT_EQ(result[0], "text/*");
  1116. }
  1117. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1118. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1119. // and must not be answered with 400 Bad Request.
  1120. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1121. struct {
  1122. const char *value;
  1123. std::vector<std::string> expected;
  1124. } cases[] = {
  1125. {",application/json", {"application/json"}},
  1126. {"text/html,", {"text/html"}},
  1127. {"text/html,,*/*", {"text/html", "*/*"}},
  1128. // An empty element may be spelled with whitespace in it
  1129. {"text/html, , application/json", {"text/html", "application/json"}},
  1130. // Nothing but empty elements is an empty list, which means the same
  1131. // thing as no Accept header at all
  1132. {",,,", {}},
  1133. // Quality values still apply across ignored empty elements
  1134. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1135. };
  1136. for (const auto &c : cases) {
  1137. std::vector<std::string> result;
  1138. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1139. << "value: " << c.value;
  1140. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1141. }
  1142. // An invalid entry is still rejected when empty elements surround it
  1143. std::vector<std::string> result;
  1144. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1145. }
  1146. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1147. // or ';' inside one does not end the list element or the parameter. Section
  1148. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1149. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1150. struct {
  1151. const char *value;
  1152. std::vector<std::string> expected;
  1153. } cases[] = {
  1154. {"text/html;profile=\"a,b\",application/json",
  1155. {"text/html", "application/json"}},
  1156. // A "q=" inside a quoted value is not the weight
  1157. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1158. {"text/html", "application/json"}},
  1159. // The weight after a quoted value still applies
  1160. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1161. {"application/json", "text/html"}},
  1162. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1163. {"application/json", "text/html"}},
  1164. {"text/html;profile=\"a\\\"b\",application/json",
  1165. {"text/html", "application/json"}},
  1166. // An escaped backslash does not escape the '"' after it
  1167. {"text/html;profile=\"a\\\\\",application/json",
  1168. {"text/html", "application/json"}},
  1169. };
  1170. for (const auto &c : cases) {
  1171. std::vector<std::string> result;
  1172. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1173. << "value: " << c.value;
  1174. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1175. }
  1176. }
  1177. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1178. Server svr;
  1179. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1180. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1181. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1182. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1183. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1184. res.set_content("ok", "text/plain");
  1185. });
  1186. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1187. EXPECT_TRUE(false);
  1188. res.set_content("bad request", "text/plain");
  1189. });
  1190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1191. auto se = detail::scope_exit([&] {
  1192. svr.stop();
  1193. listen_thread.join();
  1194. ASSERT_FALSE(svr.is_running());
  1195. });
  1196. svr.wait_until_ready();
  1197. Client cli("localhost", PORT);
  1198. {
  1199. auto res = cli.Get(
  1200. "/accept_ok",
  1201. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1203. EXPECT_EQ(StatusCode::OK_200, res->status);
  1204. }
  1205. {
  1206. auto res = cli.Get("/accept_bad_request",
  1207. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1209. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1210. }
  1211. }
  1212. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1213. Server svr;
  1214. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1215. res.set_content("ok", "text/plain");
  1216. });
  1217. std::atomic<int> start_count{0};
  1218. std::atomic<bool> running_when_called{false};
  1219. svr.set_start_handler([&]() {
  1220. running_when_called = svr.is_running();
  1221. start_count++;
  1222. });
  1223. auto port = svr.bind_to_any_port(HOST);
  1224. std::thread t([&]() { svr.listen_after_bind(); });
  1225. auto se = detail::scope_exit([&] {
  1226. svr.stop();
  1227. t.join();
  1228. ASSERT_FALSE(svr.is_running());
  1229. });
  1230. svr.wait_until_ready();
  1231. // A successful request proves the accept loop is running, which the start
  1232. // handler precedes; so by now the handler must have run exactly once.
  1233. Client cli(HOST, port);
  1234. cli.set_connection_timeout(std::chrono::seconds(5));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1237. EXPECT_EQ(StatusCode::OK_200, res->status);
  1238. EXPECT_EQ(1, start_count.load());
  1239. EXPECT_TRUE(running_when_called.load());
  1240. }
  1241. TEST(DivideTest, DivideStringTests) {
  1242. auto divide = [](const std::string &str, char d) {
  1243. std::string lhs;
  1244. std::string rhs;
  1245. detail::divide(str, d,
  1246. [&](const char *lhs_data, std::size_t lhs_size,
  1247. const char *rhs_data, std::size_t rhs_size) {
  1248. lhs.assign(lhs_data, lhs_size);
  1249. rhs.assign(rhs_data, rhs_size);
  1250. });
  1251. return std::make_pair(std::move(lhs), std::move(rhs));
  1252. };
  1253. {
  1254. const auto res = divide("", '=');
  1255. EXPECT_EQ(res.first, "");
  1256. EXPECT_EQ(res.second, "");
  1257. }
  1258. {
  1259. const auto res = divide("=", '=');
  1260. EXPECT_EQ(res.first, "");
  1261. EXPECT_EQ(res.second, "");
  1262. }
  1263. {
  1264. const auto res = divide(" ", '=');
  1265. EXPECT_EQ(res.first, " ");
  1266. EXPECT_EQ(res.second, "");
  1267. }
  1268. {
  1269. const auto res = divide("a", '=');
  1270. EXPECT_EQ(res.first, "a");
  1271. EXPECT_EQ(res.second, "");
  1272. }
  1273. {
  1274. const auto res = divide("a=", '=');
  1275. EXPECT_EQ(res.first, "a");
  1276. EXPECT_EQ(res.second, "");
  1277. }
  1278. {
  1279. const auto res = divide("=b", '=');
  1280. EXPECT_EQ(res.first, "");
  1281. EXPECT_EQ(res.second, "b");
  1282. }
  1283. {
  1284. const auto res = divide("a=b", '=');
  1285. EXPECT_EQ(res.first, "a");
  1286. EXPECT_EQ(res.second, "b");
  1287. }
  1288. {
  1289. const auto res = divide("a=b=", '=');
  1290. EXPECT_EQ(res.first, "a");
  1291. EXPECT_EQ(res.second, "b=");
  1292. }
  1293. {
  1294. const auto res = divide("a=b=c", '=');
  1295. EXPECT_EQ(res.first, "a");
  1296. EXPECT_EQ(res.second, "b=c");
  1297. }
  1298. }
  1299. TEST(SplitTest, ParseQueryString) {
  1300. string s = "key1=val1&key2=val2&key3=val3";
  1301. Params dic;
  1302. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1303. [&](const char *b, const char *e) {
  1304. string key, val;
  1305. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1306. if (key.empty()) {
  1307. key.assign(b2, e2);
  1308. } else {
  1309. val.assign(b2, e2);
  1310. }
  1311. });
  1312. dic.emplace(key, val);
  1313. });
  1314. EXPECT_EQ("val1", dic.find("key1")->second);
  1315. EXPECT_EQ("val2", dic.find("key2")->second);
  1316. EXPECT_EQ("val3", dic.find("key3")->second);
  1317. }
  1318. TEST(SplitTest, ParseInvalidQueryTests) {
  1319. {
  1320. string s = " ";
  1321. Params dict;
  1322. detail::parse_query_text(s, dict);
  1323. EXPECT_TRUE(dict.empty());
  1324. }
  1325. {
  1326. string s = " = =";
  1327. Params dict;
  1328. detail::parse_query_text(s, dict);
  1329. EXPECT_TRUE(dict.empty());
  1330. }
  1331. }
  1332. TEST(ParseQueryTest, ParseQueryString) {
  1333. {
  1334. std::string s = "key1=val1&key2=val2&key3=val3";
  1335. Params dic;
  1336. detail::parse_query_text(s, dic);
  1337. EXPECT_EQ("val1", dic.find("key1")->second);
  1338. EXPECT_EQ("val2", dic.find("key2")->second);
  1339. EXPECT_EQ("val3", dic.find("key3")->second);
  1340. }
  1341. {
  1342. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1343. Params dic;
  1344. detail::parse_query_text(s, dic);
  1345. EXPECT_EQ("", dic.find("key1")->second);
  1346. EXPECT_EQ("val1", dic.find("key2")->second);
  1347. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1348. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1349. }
  1350. }
  1351. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1352. Params dic;
  1353. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1354. dic.emplace("key1", "val1");
  1355. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1356. dic.emplace("key2", "val2");
  1357. dic.emplace("key3", "val3");
  1358. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1359. }
  1360. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1361. Params params;
  1362. params.emplace("a", "1");
  1363. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1364. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1365. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1366. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1367. // Long enough to overflow the stack when matched with std::regex.
  1368. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1369. EXPECT_EQ("/p?" + long_query + "&a=1",
  1370. append_query_params("/p?" + long_query, params));
  1371. }
  1372. // Joins every entry of a Headers or Params into "key=value " so a whole
  1373. // traversal can be compared in one assertion. Both are instantiations of the
  1374. // same insertion-ordered container, so one helper serves both.
  1375. template <typename Map> static std::string entries_to_string(const Map &m) {
  1376. std::string s;
  1377. for (const auto &entry : m) {
  1378. s += entry.first + "=" + entry.second + " ";
  1379. }
  1380. return s;
  1381. }
  1382. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1383. // Params used to be a std::multimap, which sorted by name and handed the
  1384. // caller's query back alphabetised. A client signing its query string could
  1385. // not reproduce the order it asked for.
  1386. Params dic;
  1387. dic.emplace("zulu", "1");
  1388. dic.emplace("alpha", "2");
  1389. dic.emplace("mike", "3");
  1390. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1391. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1392. }
  1393. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1394. Params dic;
  1395. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1396. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1397. }
  1398. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1399. Request req;
  1400. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1401. req.params);
  1402. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1403. EXPECT_EQ("first", req.get_param_value("tag"));
  1404. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1405. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1406. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1407. EXPECT_EQ("", req.get_param_value("tag", 3));
  1408. }
  1409. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1410. // Params shares its container with Headers, which matches field names
  1411. // case-insensitively. Parameter names must not pick that up.
  1412. Params dic;
  1413. dic.emplace("Key", "upper");
  1414. dic.emplace("key", "lower");
  1415. EXPECT_EQ(2U, dic.size());
  1416. EXPECT_EQ(1U, dic.count("Key"));
  1417. EXPECT_EQ(1U, dic.count("key"));
  1418. EXPECT_EQ("upper", dic.find("Key")->second);
  1419. EXPECT_EQ("lower", dic.find("key")->second);
  1420. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1421. }
  1422. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1423. Server svr;
  1424. std::string order;
  1425. svr.Get("/order", [&](const Request &req, Response &res) {
  1426. order = entries_to_string(req.params);
  1427. res.set_content("ok", "text/plain");
  1428. });
  1429. auto port = svr.bind_to_any_port(HOST);
  1430. thread t = thread([&] { svr.listen_after_bind(); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. t.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, port);
  1438. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1439. ASSERT_TRUE(res);
  1440. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1441. }
  1442. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1443. Server svr;
  1444. std::string field_order, file_order;
  1445. svr.Post("/order", [&](const Request &req, Response &res) {
  1446. for (const auto &field : req.form.fields) {
  1447. field_order += field.first + "=" + field.second.content + " ";
  1448. }
  1449. for (const auto &file : req.form.files) {
  1450. file_order += file.first + "=" + file.second.filename + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. UploadFormDataItems items = {
  1463. {"zulu", "1", "", ""},
  1464. {"alpha", "2", "", ""},
  1465. {"mike", "3", "", ""},
  1466. {"zebra", "z", "z.txt", "text/plain"},
  1467. {"apple", "a", "a.txt", "text/plain"},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/order", items);
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1473. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1474. }
  1475. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1476. Server svr;
  1477. std::vector<std::string> values;
  1478. std::string first, second, out_of_range, order;
  1479. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1480. values = req.form.get_fields("tag");
  1481. first = req.form.get_field("tag", 0);
  1482. second = req.form.get_field("tag", 1);
  1483. out_of_range = req.form.get_field("tag", 2);
  1484. for (const auto &field : req.form.fields) {
  1485. order += field.first + "=" + field.second.content + " ";
  1486. }
  1487. res.set_content("ok", "text/plain");
  1488. });
  1489. auto port = svr.bind_to_any_port(HOST);
  1490. thread t = thread([&] { svr.listen_after_bind(); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. t.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1498. // not adjacent in the container.
  1499. UploadFormDataItems items = {
  1500. {"tag", "first", "", ""},
  1501. {"other", "x", "", ""},
  1502. {"tag", "second", "", ""},
  1503. };
  1504. Client cli(HOST, port);
  1505. auto res = cli.Post("/repeated", items);
  1506. ASSERT_TRUE(res);
  1507. ASSERT_EQ(2U, values.size());
  1508. EXPECT_EQ("first", values[0]);
  1509. EXPECT_EQ("second", values[1]);
  1510. EXPECT_EQ("first", first);
  1511. EXPECT_EQ("second", second);
  1512. // std::multimap already kept entries sharing a name in insertion order, so
  1513. // everything above passes without this change too. The whole traversal is
  1514. // what tells the two apart: sorting by name would hoist "other" to the front
  1515. // and the two "tag" parts would end up adjacent.
  1516. EXPECT_EQ("tag=first other=x tag=second ", order);
  1517. // Advancing past the last entry of a name used to run off the container;
  1518. // the container's saturating increment makes it return the default instead.
  1519. EXPECT_EQ("", out_of_range);
  1520. }
  1521. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1522. Server svr;
  1523. std::string file_names;
  1524. svr.Post("/upload", [&](const Request &req, Response &res) {
  1525. for (const auto &file : req.form.files) {
  1526. file_names += file.first + "|" + file.second.filename + " ";
  1527. }
  1528. res.set_content("ok", "text/plain");
  1529. });
  1530. auto port = svr.bind_to_any_port(HOST);
  1531. thread t = thread([&] { svr.listen_after_bind(); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. t.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. // A trailing backslash would otherwise escape the closing quote.
  1539. UploadFormDataItems items = {
  1540. {"dir\\", "x", "a.txt", "text/plain"},
  1541. {"b", "y", "a\\\\b.txt", "text/plain"},
  1542. };
  1543. Client cli(HOST, port);
  1544. auto res = cli.Post("/upload", items);
  1545. ASSERT_TRUE(res);
  1546. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1547. }
  1548. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1549. // Server::read_content() keeps a FormFields::iterator alive across the
  1550. // content callbacks that fill the part it points at. The container is
  1551. // vector-backed, so a later emplace can reallocate and invalidate an older
  1552. // iterator; 64 parts grow the vector through seven reallocations, which
  1553. // checks that every part's content still lands in its own entry.
  1554. const size_t part_count = 64;
  1555. // One formula for both the parts sent and the values expected back, so the
  1556. // two cannot drift apart.
  1557. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1558. auto content_of = [](size_t i) {
  1559. return std::string(64, static_cast<char>('a' + (i % 26)));
  1560. };
  1561. Server svr;
  1562. std::vector<std::pair<std::string, std::string>> received;
  1563. svr.Post("/many", [&](const Request &req, Response &res) {
  1564. for (const auto &field : req.form.fields) {
  1565. received.emplace_back(field.first, field.second.content);
  1566. }
  1567. res.set_content("ok", "text/plain");
  1568. });
  1569. auto port = svr.bind_to_any_port(HOST);
  1570. thread t = thread([&] { svr.listen_after_bind(); });
  1571. auto se = detail::scope_exit([&] {
  1572. svr.stop();
  1573. t.join();
  1574. ASSERT_FALSE(svr.is_running());
  1575. });
  1576. svr.wait_until_ready();
  1577. UploadFormDataItems items;
  1578. for (size_t i = 0; i < part_count; i++) {
  1579. items.push_back({name_of(i), content_of(i), "", ""});
  1580. }
  1581. Client cli(HOST, port);
  1582. auto res = cli.Post("/many", items);
  1583. ASSERT_TRUE(res);
  1584. ASSERT_EQ(part_count, received.size());
  1585. for (size_t i = 0; i < part_count; i++) {
  1586. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1587. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1588. }
  1589. }
  1590. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1591. string content_type = "multipart/form-data; boundary=something";
  1592. string boundary;
  1593. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1594. EXPECT_TRUE(ret);
  1595. EXPECT_EQ(boundary, "something");
  1596. }
  1597. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1598. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1599. string boundary;
  1600. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1601. EXPECT_TRUE(ret);
  1602. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1603. }
  1604. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1605. string content_type =
  1606. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1607. string boundary;
  1608. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1609. EXPECT_TRUE(ret);
  1610. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1613. string content_type =
  1614. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1615. string boundary;
  1616. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1617. EXPECT_TRUE(ret);
  1618. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1619. }
  1620. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1621. const string boundary(70, 'a');
  1622. string content_type = "multipart/form-data; boundary=" + boundary;
  1623. string parsed;
  1624. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1625. EXPECT_TRUE(ret);
  1626. EXPECT_EQ(parsed, boundary);
  1627. }
  1628. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1629. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1630. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1631. string parsed;
  1632. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1633. EXPECT_FALSE(ret);
  1634. }
  1635. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1636. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1637. // is 72 characters on the wire and still valid.
  1638. const string boundary(70, 'a');
  1639. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1640. string parsed;
  1641. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1642. EXPECT_EQ(parsed, boundary);
  1643. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1644. parsed.clear();
  1645. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1646. }
  1647. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1648. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1649. // The parameter parser must not treat that '=' as the key/value separator.
  1650. string content_type =
  1651. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1652. "charset=UTF-8";
  1653. string parsed;
  1654. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1655. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1656. }
  1657. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1658. // A ';' inside the quoted-string is part of the value, not a parameter
  1659. // separator, so it must not truncate the boundary.
  1660. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1661. string parsed;
  1662. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1663. EXPECT_EQ(parsed, "a;b");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1666. string parsed;
  1667. EXPECT_TRUE(detail::parse_multipart_boundary(
  1668. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1669. EXPECT_EQ("a\\b", parsed);
  1670. EXPECT_TRUE(detail::parse_multipart_boundary(
  1671. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1672. EXPECT_EQ("a\"b", parsed);
  1673. }
  1674. TEST(ParseDispositionParamsTest, QuotedValues) {
  1675. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1676. // ';' and '=' are ordinary characters inside one.
  1677. struct {
  1678. const char *value;
  1679. std::vector<std::pair<const char *, const char *>> expected;
  1680. } cases[] = {
  1681. {"name=\"file1\"; filename=\"a.txt\"",
  1682. {{"name", "file1"}, {"filename", "a.txt"}}},
  1683. // Whitespace around '=' and ';' is still trimmed
  1684. {"name=\"file2\" ;filename = \"a.html\"",
  1685. {{"name", "file2"}, {"filename", "a.html"}}},
  1686. // '=' inside the value used to leave only the text after the last one
  1687. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1688. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1689. {"name=\"x=y\"", {{"name", "x=y"}}},
  1690. // ';' inside the value used to truncate the pair and leave a bogus one
  1691. {"name=\"file3\"; filename=\"a;b.txt\"",
  1692. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1693. // An unquoted value keeps working, and so does filename*
  1694. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1695. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1696. // A parameter with no key is dropped rather than turned into one whose
  1697. // key is the value
  1698. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1699. // An escaped quote does not end the value
  1700. {"name=\"a\\\"; filename=evil.php\"",
  1701. {{"name", "a\"; filename=evil.php"}}},
  1702. // Other backslashes, as in a Windows path, are kept
  1703. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1704. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1705. };
  1706. for (const auto &c : cases) {
  1707. Params params;
  1708. detail::parse_disposition_params(c.value, params);
  1709. for (const auto &kv : c.expected) {
  1710. auto it = params.find(kv.first);
  1711. ASSERT_NE(it, params.end())
  1712. << "value: " << c.value << ", key: " << kv.first;
  1713. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1714. }
  1715. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1716. }
  1717. }
  1718. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1719. Server svr;
  1720. std::string filename;
  1721. std::string content;
  1722. svr.Post("/upload", [&](const Request &req, Response &) {
  1723. const auto &file = req.form.get_file("file");
  1724. filename = file.filename;
  1725. content = file.content;
  1726. });
  1727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1728. auto se = detail::scope_exit([&] {
  1729. svr.stop();
  1730. thread.join();
  1731. ASSERT_FALSE(svr.is_running());
  1732. });
  1733. svr.wait_until_ready();
  1734. std::string body = "--B\r\n"
  1735. "Content-Disposition: form-data; name=\"file\"; "
  1736. "filename=\"a.txt\"\r\n"
  1737. "Content-Type: text/plain\r\n"
  1738. "\r\n"
  1739. "hello\r\n"
  1740. "--B--\r\n";
  1741. Client cli(HOST, PORT);
  1742. auto res = cli.Post(
  1743. "/upload",
  1744. [&](size_t offset, DataSink &sink) {
  1745. if (offset < body.size()) {
  1746. sink.write(&body[offset], 1);
  1747. } else {
  1748. sink.done();
  1749. }
  1750. return true;
  1751. },
  1752. "multipart/form-data; boundary=B");
  1753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1754. EXPECT_EQ(StatusCode::OK_200, res->status);
  1755. EXPECT_EQ("a.txt", filename);
  1756. EXPECT_EQ("hello", content);
  1757. }
  1758. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1759. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1760. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1761. Server svr;
  1762. std::string field_value, file_name, file_filename;
  1763. bool has_field = false, has_file = false;
  1764. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1765. has_field = req.form.has_field("x=y");
  1766. field_value = req.form.get_field("x=y");
  1767. has_file = req.form.has_file("file1");
  1768. const auto &file = req.form.get_file("file1");
  1769. file_name = file.name;
  1770. file_filename = file.filename;
  1771. res.set_content("ok", "text/plain");
  1772. });
  1773. auto port = svr.bind_to_any_port(HOST);
  1774. thread t = thread([&] { svr.listen_after_bind(); });
  1775. auto se = detail::scope_exit([&] {
  1776. svr.stop();
  1777. t.join();
  1778. ASSERT_FALSE(svr.is_running());
  1779. });
  1780. svr.wait_until_ready();
  1781. UploadFormDataItems items = {
  1782. {"x=y", "field-value", "", ""},
  1783. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1784. };
  1785. Client cli(HOST, port);
  1786. auto res = cli.Post("/quoted", items);
  1787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1788. ASSERT_EQ(StatusCode::OK_200, res->status);
  1789. EXPECT_TRUE(has_field);
  1790. EXPECT_EQ("field-value", field_value);
  1791. EXPECT_TRUE(has_file);
  1792. EXPECT_EQ("file1", file_name);
  1793. EXPECT_EQ("a;b=report.pdf", file_filename);
  1794. }
  1795. TEST(GetHeaderValueTest, DefaultValue) {
  1796. Headers headers = {{"Dummy", "Dummy"}};
  1797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1798. EXPECT_STREQ("text/plain", val);
  1799. }
  1800. TEST(GetHeaderValueTest, DefaultValueInt) {
  1801. Headers headers = {{"Dummy", "Dummy"}};
  1802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1803. EXPECT_EQ(100ull, val);
  1804. }
  1805. TEST(GetHeaderValueTest, RegularValue) {
  1806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1808. EXPECT_STREQ("text/html", val);
  1809. }
  1810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1813. EXPECT_STREQ("text/html", val);
  1814. }
  1815. TEST(GetHeaderValueTest, SetContent) {
  1816. Response res;
  1817. res.set_content("html", "text/html");
  1818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1819. res.set_content("text", "text/plain");
  1820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1822. }
  1823. TEST(GetHeaderValueTest, RegularValueInt) {
  1824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1826. EXPECT_EQ(100ull, val);
  1827. }
  1828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1829. Headers headers = {{"Content-Length", "x"}};
  1830. auto is_invalid_value = false;
  1831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1832. is_invalid_value);
  1833. EXPECT_EQ(0ull, val);
  1834. EXPECT_TRUE(is_invalid_value);
  1835. }
  1836. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1837. // An all-digit value that overflows size_t must be reported as invalid, not
  1838. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1839. // a large length to a small one on 32-bit builds, leaving the framing length
  1840. // wrong while is_invalid_value stayed false.
  1841. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1842. auto is_invalid_value = false;
  1843. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1844. is_invalid_value);
  1845. EXPECT_TRUE(is_invalid_value);
  1846. // A well-formed length is unaffected.
  1847. Headers ok = {{"Content-Length", "1234"}};
  1848. is_invalid_value = false;
  1849. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1850. is_invalid_value);
  1851. EXPECT_EQ(1234ull, val);
  1852. EXPECT_FALSE(is_invalid_value);
  1853. }
  1854. TEST(GetHeaderValueTest, Range) {
  1855. {
  1856. Headers headers = {make_range_header({{1, -1}})};
  1857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1858. EXPECT_STREQ("bytes=1-", val);
  1859. }
  1860. {
  1861. Headers headers = {make_range_header({{-1, 1}})};
  1862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1863. EXPECT_STREQ("bytes=-1", val);
  1864. }
  1865. {
  1866. Headers headers = {make_range_header({{1, 10}})};
  1867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1868. EXPECT_STREQ("bytes=1-10", val);
  1869. }
  1870. {
  1871. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1873. EXPECT_STREQ("bytes=1-10, 100-", val);
  1874. }
  1875. {
  1876. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1878. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1879. }
  1880. {
  1881. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1882. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1883. EXPECT_STREQ("bytes=0-0, -1", val);
  1884. }
  1885. }
  1886. TEST(BearerTokenAuthTest, SchemeValidation) {
  1887. // A value shorter than "Bearer " must not throw from the fixed-length
  1888. // substr, and a non-Bearer scheme must not be reported as a token.
  1889. struct {
  1890. const char *value;
  1891. const char *expected;
  1892. } cases[] = {
  1893. {"x", ""},
  1894. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1895. {"Bearer abc123", "abc123"},
  1896. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1897. };
  1898. for (const auto &c : cases) {
  1899. Request req;
  1900. req.set_header("Authorization", c.value);
  1901. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1905. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1906. // to depend on the standard library (libstdc++ handed back duplicates in
  1907. // reverse insertion order, libc++ in insertion order).
  1908. Request req;
  1909. req.set_header("Accept-Encoding", "gzip");
  1910. req.set_header("Accept-Encoding", "deflate");
  1911. req.set_header("Accept-Encoding", "br");
  1912. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1913. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1914. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1915. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1916. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1917. }
  1918. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1919. Request req;
  1920. req.set_header("X-Test", "only");
  1921. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1922. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1923. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1924. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1925. }
  1926. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1927. Request req;
  1928. req.set_header("X-First", "1");
  1929. req.set_header("X-Test", "2");
  1930. req.params.emplace("first", "1");
  1931. req.params.emplace("test", "2");
  1932. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1933. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1934. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1935. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1936. // The second one is negative when read as a signed value
  1937. const auto max_id = (std::numeric_limits<size_t>::max)();
  1938. for (auto id : {max_id / 2, max_id}) {
  1939. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1940. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1941. EXPECT_EQ("", req.get_param_value("test", id));
  1942. EXPECT_EQ("", req.form.get_field("test", id));
  1943. EXPECT_EQ("", req.form.get_file("test", id).content);
  1944. }
  1945. }
  1946. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1947. Headers headers;
  1948. headers.emplace("Host", "example.com");
  1949. headers.emplace("Accept-Encoding", "gzip");
  1950. headers.emplace("User-Agent", "test");
  1951. headers.emplace("Accept-Encoding", "deflate");
  1952. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1953. "Accept-Encoding=deflate ",
  1954. entries_to_string(headers));
  1955. }
  1956. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1957. Headers headers = {{"Content-Type", "text/html"},
  1958. {"CONTENT-TYPE", "text/xml"}};
  1959. EXPECT_EQ(2U, headers.count("content-type"));
  1960. auto it = headers.find("content-type");
  1961. ASSERT_TRUE(it != headers.end());
  1962. EXPECT_EQ("text/html", it->second);
  1963. }
  1964. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1965. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1966. // drop only those fields and leave everything positioned between them.
  1967. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1968. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1969. auto rng = headers.equal_range("a");
  1970. headers.erase(rng.first, rng.second);
  1971. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1972. }
  1973. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1974. Headers headers = {
  1975. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1976. EXPECT_EQ(3U, headers.erase("A"));
  1977. EXPECT_EQ(0U, headers.count("A"));
  1978. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1979. }
  1980. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1981. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1982. headers.emplace_front("Host", "example.com");
  1983. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1984. entries_to_string(headers));
  1985. }
  1986. TEST(ParseHeaderValueTest, Range) {
  1987. {
  1988. Ranges ranges;
  1989. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1990. EXPECT_TRUE(ret);
  1991. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1992. }
  1993. {
  1994. Ranges ranges;
  1995. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1996. EXPECT_TRUE(ret);
  1997. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1998. }
  1999. {
  2000. Ranges ranges;
  2001. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2002. EXPECT_TRUE(ret);
  2003. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2004. }
  2005. {
  2006. Ranges ranges;
  2007. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2008. EXPECT_FALSE(ret);
  2009. }
  2010. {
  2011. Ranges ranges;
  2012. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2013. EXPECT_TRUE(ret);
  2014. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2015. }
  2016. {
  2017. Ranges ranges;
  2018. auto ret =
  2019. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2020. EXPECT_TRUE(ret);
  2021. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2022. }
  2023. {
  2024. Ranges ranges;
  2025. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2026. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2027. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2028. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2029. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2030. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2031. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2032. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2033. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2034. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2035. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2036. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2037. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2038. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2039. EXPECT_FALSE(
  2040. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2041. EXPECT_TRUE(ranges.empty());
  2042. }
  2043. {
  2044. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2045. // remainder of the representation, so it stays accepted.
  2046. Ranges ranges;
  2047. auto ret =
  2048. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2049. EXPECT_TRUE(ret);
  2050. ASSERT_EQ(1u, ranges.size());
  2051. EXPECT_EQ(0, ranges[0].first);
  2052. EXPECT_EQ(-1, ranges[0].second);
  2053. }
  2054. // RFC 9110 14.1: range unit names are case-insensitive.
  2055. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2056. Ranges ranges;
  2057. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2058. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2059. }
  2060. }
  2061. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2062. Request req;
  2063. req.set_header("Accept-Encoding", "gzip");
  2064. Response res;
  2065. res.set_header("Content-Type", "text/plain");
  2066. auto ret = detail::encoding_type(req, res);
  2067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2074. Request req;
  2075. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2076. Response res;
  2077. res.set_header("Content-Type", "text/plain");
  2078. auto ret = detail::encoding_type(req, res);
  2079. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2081. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2082. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2083. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2084. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2085. #else
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. #endif
  2088. }
  2089. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding",
  2092. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2098. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2100. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2102. #else
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. #endif
  2105. }
  2106. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2107. // All supported encodings rejected with q=0 should return None
  2108. Request req;
  2109. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2110. Response res;
  2111. res.set_header("Content-Type", "text/plain");
  2112. auto ret = detail::encoding_type(req, res);
  2113. EXPECT_TRUE(ret == detail::EncodingType::None);
  2114. }
  2115. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2116. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. EXPECT_TRUE(ret == detail::EncodingType::None);
  2123. }
  2124. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2125. Request req;
  2126. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2127. Response res;
  2128. res.set_header("Content-Type", "text/plain");
  2129. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2130. }
  2131. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2132. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2133. Request req;
  2134. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2135. Response res;
  2136. res.set_header("Content-Type", "text/plain");
  2137. auto ret = detail::encoding_type(req, res);
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. }
  2140. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2141. // RFC 7231: Accept-Encoding values are case-insensitive
  2142. Request req;
  2143. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2144. Response res;
  2145. res.set_header("Content-Type", "text/plain");
  2146. auto ret = detail::encoding_type(req, res);
  2147. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2149. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2151. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2152. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2153. #else
  2154. EXPECT_TRUE(ret == detail::EncodingType::None);
  2155. #endif
  2156. }
  2157. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2158. // q value should determine priority, not hardcoded order
  2159. Request req;
  2160. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2161. Response res;
  2162. res.set_header("Content-Type", "text/plain");
  2163. auto ret = detail::encoding_type(req, res);
  2164. // gzip has highest q=1.0, so it should be selected even though
  2165. // br and zstd are also supported
  2166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2168. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2169. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2170. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2171. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2172. #else
  2173. EXPECT_TRUE(ret == detail::EncodingType::None);
  2174. #endif
  2175. }
  2176. TEST(BufferStreamTest, read) {
  2177. detail::BufferStream strm1;
  2178. Stream &strm = strm1;
  2179. EXPECT_EQ(5, strm.write("hello"));
  2180. char buf[512];
  2181. EXPECT_EQ(2, strm.read(buf, 2));
  2182. EXPECT_EQ('h', buf[0]);
  2183. EXPECT_EQ('e', buf[1]);
  2184. EXPECT_EQ(2, strm.read(buf, 2));
  2185. EXPECT_EQ('l', buf[0]);
  2186. EXPECT_EQ('l', buf[1]);
  2187. EXPECT_EQ(1, strm.read(buf, 1));
  2188. EXPECT_EQ('o', buf[0]);
  2189. EXPECT_EQ(0, strm.read(buf, 1));
  2190. }
  2191. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2192. auto host = "www.httpwatch.com";
  2193. auto ip = hosted_at(host);
  2194. EXPECT_EQ("23.96.13.243", ip);
  2195. std::vector<std::string> addrs;
  2196. hosted_at(host, addrs);
  2197. EXPECT_EQ(1u, addrs.size());
  2198. }
  2199. #if 0 // It depends on each test environment...
  2200. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2201. auto host = "www.youtube.com";
  2202. std::vector<std::string> addrs;
  2203. hosted_at(host, addrs);
  2204. EXPECT_EQ(20u, addrs.size());
  2205. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2206. EXPECT_TRUE(it != addrs.end());
  2207. }
  2208. #endif
  2209. class ChunkedEncodingTest : public ::testing::Test {
  2210. protected:
  2211. ChunkedEncodingTest()
  2212. : cli_(HOST, PORT)
  2213. #ifdef CPPHTTPLIB_SSL_ENABLED
  2214. ,
  2215. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2216. #endif
  2217. {
  2218. cli_.set_connection_timeout(2);
  2219. #ifdef CPPHTTPLIB_SSL_ENABLED
  2220. cli_.enable_server_certificate_verification(false);
  2221. #endif
  2222. }
  2223. virtual void SetUp() {
  2224. read_file("./image.jpg", image_data_);
  2225. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2226. res.set_content("Hello World!", "text/plain");
  2227. });
  2228. svr_.Get(
  2229. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2230. res.set_chunked_content_provider(
  2231. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2232. size_t remaining = image_data_.size() - offset;
  2233. if (remaining == 0) {
  2234. sink.done();
  2235. } else {
  2236. constexpr size_t CHUNK_SIZE = 1024;
  2237. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2238. sink.write(&image_data_[offset], send_size);
  2239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2240. }
  2241. return true;
  2242. });
  2243. });
  2244. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2245. svr_.wait_until_ready();
  2246. }
  2247. virtual void TearDown() {
  2248. svr_.stop();
  2249. if (!request_threads_.empty()) {
  2250. std::this_thread::sleep_for(std::chrono::seconds(1));
  2251. for (auto &t : request_threads_) {
  2252. t.join();
  2253. }
  2254. }
  2255. t_.join();
  2256. }
  2257. #ifdef CPPHTTPLIB_SSL_ENABLED
  2258. SSLClient cli_;
  2259. SSLServer svr_;
  2260. #else
  2261. Client cli_;
  2262. Server svr_;
  2263. #endif
  2264. thread t_;
  2265. std::vector<thread> request_threads_;
  2266. std::string image_data_;
  2267. };
  2268. TEST_F(ChunkedEncodingTest, NormalGet) {
  2269. auto res = cli_.Get("/chunked");
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. std::string out;
  2272. read_file("./image.jpg", out);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. EXPECT_EQ(out, res->body);
  2275. }
  2276. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2277. std::string body;
  2278. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2279. body.append(data, data_length);
  2280. return true;
  2281. });
  2282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2283. std::string out;
  2284. read_file("./image.jpg", out);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. EXPECT_EQ(out, body);
  2287. }
  2288. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2289. std::string body;
  2290. auto res = cli_.Get(
  2291. "/chunked",
  2292. [&](const Response &response) {
  2293. EXPECT_EQ(StatusCode::OK_200, response.status);
  2294. return true;
  2295. },
  2296. [&](const char *data, size_t data_length) {
  2297. body.append(data, data_length);
  2298. return true;
  2299. });
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. std::string out;
  2302. read_file("./image.jpg", out);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ(out, body);
  2305. }
  2306. TEST(RangeTest, FromHTTPBin_Online) {
  2307. auto host = "httpbingo.org";
  2308. auto path = std::string{"/range/32"};
  2309. #ifdef CPPHTTPLIB_SSL_ENABLED
  2310. auto port = 443;
  2311. SSLClient cli(host, port);
  2312. #else
  2313. auto port = 80;
  2314. Client cli(host, port);
  2315. #endif
  2316. cli.set_connection_timeout(5);
  2317. {
  2318. auto res = cli.Get(path);
  2319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2320. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2321. EXPECT_EQ(StatusCode::OK_200, res->status);
  2322. }
  2323. {
  2324. Headers headers = {make_range_header({{1, -1}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2329. }
  2330. {
  2331. Headers headers = {make_range_header({{1, 10}})};
  2332. auto res = cli.Get(path, headers);
  2333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2334. EXPECT_EQ("bcdefghijk", res->body);
  2335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2336. }
  2337. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2338. // entire resource, while the original httpbin returned 200. Both are
  2339. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2340. {
  2341. Headers headers = {make_range_header({{0, 31}})};
  2342. auto res = cli.Get(path, headers);
  2343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2344. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2345. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2346. res->status == StatusCode::PartialContent_206);
  2347. }
  2348. {
  2349. Headers headers = {make_range_header({{0, -1}})};
  2350. auto res = cli.Get(path, headers);
  2351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2352. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2353. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2354. res->status == StatusCode::PartialContent_206);
  2355. }
  2356. // go-httpbin returns 206 with clamped range for over-range requests,
  2357. // while the original httpbin returned 416. Both behaviors are observed
  2358. // in real servers, so we only verify the request succeeds.
  2359. {
  2360. Headers headers = {make_range_header({{0, 32}})};
  2361. auto res = cli.Get(path, headers);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. }
  2364. }
  2365. TEST(RangeTest, IgnoredForPost) {
  2366. Server svr;
  2367. svr.Post("/", [](const Request &, Response &res) {
  2368. res.set_content("abcdefg", "text/plain");
  2369. });
  2370. auto port = svr.bind_to_any_port(HOST);
  2371. ASSERT_GT(port, 0);
  2372. thread t = thread([&] { svr.listen_after_bind(); });
  2373. auto se = detail::scope_exit([&] {
  2374. svr.stop();
  2375. t.join();
  2376. ASSERT_FALSE(svr.is_running());
  2377. });
  2378. svr.wait_until_ready();
  2379. Client cli(HOST, port);
  2380. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2381. auto res = cli.Post("/", Headers{{"Range", range}});
  2382. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2383. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2384. EXPECT_EQ("abcdefg", res->body) << range;
  2385. }
  2386. }
  2387. TEST(RangeTest, IgnoredForUnknownUnit) {
  2388. Server svr;
  2389. svr.Get("/", [](const Request &, Response &res) {
  2390. res.set_content("abcdefg", "text/plain");
  2391. });
  2392. auto port = svr.bind_to_any_port(HOST);
  2393. ASSERT_GT(port, 0);
  2394. thread t = thread([&] { svr.listen_after_bind(); });
  2395. auto se = detail::scope_exit([&] {
  2396. svr.stop();
  2397. t.join();
  2398. ASSERT_FALSE(svr.is_running());
  2399. });
  2400. svr.wait_until_ready();
  2401. Client cli(HOST, port);
  2402. for (auto range : {"items=1-2", "none=x"}) {
  2403. auto res = cli.Get("/", Headers{{"Range", range}});
  2404. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2405. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2406. EXPECT_EQ("abcdefg", res->body) << range;
  2407. }
  2408. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2409. ASSERT_TRUE(res) << to_string(res.error());
  2410. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2411. }
  2412. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2413. auto host = "unresolvableaddress.local";
  2414. auto path = std::string{"/"};
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. auto port = 443;
  2417. SSLClient cli(host, port);
  2418. #else
  2419. auto port = 80;
  2420. Client cli(host, port);
  2421. #endif
  2422. cli.set_connection_timeout(1);
  2423. {
  2424. auto res = cli.Get(path);
  2425. ASSERT_FALSE(res);
  2426. }
  2427. std::this_thread::sleep_for(std::chrono::seconds(8));
  2428. }
  2429. #if defined(__linux__) && defined(__GLIBC__) && \
  2430. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2431. // Forward declaration: in split builds split.py strips `inline` and moves the
  2432. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2433. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2434. // against the symbol in both header-only and split builds.
  2435. namespace httplib {
  2436. namespace detail {
  2437. int getaddrinfo_with_timeout(const char *node, const char *service,
  2438. const struct addrinfo *hints,
  2439. struct addrinfo **res, time_t timeout_sec);
  2440. } // namespace detail
  2441. } // namespace httplib
  2442. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2443. //
  2444. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2445. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2446. // gai_suspend() call hits the connection timeout the function calls
  2447. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2448. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2449. // still alive and still references the now-destroyed stack frame.
  2450. //
  2451. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2452. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2453. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2454. // and runs them in a container.
  2455. namespace {
  2456. bool should_run_issue_2431_tests() {
  2457. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2458. return v && *v && std::string(v) != "0";
  2459. }
  2460. std::string unique_unresolvable_host(int n) {
  2461. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2462. // glibc still asks the configured nameserver — which is exactly the path
  2463. // we want to exercise. A unique label per call avoids the resolver cache.
  2464. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2465. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2466. std::to_string(n) + ".invalid";
  2467. }
  2468. } // namespace
  2469. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2470. if (!should_run_issue_2431_tests()) {
  2471. GTEST_SKIP()
  2472. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2473. }
  2474. for (int i = 0; i < 8; ++i) {
  2475. struct addrinfo hints;
  2476. memset(&hints, 0, sizeof(hints));
  2477. hints.ai_family = AF_UNSPEC;
  2478. hints.ai_socktype = SOCK_STREAM;
  2479. auto host = unique_unresolvable_host(i);
  2480. struct addrinfo *result = nullptr;
  2481. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2482. &result, /*timeout_sec=*/1);
  2483. if (rc == 0 && result) { freeaddrinfo(result); }
  2484. }
  2485. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2486. // stack region they still believe holds their gaicb.
  2487. std::this_thread::sleep_for(std::chrono::seconds(3));
  2488. }
  2489. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2490. if (!should_run_issue_2431_tests()) {
  2491. GTEST_SKIP()
  2492. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2493. }
  2494. std::atomic<bool> stop{false};
  2495. std::vector<std::thread> threads;
  2496. for (int t = 0; t < 8; ++t) {
  2497. threads.emplace_back([t, &stop] {
  2498. int i = 0;
  2499. while (!stop.load(std::memory_order_relaxed)) {
  2500. struct addrinfo hints;
  2501. memset(&hints, 0, sizeof(hints));
  2502. hints.ai_family = AF_UNSPEC;
  2503. hints.ai_socktype = SOCK_STREAM;
  2504. auto host = unique_unresolvable_host(t * 100000 + i++);
  2505. struct addrinfo *result = nullptr;
  2506. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2507. &result, /*timeout_sec=*/1);
  2508. if (rc == 0 && result) { freeaddrinfo(result); }
  2509. }
  2510. });
  2511. }
  2512. std::this_thread::sleep_for(std::chrono::seconds(8));
  2513. stop.store(true, std::memory_order_relaxed);
  2514. for (auto &th : threads) {
  2515. th.join();
  2516. }
  2517. std::this_thread::sleep_for(std::chrono::seconds(3));
  2518. }
  2519. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2520. if (!should_run_issue_2431_tests()) {
  2521. GTEST_SKIP()
  2522. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2523. }
  2524. std::atomic<bool> stop{false};
  2525. std::vector<std::thread> threads;
  2526. for (int t = 0; t < 8; ++t) {
  2527. threads.emplace_back([t, &stop] {
  2528. int i = 0;
  2529. while (!stop.load(std::memory_order_relaxed)) {
  2530. auto host = unique_unresolvable_host(t * 100000 + i++);
  2531. Client cli(host, 80);
  2532. cli.set_connection_timeout(1, 0);
  2533. cli.set_read_timeout(1, 0);
  2534. cli.set_write_timeout(1, 0);
  2535. (void)cli.Get("/");
  2536. }
  2537. });
  2538. }
  2539. std::this_thread::sleep_for(std::chrono::seconds(8));
  2540. stop.store(true, std::memory_order_relaxed);
  2541. for (auto &th : threads) {
  2542. th.join();
  2543. }
  2544. std::this_thread::sleep_for(std::chrono::seconds(3));
  2545. }
  2546. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2547. TEST(ConnectionErrorTest, InvalidHost) {
  2548. auto host = "-abcde.com";
  2549. #ifdef CPPHTTPLIB_SSL_ENABLED
  2550. auto port = 443;
  2551. SSLClient cli(host, port);
  2552. #else
  2553. auto port = 80;
  2554. Client cli(host, port);
  2555. #endif
  2556. cli.set_connection_timeout(std::chrono::seconds(2));
  2557. auto res = cli.Get("/");
  2558. ASSERT_TRUE(!res);
  2559. EXPECT_EQ(Error::Connection, res.error());
  2560. }
  2561. TEST(ConnectionErrorTest, InvalidHost2) {
  2562. auto host = "httpcan.org/";
  2563. #ifdef CPPHTTPLIB_SSL_ENABLED
  2564. SSLClient cli(host);
  2565. #else
  2566. Client cli(host);
  2567. #endif
  2568. cli.set_connection_timeout(std::chrono::seconds(2));
  2569. auto res = cli.Get("/");
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Connection, res.error());
  2572. }
  2573. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2574. auto host = "httpcan.org/";
  2575. #ifdef CPPHTTPLIB_SSL_ENABLED
  2576. SSLClient cli(host);
  2577. #else
  2578. Client cli(host);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(2));
  2581. auto res = cli.Get("/");
  2582. ASSERT_TRUE(!res);
  2583. stringstream s;
  2584. s << "error code: " << res.error();
  2585. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2586. }
  2587. TEST(ConnectionErrorTest, InvalidPort) {
  2588. auto host = "localhost";
  2589. auto port = 44380;
  2590. #ifdef CPPHTTPLIB_SSL_ENABLED
  2591. SSLClient cli(host, port);
  2592. #else
  2593. Client cli(host, port);
  2594. #endif
  2595. cli.set_connection_timeout(std::chrono::seconds(2));
  2596. auto res = cli.Get("/");
  2597. ASSERT_TRUE(!res);
  2598. EXPECT_TRUE(Error::Connection == res.error() ||
  2599. Error::ConnectionTimeout == res.error());
  2600. }
  2601. TEST(ConnectionErrorTest, Timeout_Online) {
  2602. auto host = "google.com";
  2603. #ifdef CPPHTTPLIB_SSL_ENABLED
  2604. auto port = 44380;
  2605. SSLClient cli(host, port);
  2606. #else
  2607. auto port = 8080;
  2608. Client cli(host, port);
  2609. #endif
  2610. cli.set_connection_timeout(std::chrono::seconds(2));
  2611. // only probe one address type so that the error reason
  2612. // correlates to the timed-out IPv4, not the unsupported
  2613. // IPv6 connection attempt
  2614. cli.set_address_family(AF_INET);
  2615. auto res = cli.Get("/");
  2616. ASSERT_TRUE(!res);
  2617. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2618. }
  2619. TEST(CancelTest, NoCancel_Online) {
  2620. auto host = "httpbingo.org";
  2621. auto path = std::string{"/range/32"};
  2622. #ifdef CPPHTTPLIB_SSL_ENABLED
  2623. auto port = 443;
  2624. SSLClient cli(host, port);
  2625. #else
  2626. auto port = 80;
  2627. Client cli(host, port);
  2628. #endif
  2629. cli.set_connection_timeout(std::chrono::seconds(5));
  2630. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. }
  2635. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2636. // Use /bytes with a large payload so that the DownloadProgress callback
  2637. // (which only fires for Content-Length responses) is invoked before the
  2638. // entire body is received, giving cancellation a chance to fire.
  2639. auto host = "httpbingo.org";
  2640. auto path = std::string{"/bytes/524288"};
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. auto port = 443;
  2643. SSLClient cli(host, port);
  2644. #else
  2645. auto port = 80;
  2646. Client cli(host, port);
  2647. #endif
  2648. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2649. cli.set_connection_timeout(std::chrono::seconds(5));
  2650. ASSERT_TRUE(!res);
  2651. EXPECT_EQ(Error::Canceled, res.error());
  2652. }
  2653. TEST(CancelTest, WithCancelLargePayload_Online) {
  2654. auto host = "httpbingo.org";
  2655. auto path = std::string{"/bytes/524288"};
  2656. #ifdef CPPHTTPLIB_SSL_ENABLED
  2657. auto port = 443;
  2658. SSLClient cli(host, port);
  2659. #else
  2660. auto port = 80;
  2661. Client cli(host, port);
  2662. #endif
  2663. cli.set_connection_timeout(std::chrono::seconds(5));
  2664. uint32_t count = 0;
  2665. auto res =
  2666. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2667. ASSERT_TRUE(!res);
  2668. EXPECT_EQ(Error::Canceled, res.error());
  2669. }
  2670. TEST(CancelTest, NoCancelPost) {
  2671. Server svr;
  2672. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2673. res.set_content("Hello World!", "text/plain");
  2674. });
  2675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2676. auto se = detail::scope_exit([&] {
  2677. svr.stop();
  2678. thread.join();
  2679. ASSERT_FALSE(svr.is_running());
  2680. });
  2681. svr.wait_until_ready();
  2682. Client cli(HOST, PORT);
  2683. cli.set_connection_timeout(std::chrono::seconds(5));
  2684. auto res =
  2685. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2686. "application/json", [](uint64_t, uint64_t) { return true; });
  2687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2688. EXPECT_EQ("Hello World!", res->body);
  2689. EXPECT_EQ(StatusCode::OK_200, res->status);
  2690. }
  2691. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2692. Server svr;
  2693. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2694. res.set_content("Hello World!", "text/plain");
  2695. });
  2696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2697. auto se = detail::scope_exit([&] {
  2698. svr.stop();
  2699. thread.join();
  2700. ASSERT_FALSE(svr.is_running());
  2701. });
  2702. svr.wait_until_ready();
  2703. Client cli(HOST, PORT);
  2704. cli.set_connection_timeout(std::chrono::seconds(5));
  2705. auto res =
  2706. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2707. "application/json", [](uint64_t, uint64_t) { return false; });
  2708. ASSERT_TRUE(!res);
  2709. EXPECT_EQ(Error::Canceled, res.error());
  2710. }
  2711. TEST(CancelTest, WithCancelLargePayloadPost) {
  2712. Server svr;
  2713. svr.set_payload_max_length(200 * 1024 * 1024);
  2714. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2715. res.set_content(LARGE_DATA, "text/plain");
  2716. });
  2717. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2718. auto se = detail::scope_exit([&] {
  2719. svr.stop();
  2720. thread.join();
  2721. ASSERT_FALSE(svr.is_running());
  2722. });
  2723. svr.wait_until_ready();
  2724. Client cli(HOST, PORT);
  2725. cli.set_payload_max_length(200 * 1024 * 1024);
  2726. cli.set_connection_timeout(std::chrono::seconds(5));
  2727. auto res =
  2728. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2729. "application/json", [](uint64_t, uint64_t) { return false; });
  2730. ASSERT_TRUE(!res);
  2731. EXPECT_EQ(Error::Canceled, res.error());
  2732. }
  2733. TEST(CancelTest, NoCancelPut) {
  2734. Server svr;
  2735. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2736. res.set_content("Hello World!", "text/plain");
  2737. });
  2738. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2739. auto se = detail::scope_exit([&] {
  2740. svr.stop();
  2741. thread.join();
  2742. ASSERT_FALSE(svr.is_running());
  2743. });
  2744. svr.wait_until_ready();
  2745. Client cli(HOST, PORT);
  2746. cli.set_connection_timeout(std::chrono::seconds(5));
  2747. auto res =
  2748. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2749. "application/json", [](uint64_t, uint64_t) { return true; });
  2750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2751. EXPECT_EQ("Hello World!", res->body);
  2752. EXPECT_EQ(StatusCode::OK_200, res->status);
  2753. }
  2754. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2755. Server svr;
  2756. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!", "text/plain");
  2758. });
  2759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2760. auto se = detail::scope_exit([&] {
  2761. svr.stop();
  2762. thread.join();
  2763. ASSERT_FALSE(svr.is_running());
  2764. });
  2765. svr.wait_until_ready();
  2766. Client cli(HOST, PORT);
  2767. cli.set_connection_timeout(std::chrono::seconds(5));
  2768. auto res =
  2769. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2770. "application/json", [](uint64_t, uint64_t) { return false; });
  2771. ASSERT_TRUE(!res);
  2772. EXPECT_EQ(Error::Canceled, res.error());
  2773. }
  2774. TEST(CancelTest, WithCancelLargePayloadPut) {
  2775. Server svr;
  2776. svr.set_payload_max_length(200 * 1024 * 1024);
  2777. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2778. res.set_content(LARGE_DATA, "text/plain");
  2779. });
  2780. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2781. auto se = detail::scope_exit([&] {
  2782. svr.stop();
  2783. thread.join();
  2784. ASSERT_FALSE(svr.is_running());
  2785. });
  2786. svr.wait_until_ready();
  2787. Client cli(HOST, PORT);
  2788. cli.set_payload_max_length(200 * 1024 * 1024);
  2789. cli.set_connection_timeout(std::chrono::seconds(5));
  2790. auto res =
  2791. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2792. "application/json", [](uint64_t, uint64_t) { return false; });
  2793. ASSERT_TRUE(!res);
  2794. EXPECT_EQ(Error::Canceled, res.error());
  2795. }
  2796. TEST(CancelTest, NoCancelPatch) {
  2797. Server svr;
  2798. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2799. res.set_content("Hello World!", "text/plain");
  2800. });
  2801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2802. auto se = detail::scope_exit([&] {
  2803. svr.stop();
  2804. thread.join();
  2805. ASSERT_FALSE(svr.is_running());
  2806. });
  2807. svr.wait_until_ready();
  2808. Client cli(HOST, PORT);
  2809. cli.set_connection_timeout(std::chrono::seconds(5));
  2810. auto res =
  2811. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2812. "application/json", [](uint64_t, uint64_t) { return true; });
  2813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2814. EXPECT_EQ("Hello World!", res->body);
  2815. EXPECT_EQ(StatusCode::OK_200, res->status);
  2816. }
  2817. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2818. Server svr;
  2819. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2820. res.set_content("Hello World!", "text/plain");
  2821. });
  2822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2823. auto se = detail::scope_exit([&] {
  2824. svr.stop();
  2825. thread.join();
  2826. ASSERT_FALSE(svr.is_running());
  2827. });
  2828. svr.wait_until_ready();
  2829. Client cli(HOST, PORT);
  2830. cli.set_connection_timeout(std::chrono::seconds(5));
  2831. auto res =
  2832. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2833. "application/json", [](uint64_t, uint64_t) { return false; });
  2834. ASSERT_TRUE(!res);
  2835. EXPECT_EQ(Error::Canceled, res.error());
  2836. }
  2837. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2838. Server svr;
  2839. svr.set_payload_max_length(200 * 1024 * 1024);
  2840. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2841. res.set_content(LARGE_DATA, "text/plain");
  2842. });
  2843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2844. auto se = detail::scope_exit([&] {
  2845. svr.stop();
  2846. thread.join();
  2847. ASSERT_FALSE(svr.is_running());
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, PORT);
  2851. cli.set_payload_max_length(200 * 1024 * 1024);
  2852. cli.set_connection_timeout(std::chrono::seconds(5));
  2853. auto res =
  2854. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2855. "application/json", [](uint64_t, uint64_t) { return false; });
  2856. ASSERT_TRUE(!res);
  2857. EXPECT_EQ(Error::Canceled, res.error());
  2858. }
  2859. TEST(CancelTest, NoCancelDelete) {
  2860. Server svr;
  2861. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2862. res.set_content("Hello World!", "text/plain");
  2863. });
  2864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2865. auto se = detail::scope_exit([&] {
  2866. svr.stop();
  2867. thread.join();
  2868. ASSERT_FALSE(svr.is_running());
  2869. });
  2870. svr.wait_until_ready();
  2871. Client cli(HOST, PORT);
  2872. cli.set_connection_timeout(std::chrono::seconds(5));
  2873. auto res =
  2874. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2875. "application/json", [](uint64_t, uint64_t) { return true; });
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ("Hello World!", res->body);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2881. Server svr;
  2882. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2883. res.set_content("Hello World!", "text/plain");
  2884. });
  2885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2886. auto se = detail::scope_exit([&] {
  2887. svr.stop();
  2888. thread.join();
  2889. ASSERT_FALSE(svr.is_running());
  2890. });
  2891. svr.wait_until_ready();
  2892. Client cli(HOST, PORT);
  2893. cli.set_connection_timeout(std::chrono::seconds(5));
  2894. auto res =
  2895. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2896. "application/json", [](uint64_t, uint64_t) { return false; });
  2897. ASSERT_TRUE(!res);
  2898. EXPECT_EQ(Error::Canceled, res.error());
  2899. }
  2900. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2901. Server svr;
  2902. svr.set_payload_max_length(200 * 1024 * 1024);
  2903. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2904. res.set_content(LARGE_DATA, "text/plain");
  2905. });
  2906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2907. auto se = detail::scope_exit([&] {
  2908. svr.stop();
  2909. thread.join();
  2910. ASSERT_FALSE(svr.is_running());
  2911. });
  2912. svr.wait_until_ready();
  2913. Client cli(HOST, PORT);
  2914. cli.set_payload_max_length(200 * 1024 * 1024);
  2915. cli.set_connection_timeout(std::chrono::seconds(5));
  2916. auto res =
  2917. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2918. "application/json", [](uint64_t, uint64_t) { return false; });
  2919. ASSERT_TRUE(!res);
  2920. EXPECT_EQ(Error::Canceled, res.error());
  2921. }
  2922. // One stop() from another thread ends a request that waits for the response
  2923. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2924. Server svr;
  2925. std::atomic<bool> received{false};
  2926. std::atomic<bool> done{false};
  2927. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2928. received.store(true);
  2929. while (!done.load()) {
  2930. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2931. }
  2932. res.set_content("Hello World!", "text/plain");
  2933. });
  2934. auto port = svr.bind_to_any_port(HOST);
  2935. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2936. Client cli(HOST, port);
  2937. cli.set_read_timeout(std::chrono::seconds(30));
  2938. std::future<Result> request;
  2939. auto se = detail::scope_exit([&] {
  2940. done.store(true);
  2941. svr.stop();
  2942. thread.join();
  2943. ASSERT_FALSE(svr.is_running());
  2944. });
  2945. svr.wait_until_ready();
  2946. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  2947. for (int i = 0; i < 500 && !received.load(); ++i) {
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2949. }
  2950. ASSERT_TRUE(received.load());
  2951. // Let the client block in the wait for the response
  2952. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2953. auto start = std::chrono::steady_clock::now();
  2954. cli.stop();
  2955. ASSERT_EQ(std::future_status::ready,
  2956. request.wait_for(std::chrono::seconds(5)));
  2957. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  2958. auto res = request.get();
  2959. ASSERT_TRUE(!res);
  2960. EXPECT_EQ(Error::Read, res.error());
  2961. }
  2962. static std::string remove_whitespace(const std::string &input) {
  2963. std::string output;
  2964. output.reserve(input.size());
  2965. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2966. [](unsigned char c) { return !std::isspace(c); });
  2967. return output;
  2968. }
  2969. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2970. auto host = "httpbingo.org";
  2971. auto path = std::string{"/basic-auth/hello/world"};
  2972. #ifdef CPPHTTPLIB_SSL_ENABLED
  2973. auto port = 443;
  2974. SSLClient cli(host, port);
  2975. #else
  2976. auto port = 80;
  2977. Client cli(host, port);
  2978. #endif
  2979. {
  2980. auto res = cli.Get(path);
  2981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2982. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2983. }
  2984. {
  2985. auto res = cli.Get(
  2986. path, Headers{make_basic_authentication_header("hello", "world")});
  2987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2988. auto body = remove_whitespace(res->body);
  2989. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2990. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2991. EXPECT_EQ(StatusCode::OK_200, res->status);
  2992. }
  2993. {
  2994. cli.set_basic_auth("hello", "world");
  2995. auto res = cli.Get(path);
  2996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2997. auto body = remove_whitespace(res->body);
  2998. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2999. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3000. EXPECT_EQ(StatusCode::OK_200, res->status);
  3001. }
  3002. {
  3003. cli.set_basic_auth("hello", "bad");
  3004. auto res = cli.Get(path);
  3005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3006. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3007. }
  3008. {
  3009. cli.set_basic_auth("bad", "world");
  3010. auto res = cli.Get(path);
  3011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3012. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3013. }
  3014. }
  3015. #ifdef CPPHTTPLIB_SSL_ENABLED
  3016. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3017. auto host = "httpbingo.org";
  3018. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3019. auto paths = std::vector<std::string>{
  3020. "/digest-auth/auth/hello/world/MD5",
  3021. "/digest-auth/auth/hello/world/SHA-256",
  3022. };
  3023. auto port = 443;
  3024. SSLClient cli(host, port);
  3025. {
  3026. auto res = cli.Get(unauth_path);
  3027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3028. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3029. }
  3030. {
  3031. cli.set_digest_auth("hello", "world");
  3032. for (const auto &path : paths) {
  3033. auto res = cli.Get(path.c_str());
  3034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3035. auto body = remove_whitespace(res->body);
  3036. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3037. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3038. EXPECT_EQ(StatusCode::OK_200, res->status);
  3039. }
  3040. cli.set_digest_auth("hello", "bad");
  3041. for (const auto &path : paths) {
  3042. auto res = cli.Get(path.c_str());
  3043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3044. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3045. }
  3046. }
  3047. }
  3048. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3049. // comma-separated list of challenges, and each challenge may itself carry a
  3050. // comma-separated auth-param list, so a server can legally offer Basic
  3051. // before Digest, either as two field lines or packed into one. Runs one 401
  3052. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3053. // value() joins them in receipt order) and checks that the retry carries a
  3054. // well-formed Digest Authorization header naming expected_realm.
  3055. static void
  3056. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3057. const std::string &expected_realm) {
  3058. std::atomic<int> hits{0};
  3059. Server svr;
  3060. svr.Get("/x", [&](const Request &req, Response &res) {
  3061. if (++hits == 1) {
  3062. res.status = StatusCode::Unauthorized_401;
  3063. for (const auto &challenge : challenges) {
  3064. res.set_header("WWW-Authenticate", challenge);
  3065. }
  3066. } else {
  3067. auto authorization = req.get_header_value("Authorization");
  3068. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3069. EXPECT_NE(std::string::npos,
  3070. authorization.find("realm=\"" + expected_realm + "\""));
  3071. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3072. res.set_content("ok", "text/plain");
  3073. }
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(2, hits.load());
  3087. }
  3088. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3089. static const char *kDigestChallenge =
  3090. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3091. "algorithm=MD5";
  3092. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3093. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3094. "testrealm");
  3095. }
  3096. // Same challenge list with the schemes in the opposite order, to make sure
  3097. // the fix above didn't just special-case "Basic first".
  3098. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3099. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3100. "testrealm");
  3101. }
  3102. // A comma inside a quoted auth-param value must not be mistaken for the
  3103. // separator between two challenges (or two auth-params).
  3104. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3105. run_digest_challenge_list_test(
  3106. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3107. "algorithm=MD5"},
  3108. "test,realm");
  3109. }
  3110. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3111. // the params and leaves out the fragment.
  3112. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3113. Server svr;
  3114. std::string uri, target;
  3115. svr.Get("/a b", [&](const Request &req, Response &res) {
  3116. auto auth = req.get_header_value("Authorization");
  3117. if (auth.empty()) {
  3118. res.status = StatusCode::Unauthorized_401;
  3119. res.set_header("WWW-Authenticate",
  3120. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3121. return;
  3122. }
  3123. auto b = auth.find("uri=\"") + 5;
  3124. uri = auth.substr(b, auth.find('"', b) - b);
  3125. target = req.target;
  3126. });
  3127. auto port = svr.bind_to_any_port(HOST);
  3128. std::thread t([&]() { svr.listen_after_bind(); });
  3129. auto se = detail::scope_exit([&] {
  3130. svr.stop();
  3131. t.join();
  3132. });
  3133. svr.wait_until_ready();
  3134. Client cli(HOST, port);
  3135. cli.set_digest_auth("hello", "world");
  3136. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ("/a%20b?x=1", target);
  3139. EXPECT_EQ(target, uri);
  3140. }
  3141. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3142. // make_digest_authentication_header() dereferences both unconditionally, so
  3143. // a server sending a challenge missing either one must not be treated as
  3144. // usable -- doing so used to crash the client with std::out_of_range.
  3145. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3146. Server svr;
  3147. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3148. res.status = StatusCode::Unauthorized_401;
  3149. res.set_header("WWW-Authenticate", challenge);
  3150. });
  3151. auto port = svr.bind_to_any_port(HOST);
  3152. std::thread t([&]() { svr.listen_after_bind(); });
  3153. auto se = detail::scope_exit([&] {
  3154. svr.stop();
  3155. t.join();
  3156. });
  3157. svr.wait_until_ready();
  3158. Client cli(HOST, port);
  3159. cli.set_digest_auth("hello", "world");
  3160. auto res = cli.Get("/x");
  3161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3162. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3163. }
  3164. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3165. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3166. }
  3167. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3168. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3169. }
  3170. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3171. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3172. }
  3173. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3174. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3175. // when storing the values, so the header builder has to re-escape them (and
  3176. // keep algorithm a bare token); otherwise the value breaks out of its
  3177. // quoted-string and injects extra auth-params into the client's Authorization.
  3178. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3179. std::atomic<int> hits{0};
  3180. std::string authorization;
  3181. Server svr;
  3182. svr.Get("/x", [&](const Request &req, Response &res) {
  3183. if (++hits == 1) {
  3184. res.status = StatusCode::Unauthorized_401;
  3185. // On the wire the quotes embedded in the values are backslash-escaped.
  3186. res.set_header("WWW-Authenticate",
  3187. "Digest realm=\"testrealm\", "
  3188. "nonce=\"n\\\"; injected=\\\"x\", "
  3189. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3190. } else {
  3191. authorization = req.get_header_value("Authorization");
  3192. res.set_content("ok", "text/plain");
  3193. }
  3194. });
  3195. auto port = svr.bind_to_any_port(HOST);
  3196. std::thread t([&]() { svr.listen_after_bind(); });
  3197. auto se = detail::scope_exit([&] {
  3198. svr.stop();
  3199. t.join();
  3200. });
  3201. svr.wait_until_ready();
  3202. Client cli(HOST, port);
  3203. cli.set_digest_auth("hello", "world");
  3204. auto res = cli.Get("/x");
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(2, hits.load());
  3207. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3208. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3209. // inside its quoted-string rather than starting an "injected" auth-param.
  3210. EXPECT_NE(std::string::npos,
  3211. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3212. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3213. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3214. }
  3215. #endif
  3216. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3217. auto host = "google.com";
  3218. auto another_host = "example.com";
  3219. auto wrong_ip = "0.0.0.0";
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3226. auto res = cli.Get("/");
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3229. }
  3230. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3231. auto host = "google.com";
  3232. auto wrong_ip = "0.0.0.0";
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3239. auto res = cli.Get("/");
  3240. ASSERT_TRUE(!res);
  3241. EXPECT_EQ(Error::Connection, res.error());
  3242. }
  3243. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3244. // A mapped value that is not an IP literal must be resolved. "localhost"
  3245. // resolves from the hosts file, so this test needs no external DNS.
  3246. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3247. auto host = "target.invalid";
  3248. Server svr;
  3249. std::string received_host;
  3250. svr.Get("/hi", [&](const Request &req, Response &res) {
  3251. received_host = req.get_header_value("Host");
  3252. res.set_content("Hello World!", "text/plain");
  3253. });
  3254. auto port = svr.bind_to_any_port(HOST);
  3255. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3256. auto se = detail::scope_exit([&] {
  3257. svr.stop();
  3258. thread.join();
  3259. ASSERT_FALSE(svr.is_running());
  3260. });
  3261. svr.wait_until_ready();
  3262. Client cli(host, port);
  3263. cli.set_direct_hostname_addr_map({{host, HOST}});
  3264. auto res = cli.Get("/hi");
  3265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3266. EXPECT_EQ(StatusCode::OK_200, res->status);
  3267. // The mapping only redirects the connection; the identity stays host_.
  3268. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3269. }
  3270. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3271. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3272. auto host = "target.invalid";
  3273. Server svr;
  3274. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3275. res.set_content("Hello World!", "text/plain");
  3276. });
  3277. auto port = svr.bind_to_any_port("127.0.0.1");
  3278. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3279. auto se = detail::scope_exit([&] {
  3280. svr.stop();
  3281. thread.join();
  3282. ASSERT_FALSE(svr.is_running());
  3283. });
  3284. svr.wait_until_ready();
  3285. Client cli(host, port);
  3286. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3287. auto res = cli.Get("/hi");
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3292. // An empty mapped value must leave host_ as the connection target. Without
  3293. // that guard the empty value would become the host argument, getaddrinfo
  3294. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3295. // loopback - silently connecting somewhere the caller never asked for.
  3296. // The server listens on loopback, so such a fallback would succeed and is
  3297. // therefore observable as a failure of this test.
  3298. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3299. Server svr;
  3300. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3301. res.set_content("Hello World!", "text/plain");
  3302. });
  3303. auto port = svr.bind_to_any_port(HOST);
  3304. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. Client cli(blackhole, port);
  3312. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3313. cli.set_connection_timeout(1);
  3314. auto res = cli.Get("/hi");
  3315. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3316. }
  3317. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3318. auto host = "target.invalid";
  3319. Server svr;
  3320. std::string received_host;
  3321. svr.Get("/hi", [&](const Request &req, Response &res) {
  3322. received_host = req.get_header_value("Host");
  3323. res.set_content("Hello World!", "text/plain");
  3324. });
  3325. auto port = svr.bind_to_any_port("127.0.0.1");
  3326. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3327. auto se = detail::scope_exit([&] {
  3328. svr.stop();
  3329. thread.join();
  3330. ASSERT_FALSE(svr.is_running());
  3331. });
  3332. svr.wait_until_ready();
  3333. Client cli(host, port);
  3334. #pragma GCC diagnostic push
  3335. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3336. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3337. #pragma GCC diagnostic pop
  3338. auto res = cli.Get("/hi");
  3339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3340. EXPECT_EQ(StatusCode::OK_200, res->status);
  3341. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3342. }
  3343. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3344. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3345. Server svr;
  3346. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3347. res.set_content("Hello World!", "text/plain");
  3348. });
  3349. auto port = svr.bind_to_any_port("127.0.0.1");
  3350. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3351. auto se = detail::scope_exit([&] {
  3352. svr.stop();
  3353. thread.join();
  3354. ASSERT_FALSE(svr.is_running());
  3355. });
  3356. svr.wait_until_ready();
  3357. Client cli("127.0.0.1", port);
  3358. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3359. cli.set_connection_timeout(1);
  3360. auto res = cli.Get("/hi");
  3361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3362. EXPECT_EQ(StatusCode::OK_200, res->status);
  3363. }
  3364. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3365. auto host = "httpbingo.org";
  3366. auto path = std::string{"/absolute-redirect/3"};
  3367. #ifdef CPPHTTPLIB_SSL_ENABLED
  3368. SSLClient cli(host);
  3369. #else
  3370. Client cli(host);
  3371. #endif
  3372. cli.set_follow_location(true);
  3373. auto res = cli.Get(path);
  3374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3375. EXPECT_EQ(StatusCode::OK_200, res->status);
  3376. }
  3377. TEST(RedirectTest, Redirect_Online) {
  3378. auto host = "httpbingo.org";
  3379. auto path = std::string{"/redirect/3"};
  3380. #ifdef CPPHTTPLIB_SSL_ENABLED
  3381. SSLClient cli(host);
  3382. #else
  3383. Client cli(host);
  3384. #endif
  3385. cli.set_follow_location(true);
  3386. auto res = cli.Get(path);
  3387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3388. EXPECT_EQ(StatusCode::OK_200, res->status);
  3389. }
  3390. TEST(RelativeRedirectTest, Redirect_Online) {
  3391. auto host = "httpbingo.org";
  3392. auto path = std::string{"/relative-redirect/3"};
  3393. #ifdef CPPHTTPLIB_SSL_ENABLED
  3394. SSLClient cli(host);
  3395. #else
  3396. Client cli(host);
  3397. #endif
  3398. cli.set_follow_location(true);
  3399. auto res = cli.Get(path);
  3400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3401. EXPECT_EQ(StatusCode::OK_200, res->status);
  3402. }
  3403. TEST(TooManyRedirectTest, Redirect_Online) {
  3404. auto host = "httpbingo.org";
  3405. auto path = std::string{"/redirect/21"};
  3406. #ifdef CPPHTTPLIB_SSL_ENABLED
  3407. SSLClient cli(host);
  3408. #else
  3409. Client cli(host);
  3410. #endif
  3411. cli.set_follow_location(true);
  3412. auto res = cli.Get(path);
  3413. ASSERT_TRUE(!res);
  3414. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3415. }
  3416. #ifdef CPPHTTPLIB_SSL_ENABLED
  3417. TEST(YahooRedirectTest, Redirect_Online) {
  3418. Client cli("yahoo.com");
  3419. auto res = cli.Get("/");
  3420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3421. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3422. cli.set_follow_location(true);
  3423. res = cli.Get("/");
  3424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3425. EXPECT_EQ(StatusCode::OK_200, res->status);
  3426. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3427. }
  3428. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3429. #define REDIR_HOST "httpbingo.org"
  3430. #define REDIR_PATH "/redirect-to"
  3431. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3432. SSLClient cli(REDIR_HOST);
  3433. cli.set_follow_location(true);
  3434. auto res =
  3435. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3437. EXPECT_EQ(StatusCode::OK_200, res->status);
  3438. }
  3439. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3440. SSLClient cli(REDIR_HOST);
  3441. cli.set_follow_location(true);
  3442. Params params;
  3443. params.emplace("url", "http://example.com");
  3444. params.emplace("status_code", "302");
  3445. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3447. EXPECT_EQ(StatusCode::OK_200, res->status);
  3448. }
  3449. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3450. SSLClient cli(REDIR_HOST);
  3451. cli.set_follow_location(true);
  3452. Params params;
  3453. params.emplace("url", "http://example.com");
  3454. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3456. EXPECT_EQ(StatusCode::OK_200, res->status);
  3457. }
  3458. TEST(UrlWithSpace, Redirect_Online) {
  3459. SSLClient cli("edge.forgecdn.net");
  3460. cli.set_follow_location(true);
  3461. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3465. }
  3466. #endif
  3467. #if !defined(_WIN32) && !defined(_WIN64)
  3468. TEST(ReceiveSignals, Signal) {
  3469. auto setupSignalHandlers = []() {
  3470. struct sigaction act;
  3471. sigemptyset(&act.sa_mask);
  3472. act.sa_flags = SA_SIGINFO;
  3473. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3474. switch (sig) {
  3475. case SIGINT:
  3476. default: break;
  3477. }
  3478. };
  3479. ::sigaction(SIGINT, &act, nullptr);
  3480. };
  3481. Server svr;
  3482. int port = 0;
  3483. auto thread = std::thread([&]() {
  3484. setupSignalHandlers();
  3485. port = svr.bind_to_any_port(HOST);
  3486. svr.listen_after_bind();
  3487. });
  3488. auto se = detail::scope_exit([&] {
  3489. svr.stop();
  3490. thread.join();
  3491. ASSERT_FALSE(svr.is_running());
  3492. });
  3493. svr.wait_until_ready();
  3494. ASSERT_TRUE(svr.is_running());
  3495. pthread_kill(thread.native_handle(), SIGINT);
  3496. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3497. ASSERT_TRUE(svr.is_running());
  3498. }
  3499. #endif
  3500. TEST(RedirectToDifferentPort, Redirect) {
  3501. Server svr1;
  3502. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3503. res.set_content("Hello World!", "text/plain");
  3504. });
  3505. int svr1_port = 0;
  3506. auto thread1 = std::thread([&]() {
  3507. svr1_port = svr1.bind_to_any_port(HOST);
  3508. svr1.listen_after_bind();
  3509. });
  3510. Server svr2;
  3511. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3512. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3513. });
  3514. int svr2_port = 0;
  3515. auto thread2 = std::thread([&]() {
  3516. svr2_port = svr2.bind_to_any_port(HOST);
  3517. svr2.listen_after_bind();
  3518. });
  3519. auto se = detail::scope_exit([&] {
  3520. svr2.stop();
  3521. thread2.join();
  3522. svr1.stop();
  3523. thread1.join();
  3524. ASSERT_FALSE(svr2.is_running());
  3525. ASSERT_FALSE(svr1.is_running());
  3526. });
  3527. svr1.wait_until_ready();
  3528. svr2.wait_until_ready();
  3529. Client cli("localhost", svr2_port);
  3530. cli.set_follow_location(true);
  3531. auto res = cli.Get("/2");
  3532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3533. EXPECT_EQ(StatusCode::OK_200, res->status);
  3534. EXPECT_EQ("Hello World!", res->body);
  3535. }
  3536. // GET /redir on one server redirects to /target on another port, so the
  3537. // client follows it with a new client.
  3538. static Result
  3539. GetThroughRedirectToDifferentPort(Server::Handler target,
  3540. const std::function<void(Client &)> &setup,
  3541. const Headers &headers = Headers()) {
  3542. Server target_svr;
  3543. target_svr.Get("/target", target);
  3544. int target_port = 0;
  3545. auto target_thread = std::thread([&]() {
  3546. target_port = target_svr.bind_to_any_port(HOST);
  3547. target_svr.listen_after_bind();
  3548. });
  3549. Server origin_svr;
  3550. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3551. res.set_redirect(
  3552. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3553. });
  3554. int origin_port = 0;
  3555. auto origin_thread = std::thread([&]() {
  3556. origin_port = origin_svr.bind_to_any_port(HOST);
  3557. origin_svr.listen_after_bind();
  3558. });
  3559. auto se = detail::scope_exit([&] {
  3560. origin_svr.stop();
  3561. origin_thread.join();
  3562. target_svr.stop();
  3563. target_thread.join();
  3564. });
  3565. target_svr.wait_until_ready();
  3566. origin_svr.wait_until_ready();
  3567. Client cli("localhost", origin_port);
  3568. cli.set_follow_location(true);
  3569. setup(cli);
  3570. return cli.Get("/redir", headers);
  3571. }
  3572. static void
  3573. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3574. std::string captured_authorization;
  3575. auto result = GetThroughRedirectToDifferentPort(
  3576. [&](const Request &req, Response &res) {
  3577. captured_authorization = req.get_header_value("Authorization");
  3578. res.set_content("OK", "text/plain");
  3579. },
  3580. set_auth);
  3581. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3582. EXPECT_EQ(StatusCode::OK_200, result->status);
  3583. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3584. EXPECT_TRUE(captured_authorization.empty());
  3585. }
  3586. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3587. TestDoNotForwardCredentialsOnRedirect(
  3588. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3589. }
  3590. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3591. TestDoNotForwardCredentialsOnRedirect(
  3592. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3593. }
  3594. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3595. std::string captured_cookie;
  3596. auto result = GetThroughRedirectToDifferentPort(
  3597. [&](const Request &req, Response &res) {
  3598. captured_cookie = req.get_header_value("Cookie");
  3599. res.set_content("OK", "text/plain");
  3600. },
  3601. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3602. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3603. EXPECT_EQ(StatusCode::OK_200, result->status);
  3604. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3605. EXPECT_TRUE(captured_cookie.empty());
  3606. }
  3607. TEST(RedirectToSamePort, ForwardCookie) {
  3608. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3609. // header so that ordinary session flows keep working.
  3610. Server svr;
  3611. std::string captured_cookie;
  3612. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3613. res.set_redirect("/target", 302);
  3614. });
  3615. svr.Get("/target", [&](const Request &req, Response &res) {
  3616. captured_cookie = req.get_header_value("Cookie");
  3617. res.set_content("OK", "text/plain");
  3618. });
  3619. auto port = svr.bind_to_any_port(HOST);
  3620. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3621. auto se = detail::scope_exit([&] {
  3622. svr.stop();
  3623. thread.join();
  3624. ASSERT_FALSE(svr.is_running());
  3625. });
  3626. svr.wait_until_ready();
  3627. Client cli(HOST, port);
  3628. cli.set_follow_location(true);
  3629. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3630. auto res = cli.Get("/redir", headers);
  3631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3634. }
  3635. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3636. // The Location alone names the next target, on any origin.
  3637. Server target_svr;
  3638. std::string cross_target;
  3639. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3640. cross_target = req.target;
  3641. res.set_content("OK", "text/plain");
  3642. });
  3643. auto target_port = target_svr.bind_to_any_port(HOST);
  3644. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3645. Server origin_svr;
  3646. std::string same_target;
  3647. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3648. res.set_redirect(
  3649. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3650. });
  3651. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3652. res.set_redirect("/landing", 302);
  3653. });
  3654. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3655. same_target = req.target;
  3656. res.set_content("OK", "text/plain");
  3657. });
  3658. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3659. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3660. auto se = detail::scope_exit([&] {
  3661. origin_svr.stop();
  3662. origin_thread.join();
  3663. target_svr.stop();
  3664. target_thread.join();
  3665. });
  3666. target_svr.wait_until_ready();
  3667. origin_svr.wait_until_ready();
  3668. Client cli("localhost", origin_port);
  3669. cli.set_follow_location(true);
  3670. Request req;
  3671. req.method = "GET";
  3672. req.params = {{"api_key", "SECRET"}};
  3673. req.path = "/cross";
  3674. auto res = cli.send(req);
  3675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3676. EXPECT_EQ("/landing", cross_target);
  3677. req.path = "/same";
  3678. res = cli.send(req);
  3679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3680. EXPECT_EQ("/landing", same_target);
  3681. }
  3682. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3683. std::string authorization;
  3684. std::string trace_id;
  3685. auto result = GetThroughRedirectToDifferentPort(
  3686. [&](const Request &req, Response &res) {
  3687. authorization = req.get_header_value("Authorization");
  3688. trace_id = req.get_header_value("X-Trace-Id");
  3689. res.set_content("OK", "text/plain");
  3690. },
  3691. [](Client &cli) {
  3692. cli.set_default_headers(
  3693. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3694. });
  3695. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3696. EXPECT_EQ(StatusCode::OK_200, result->status);
  3697. // Like a header given with the request, a default one goes along unless it
  3698. // carries credentials (RFC 9110 15.4).
  3699. EXPECT_TRUE(authorization.empty());
  3700. EXPECT_EQ("42", trace_id);
  3701. }
  3702. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3703. auto result = GetThroughRedirectToDifferentPort(
  3704. [](const Request &, Response &res) {
  3705. res.set_content(std::string(2048, 'x'), "text/plain");
  3706. },
  3707. [](Client &cli) { cli.set_payload_max_length(1024); });
  3708. EXPECT_FALSE(result);
  3709. }
  3710. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3711. auto result = GetThroughRedirectToDifferentPort(
  3712. [](const Request &req, Response &res) {
  3713. // Answer after a second, or once the client gives up.
  3714. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3715. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3716. }
  3717. res.set_content("late", "text/plain");
  3718. },
  3719. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3720. ASSERT_FALSE(result);
  3721. EXPECT_EQ(Error::Read, result.error());
  3722. }
  3723. #ifdef CPPHTTPLIB_SSL_ENABLED
  3724. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3725. auto result = GetThroughRedirectToDifferentPort(
  3726. [](const Request &, Response &res) {
  3727. res.status = StatusCode::Unauthorized_401;
  3728. res.set_header("WWW-Authenticate",
  3729. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3730. },
  3731. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3732. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3733. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3734. }
  3735. #endif
  3736. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3737. Server svr;
  3738. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3739. // Port number that overflows int — should not crash
  3740. res.set_redirect("http://localhost:99999999999999999999/target");
  3741. });
  3742. auto port = svr.bind_to_any_port(HOST);
  3743. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3744. auto se = detail::scope_exit([&] {
  3745. svr.stop();
  3746. thread.join();
  3747. ASSERT_FALSE(svr.is_running());
  3748. });
  3749. svr.wait_until_ready();
  3750. Client cli(HOST, port);
  3751. cli.set_follow_location(true);
  3752. auto res = cli.Get("/redir");
  3753. // Should fail gracefully, not crash (no valid response due to bad port)
  3754. EXPECT_FALSE(res);
  3755. }
  3756. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3757. Server svr;
  3758. auto port = svr.bind_to_any_port(HOST);
  3759. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3760. // The server's own port followed by junk must not be followed
  3761. res.set_redirect("http://" + std::string(HOST) + ":" +
  3762. std::to_string(port) + "junk/target");
  3763. });
  3764. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3765. res.set_content("target", "text/plain");
  3766. });
  3767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3768. auto se = detail::scope_exit([&] {
  3769. svr.stop();
  3770. thread.join();
  3771. ASSERT_FALSE(svr.is_running());
  3772. });
  3773. svr.wait_until_ready();
  3774. Client cli(HOST, port);
  3775. cli.set_follow_location(true);
  3776. auto res = cli.Get("/redir");
  3777. EXPECT_FALSE(res);
  3778. }
  3779. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3780. Server svr;
  3781. std::atomic<bool> followed{false};
  3782. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3783. res.status = StatusCode::NotModified_304;
  3784. res.set_header("Location", "/target");
  3785. });
  3786. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3787. res.status = StatusCode::UseProxy_305;
  3788. res.set_header("Location", "/target");
  3789. });
  3790. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3791. followed = true;
  3792. res.set_content("target", "text/plain");
  3793. });
  3794. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3795. auto se = detail::scope_exit([&] {
  3796. svr.stop();
  3797. th.join();
  3798. ASSERT_FALSE(svr.is_running());
  3799. });
  3800. svr.wait_until_ready();
  3801. Client cli("localhost", PORT);
  3802. cli.set_follow_location(true);
  3803. auto res = cli.Get("/304");
  3804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3805. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3806. res = cli.Get("/305");
  3807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3808. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3809. EXPECT_FALSE(followed);
  3810. }
  3811. TEST(RedirectFromPageWithContent, Redirect) {
  3812. Server svr;
  3813. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3814. res.set_content("___", "text/plain");
  3815. res.set_redirect("/2");
  3816. });
  3817. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3818. res.set_content("Hello World!", "text/plain");
  3819. });
  3820. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3821. auto se = detail::scope_exit([&] {
  3822. svr.stop();
  3823. th.join();
  3824. ASSERT_FALSE(svr.is_running());
  3825. });
  3826. svr.wait_until_ready();
  3827. {
  3828. Client cli("localhost", PORT);
  3829. cli.set_follow_location(true);
  3830. std::string body;
  3831. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3832. body.append(data, data_length);
  3833. return true;
  3834. });
  3835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3836. EXPECT_EQ(StatusCode::OK_200, res->status);
  3837. EXPECT_EQ("Hello World!", body);
  3838. }
  3839. {
  3840. Client cli("localhost", PORT);
  3841. std::string body;
  3842. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3843. body.append(data, data_length);
  3844. return true;
  3845. });
  3846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3847. EXPECT_EQ(StatusCode::Found_302, res->status);
  3848. EXPECT_EQ("___", body);
  3849. }
  3850. }
  3851. // A server can close the connection after a request with "Connection: close"
  3852. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3853. // redirected request must go out on a new connection.
  3854. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3855. #ifndef _WIN32
  3856. signal(SIGPIPE, SIG_IGN);
  3857. #endif
  3858. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3859. default_socket_options(srv);
  3860. sockaddr_in addr{};
  3861. addr.sin_family = AF_INET;
  3862. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3863. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3864. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3865. ASSERT_EQ(0, ::listen(srv, 2));
  3866. auto send_text = [](socket_t sock, const std::string &text) {
  3867. ::send(sock,
  3868. #ifdef _WIN32
  3869. static_cast<const char *>(text.c_str()),
  3870. static_cast<int>(text.size()),
  3871. #else
  3872. text.c_str(), text.size(),
  3873. #endif
  3874. 0);
  3875. };
  3876. auto reused = false;
  3877. auto server_thread = std::thread([&] {
  3878. char buf[4096];
  3879. auto first = ::accept(srv, nullptr, nullptr);
  3880. if (first == INVALID_SOCKET) { return; }
  3881. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3882. ::recv(first, buf, sizeof(buf), 0);
  3883. send_text(
  3884. first,
  3885. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3886. auto next = first;
  3887. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3888. reused = true;
  3889. } else {
  3890. detail::close_socket(first);
  3891. next = ::accept(srv, nullptr, nullptr);
  3892. if (next == INVALID_SOCKET) { return; }
  3893. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3894. ::recv(next, buf, sizeof(buf), 0);
  3895. }
  3896. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3897. "Connection: close\r\n\r\nok");
  3898. detail::close_socket(next);
  3899. });
  3900. Client cli("127.0.0.1", PORT + 2);
  3901. cli.set_follow_location(true);
  3902. cli.set_read_timeout(5, 0);
  3903. auto res = cli.Get("/1");
  3904. server_thread.join();
  3905. detail::close_socket(srv);
  3906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3907. EXPECT_EQ(StatusCode::OK_200, res->status);
  3908. EXPECT_EQ("ok", res->body);
  3909. EXPECT_FALSE(reused);
  3910. }
  3911. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3912. Server svr;
  3913. auto port_str = std::to_string(PORT);
  3914. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3915. auto expected_host = "[::1]:" + port_str;
  3916. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3917. res.set_content("___", "text/plain");
  3918. // res.set_redirect("/2");
  3919. res.set_redirect(redirect_url);
  3920. });
  3921. svr.Get("/2", [&](const Request &req, Response &res) {
  3922. auto host_header = req.headers.find("Host");
  3923. ASSERT_TRUE(host_header != req.headers.end());
  3924. EXPECT_EQ(expected_host, host_header->second);
  3925. res.set_content("Hello World!", "text/plain");
  3926. });
  3927. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3928. auto se = detail::scope_exit([&] {
  3929. svr.stop();
  3930. th.join();
  3931. ASSERT_FALSE(svr.is_running());
  3932. });
  3933. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3934. // actually starts anything, so the condition !svr.is_running() will
  3935. // always remain true, and the loop never stops.
  3936. // This basically counts how many milliseconds have passed since the
  3937. // call to svr.listen(), and if after 5 seconds nothing started yet
  3938. // aborts the test.
  3939. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3940. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3941. ASSERT_LT(milliseconds, 5000U);
  3942. }
  3943. {
  3944. Client cli("::1", PORT);
  3945. cli.set_follow_location(true);
  3946. std::string body;
  3947. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3948. body.append(data, data_length);
  3949. return true;
  3950. });
  3951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. EXPECT_EQ("Hello World!", body);
  3954. }
  3955. {
  3956. Client cli("::1", PORT);
  3957. std::string body;
  3958. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3959. body.append(data, data_length);
  3960. return true;
  3961. });
  3962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3963. EXPECT_EQ(StatusCode::Found_302, res->status);
  3964. EXPECT_EQ("___", body);
  3965. }
  3966. }
  3967. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3968. Server svr;
  3969. svr.Get("/foo", [](const Request &req, Response &res) {
  3970. auto a = req.params.find("a");
  3971. if (a != req.params.end()) {
  3972. res.set_content((*a).second, "text/plain");
  3973. res.status = StatusCode::OK_200;
  3974. } else {
  3975. res.status = StatusCode::BadRequest_400;
  3976. }
  3977. });
  3978. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3979. auto se = detail::scope_exit([&] {
  3980. svr.stop();
  3981. thread.join();
  3982. ASSERT_FALSE(svr.is_running());
  3983. });
  3984. svr.wait_until_ready();
  3985. {
  3986. Client cli(HOST, PORT);
  3987. cli.set_path_encode(false);
  3988. auto res = cli.Get("/foo?a=explicitly+encoded");
  3989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3990. EXPECT_EQ(StatusCode::OK_200, res->status);
  3991. // This expects it back with a space, as the `+` won't have been
  3992. // url-encoded, and server-side the params get decoded turning `+`
  3993. // into spaces.
  3994. EXPECT_EQ("explicitly encoded", res->body);
  3995. }
  3996. }
  3997. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3998. // When path encoding is disabled the client must transmit the supplied
  3999. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4000. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4001. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4002. // than a space (0x20). Assert on the raw wire target to catch this.
  4003. Server svr;
  4004. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4005. svr.Get("/foo", [&](const Request &req, Response &res) {
  4006. EXPECT_EQ(expected_target, req.target);
  4007. res.status = StatusCode::OK_200;
  4008. });
  4009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4010. auto se = detail::scope_exit([&] {
  4011. svr.stop();
  4012. thread.join();
  4013. ASSERT_FALSE(svr.is_running());
  4014. });
  4015. svr.wait_until_ready();
  4016. {
  4017. Client cli(HOST, PORT);
  4018. cli.set_path_encode(false);
  4019. auto res = cli.Get(expected_target.c_str());
  4020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4021. EXPECT_EQ(StatusCode::OK_200, res->status);
  4022. }
  4023. }
  4024. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4025. // `open_stream()` used to skip the path encoding that the buffered send
  4026. // path applies, so the same `path` produced different bytes in the request
  4027. // line depending on which API was used. Assert the two agree.
  4028. Server svr;
  4029. std::string target;
  4030. svr.Get(".*", [&](const Request &req, Response &res) {
  4031. target = req.target;
  4032. res.status = StatusCode::OK_200;
  4033. });
  4034. auto port = svr.bind_to_any_port(HOST);
  4035. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4036. auto se = detail::scope_exit([&] {
  4037. svr.stop();
  4038. thread.join();
  4039. ASSERT_FALSE(svr.is_running());
  4040. });
  4041. svr.wait_until_ready();
  4042. struct {
  4043. const char *path;
  4044. const char *expected;
  4045. } cases[] = {
  4046. {"/a b?x=1", "/a%20b?x=1"},
  4047. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4048. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4049. };
  4050. for (const auto &c : cases) {
  4051. Client cli(HOST, port);
  4052. target.clear();
  4053. auto res = cli.Get(c.path);
  4054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4055. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4056. auto buffered_target = target;
  4057. target.clear();
  4058. auto handle = cli.open_stream("GET", c.path);
  4059. EXPECT_TRUE(handle.is_valid())
  4060. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4061. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4062. }
  4063. }
  4064. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4065. // The `set_path_encode(false)` contract — transmit the supplied target
  4066. // verbatim — must hold for the streaming API too.
  4067. Server svr;
  4068. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4069. std::string target;
  4070. svr.Get("/foo", [&](const Request &req, Response &res) {
  4071. target = req.target;
  4072. res.status = StatusCode::OK_200;
  4073. });
  4074. auto port = svr.bind_to_any_port(HOST);
  4075. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4076. auto se = detail::scope_exit([&] {
  4077. svr.stop();
  4078. thread.join();
  4079. ASSERT_FALSE(svr.is_running());
  4080. });
  4081. svr.wait_until_ready();
  4082. {
  4083. Client cli(HOST, port);
  4084. cli.set_path_encode(false);
  4085. auto handle = cli.open_stream("GET", expected_target);
  4086. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4087. EXPECT_EQ(expected_target, target);
  4088. }
  4089. }
  4090. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4091. // With path encoding enabled a CR/LF in the target is percent-encoded
  4092. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4093. // write_request_line still backstops `set_path_encode(false)`, which is
  4094. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4095. Server svr;
  4096. // Captured before routing: the decoded path contains a newline, which a
  4097. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4098. std::string target;
  4099. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4100. target = req.target;
  4101. res.status = StatusCode::OK_200;
  4102. return Server::HandlerResponse::Handled;
  4103. });
  4104. auto port = svr.bind_to_any_port(HOST);
  4105. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4106. auto se = detail::scope_exit([&] {
  4107. svr.stop();
  4108. thread.join();
  4109. ASSERT_FALSE(svr.is_running());
  4110. });
  4111. svr.wait_until_ready();
  4112. {
  4113. Client cli(HOST, port);
  4114. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4115. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4116. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4117. }
  4118. }
  4119. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4120. // Every control character is percent-encoded, not just CR/LF, so the target
  4121. // passes the request-target check in write_request_line.
  4122. Server svr;
  4123. std::string target;
  4124. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4125. target = req.target;
  4126. res.status = StatusCode::OK_200;
  4127. return Server::HandlerResponse::Handled;
  4128. });
  4129. auto port = svr.bind_to_any_port(HOST);
  4130. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4131. auto se = detail::scope_exit([&] {
  4132. svr.stop();
  4133. thread.join();
  4134. ASSERT_FALSE(svr.is_running());
  4135. });
  4136. svr.wait_until_ready();
  4137. {
  4138. Client cli(HOST, port);
  4139. auto res = cli.Get("/a\tb\x1b\x7f");
  4140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4141. EXPECT_EQ("/a%09b%1B%7F", target);
  4142. }
  4143. }
  4144. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4145. // Nothing may reach the wire: a raw CR/LF target would split the request
  4146. // line and inject headers.
  4147. Server svr;
  4148. // Pre-routing so that "not called" means nothing reached the server at all,
  4149. // rather than merely failing to match a handler pattern.
  4150. auto handler_called = false;
  4151. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4152. handler_called = true;
  4153. res.status = StatusCode::OK_200;
  4154. return Server::HandlerResponse::Handled;
  4155. });
  4156. auto port = svr.bind_to_any_port(HOST);
  4157. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4158. auto se = detail::scope_exit([&] {
  4159. svr.stop();
  4160. thread.join();
  4161. ASSERT_FALSE(svr.is_running());
  4162. });
  4163. svr.wait_until_ready();
  4164. {
  4165. Client cli(HOST, port);
  4166. cli.set_path_encode(false);
  4167. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4168. EXPECT_FALSE(handle.is_valid());
  4169. EXPECT_EQ(Error::Write, handle.error);
  4170. EXPECT_FALSE(handler_called);
  4171. }
  4172. }
  4173. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4174. // Which of the two branches runs is decided by whether the query component
  4175. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4176. // an empty query and must still fall back to building one from
  4177. // `req.params`, while a non-empty query must win over `req.params`.
  4178. Server svr;
  4179. std::string target;
  4180. svr.Get("/foo", [&](const Request &req, Response &res) {
  4181. target = req.target;
  4182. res.status = StatusCode::OK_200;
  4183. });
  4184. auto port = svr.bind_to_any_port(HOST);
  4185. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4186. auto se = detail::scope_exit([&] {
  4187. svr.stop();
  4188. thread.join();
  4189. ASSERT_FALSE(svr.is_running());
  4190. });
  4191. svr.wait_until_ready();
  4192. {
  4193. // Trailing `?` -> empty query component -> `req.params` is used.
  4194. Client cli(HOST, port);
  4195. Request req;
  4196. req.method = "GET";
  4197. req.path = "/foo?";
  4198. req.params.emplace("a", "1");
  4199. target.clear();
  4200. auto res = cli.send(req);
  4201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4202. EXPECT_EQ("/foo?a=1", target);
  4203. }
  4204. {
  4205. // Non-empty query in `req.path` -> `req.params` is not appended.
  4206. Client cli(HOST, port);
  4207. Request req;
  4208. req.method = "GET";
  4209. req.path = "/foo?b=2";
  4210. req.params.emplace("a", "1");
  4211. target.clear();
  4212. auto res = cli.send(req);
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ("/foo?b=2", target);
  4215. }
  4216. }
  4217. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4218. Server svr;
  4219. svr.Get("/", [](const Request &req, Response &) {
  4220. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4221. });
  4222. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4223. auto se = detail::scope_exit([&] {
  4224. svr.stop();
  4225. thread.join();
  4226. ASSERT_FALSE(svr.is_running());
  4227. });
  4228. svr.wait_until_ready();
  4229. {
  4230. Client cli(HOST, PORT);
  4231. cli.set_path_encode(false);
  4232. auto res = cli.Get("/?something=%0A");
  4233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4234. EXPECT_EQ(StatusCode::OK_200, res->status);
  4235. }
  4236. }
  4237. TEST(BindServerTest, BindDualStack) {
  4238. Server svr;
  4239. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4240. res.set_content("Hello World!", "text/plain");
  4241. });
  4242. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4243. auto se = detail::scope_exit([&] {
  4244. svr.stop();
  4245. thread.join();
  4246. ASSERT_FALSE(svr.is_running());
  4247. });
  4248. svr.wait_until_ready();
  4249. {
  4250. Client cli("127.0.0.1", PORT);
  4251. auto res = cli.Get("/1");
  4252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4253. EXPECT_EQ(StatusCode::OK_200, res->status);
  4254. EXPECT_EQ("Hello World!", res->body);
  4255. }
  4256. {
  4257. Client cli("::1", PORT);
  4258. auto res = cli.Get("/1");
  4259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4260. EXPECT_EQ(StatusCode::OK_200, res->status);
  4261. EXPECT_EQ("Hello World!", res->body);
  4262. }
  4263. }
  4264. TEST(BindServerTest, BindAndListenSeparately) {
  4265. Server svr;
  4266. int port = svr.bind_to_any_port("0.0.0.0");
  4267. ASSERT_TRUE(svr.is_valid());
  4268. ASSERT_TRUE(port > 0);
  4269. svr.stop();
  4270. }
  4271. // Reports whether anything is still listening on a loopback port. A plain
  4272. // connect() is used instead of a Client request because a socket left bound by
  4273. // mistake accepts the connection into its backlog and never answers, which
  4274. // would hang the test instead of failing it.
  4275. static bool is_loopback_port_accepting(int port) {
  4276. sockaddr_in addr{};
  4277. addr.sin_family = AF_INET;
  4278. addr.sin_port = htons(static_cast<uint16_t>(port));
  4279. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4280. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4281. EXPECT_NE(sock, INVALID_SOCKET);
  4282. if (sock == INVALID_SOCKET) { return false; }
  4283. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4284. static_cast<socklen_t>(sizeof(addr)));
  4285. detail::close_socket(sock);
  4286. return ret == 0;
  4287. }
  4288. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4289. Server svr;
  4290. auto port = svr.bind_to_any_port("127.0.0.1");
  4291. ASSERT_TRUE(port > 0);
  4292. svr.stop();
  4293. // bind_to_any_port() already called listen(2), so until stop() closed the
  4294. // descriptor the port kept accepting connections into the backlog. ASSERT
  4295. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4296. // below blocks forever in the accept loop.
  4297. ASSERT_FALSE(is_loopback_port_accepting(port));
  4298. // Nothing is left to accept on, so listen_after_bind() must report failure
  4299. // instead of returning success without ever serving.
  4300. EXPECT_FALSE(svr.listen_after_bind());
  4301. // The failed listen marks the server decommissioned, so a waiter returns
  4302. // instead of spinning forever.
  4303. svr.wait_until_ready();
  4304. }
  4305. #ifdef CPPHTTPLIB_SSL_ENABLED
  4306. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4308. CLIENT_CA_CERT_DIR);
  4309. int port = svr.bind_to_any_port("0.0.0.0");
  4310. ASSERT_TRUE(svr.is_valid());
  4311. ASSERT_TRUE(port > 0);
  4312. svr.stop();
  4313. }
  4314. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4315. // or a rejected CustomRoute() registration would not stop the server binding.
  4316. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4318. CLIENT_CA_CERT_DIR);
  4319. ASSERT_TRUE(svr.is_valid());
  4320. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4321. EXPECT_FALSE(svr.is_valid());
  4322. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4323. }
  4324. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4325. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4326. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4327. int port = svr.bind_to_any_port("0.0.0.0");
  4328. ASSERT_TRUE(svr.is_valid());
  4329. ASSERT_TRUE(port > 0);
  4330. svr.stop();
  4331. }
  4332. TEST(BindServerTest, UpdateCertsPem) {
  4333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4334. int port = svr.bind_to_any_port("0.0.0.0");
  4335. ASSERT_TRUE(svr.is_valid());
  4336. ASSERT_TRUE(port > 0);
  4337. // Read PEM files
  4338. std::string cert_pem, key_pem, ca_pem;
  4339. read_file(SERVER_CERT_FILE, cert_pem);
  4340. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4341. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4342. // Update server certificates using PEM API
  4343. ASSERT_TRUE(
  4344. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4345. ASSERT_TRUE(svr.is_valid());
  4346. svr.stop();
  4347. }
  4348. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4349. // Start server with client CA (enables client auth)
  4350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4351. ASSERT_TRUE(svr.is_valid());
  4352. bool handler_called = false;
  4353. svr.Get("/test", [&](const Request &req, Response &res) {
  4354. handler_called = true;
  4355. // Verify client certificate is present
  4356. auto cert = req.peer_cert();
  4357. EXPECT_TRUE(static_cast<bool>(cert));
  4358. res.set_content("ok", "text/plain");
  4359. });
  4360. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4361. auto se = detail::scope_exit([&] {
  4362. svr.stop();
  4363. t.join();
  4364. ASSERT_FALSE(svr.is_running());
  4365. });
  4366. svr.wait_until_ready();
  4367. // Read PEM files
  4368. std::string cert_pem, key_pem, ca_pem;
  4369. read_file(SERVER_CERT_FILE, cert_pem);
  4370. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4371. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4372. // Update server certificates and client CA using PEM API while server running
  4373. ASSERT_TRUE(
  4374. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4375. // Connect with client certificate
  4376. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4377. cli.enable_server_certificate_verification(false);
  4378. cli.set_connection_timeout(30);
  4379. auto res = cli.Get("/test");
  4380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4381. ASSERT_EQ(StatusCode::OK_200, res->status);
  4382. ASSERT_TRUE(handler_called);
  4383. EXPECT_EQ("ok", res->body);
  4384. }
  4385. // Puts a CA that did not sign the client's certificate in the old one's place.
  4386. static bool replace_client_ca(SSLServer &svr) {
  4387. std::string cert_pem, key_pem, ca_pem;
  4388. read_file(SERVER_CERT_FILE, cert_pem);
  4389. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4390. read_file(SERVER_CERT2_FILE, ca_pem);
  4391. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4392. ca_pem.c_str());
  4393. }
  4394. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4395. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4396. ASSERT_TRUE(svr.is_valid());
  4397. svr.Get("/test", [](const Request &, Response &res) {
  4398. res.set_content("ok", "text/plain");
  4399. });
  4400. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4401. auto se = detail::scope_exit([&] {
  4402. svr.stop();
  4403. t.join();
  4404. ASSERT_FALSE(svr.is_running());
  4405. });
  4406. svr.wait_until_ready();
  4407. auto get = [] {
  4408. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4409. cli.enable_server_certificate_verification(false);
  4410. return cli.Get("/test");
  4411. };
  4412. ASSERT_TRUE(get());
  4413. ASSERT_TRUE(replace_client_ca(svr));
  4414. EXPECT_FALSE(get());
  4415. }
  4416. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4417. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4419. ASSERT_TRUE(svr.is_valid());
  4420. tls::set_verify_callback(svr.tls_context(),
  4421. [](const tls::VerifyContext &) -> bool {
  4422. throw std::runtime_error("verify");
  4423. });
  4424. svr.Get("/test", [](const Request &, Response &res) {
  4425. res.set_content("ok", "text/plain");
  4426. });
  4427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4428. auto se = detail::scope_exit([&] {
  4429. svr.stop();
  4430. t.join();
  4431. ASSERT_FALSE(svr.is_running());
  4432. });
  4433. svr.wait_until_ready();
  4434. auto get = [] {
  4435. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4436. cli.enable_server_certificate_verification(false);
  4437. return cli.Get("/test");
  4438. };
  4439. EXPECT_FALSE(get());
  4440. // The handshake is over, so an update does not wait for it.
  4441. std::string cert_pem, key_pem;
  4442. read_file(SERVER_CERT_FILE, cert_pem);
  4443. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4444. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4445. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4446. return v.preverify_ok;
  4447. });
  4448. auto res = get();
  4449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4450. EXPECT_EQ("ok", res->body);
  4451. }
  4452. #endif
  4453. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4454. // Sends each request over a new connection with a client certificate,
  4455. // resuming the session of the one before when there is one.
  4456. class ResumingClient {
  4457. public:
  4458. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4459. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4460. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4461. SSL_FILETYPE_PEM);
  4462. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4463. // callback, not through SSL_get1_session().
  4464. SSL_CTX_set_app_data(ctx_, this);
  4465. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4466. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4467. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4468. auto self = static_cast<ResumingClient *>(
  4469. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4470. SSL_SESSION_free(self->session_);
  4471. self->session_ = session;
  4472. return 1; // Keeps the reference
  4473. });
  4474. }
  4475. ~ResumingClient() {
  4476. SSL_SESSION_free(session_);
  4477. SSL_CTX_free(ctx_);
  4478. }
  4479. // Tells whether the request was answered.
  4480. bool get() {
  4481. auto error = Error::Success;
  4482. auto sock = detail::create_client_socket(
  4483. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4484. /*connection_timeout_sec=*/5, 0,
  4485. /*read_timeout_sec=*/5, 0,
  4486. /*write_timeout_sec=*/5, 0, std::string(), error);
  4487. if (sock == INVALID_SOCKET) { return false; }
  4488. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4489. auto ssl = SSL_new(ctx_);
  4490. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4491. SSL_set_fd(ssl, static_cast<int>(sock));
  4492. if (session_) { SSL_set_session(ssl, session_); }
  4493. if (SSL_connect(ssl) != 1) { return false; }
  4494. reused_ = SSL_session_reused(ssl) == 1;
  4495. // Reading the response also takes in a TLS 1.3 session ticket.
  4496. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4497. "Connection: close\r\n\r\n";
  4498. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4499. std::string res;
  4500. char buf[256];
  4501. int n;
  4502. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4503. res.append(buf, static_cast<size_t>(n));
  4504. }
  4505. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4506. SSL_shutdown(ssl);
  4507. return res.find("200 OK") != std::string::npos;
  4508. }
  4509. // Whether the last connection resumed a session
  4510. bool reused() const { return reused_; }
  4511. private:
  4512. SSL_CTX *ctx_;
  4513. SSL_SESSION *session_ = nullptr;
  4514. bool reused_ = false;
  4515. };
  4516. // A client that resumes its session gets through, but not once the client CA
  4517. // has changed, as a resumed session does not show the certificate again.
  4518. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4520. ASSERT_TRUE(svr.is_valid());
  4521. svr.Get("/test", [](const Request &, Response &res) {
  4522. res.set_content("ok", "text/plain");
  4523. });
  4524. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4525. auto se = detail::scope_exit([&] {
  4526. svr.stop();
  4527. t.join();
  4528. ASSERT_FALSE(svr.is_running());
  4529. });
  4530. svr.wait_until_ready();
  4531. ResumingClient cli;
  4532. ASSERT_TRUE(cli.get());
  4533. ASSERT_TRUE(cli.get());
  4534. EXPECT_TRUE(cli.reused());
  4535. ASSERT_TRUE(replace_client_ca(svr));
  4536. EXPECT_FALSE(cli.get());
  4537. }
  4538. // A resumed session does not show the certificate again, so the server does
  4539. // not resume one with a verify callback to run on it.
  4540. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4542. ASSERT_TRUE(svr.is_valid());
  4543. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4544. return v.preverify_ok;
  4545. });
  4546. svr.Get("/test", [](const Request &, Response &res) {
  4547. res.set_content("ok", "text/plain");
  4548. });
  4549. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4550. auto se = detail::scope_exit([&] {
  4551. svr.stop();
  4552. t.join();
  4553. ASSERT_FALSE(svr.is_running());
  4554. });
  4555. svr.wait_until_ready();
  4556. ResumingClient cli;
  4557. ASSERT_TRUE(cli.get());
  4558. ASSERT_TRUE(cli.get());
  4559. EXPECT_FALSE(cli.reused());
  4560. }
  4561. #endif
  4562. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4563. // wolfSSL shares its session cache between contexts, so a resumed session
  4564. // could carry a client certificate checked against another server's CA, or
  4565. // against a client CA since replaced.
  4566. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4568. ASSERT_TRUE(svr.is_valid());
  4569. // Trusts a CA that did not sign the client's certificate.
  4570. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4571. ASSERT_TRUE(other.is_valid());
  4572. for (auto s : {&svr, &other}) {
  4573. s->Get("/test", [](const Request &, Response &res) {
  4574. res.set_content("ok", "text/plain");
  4575. });
  4576. }
  4577. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4578. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4579. auto se = detail::scope_exit([&] {
  4580. other.stop();
  4581. svr.stop();
  4582. t2.join();
  4583. t.join();
  4584. });
  4585. svr.wait_until_ready();
  4586. other.wait_until_ready();
  4587. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4588. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4589. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4590. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4591. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4592. ASSERT_EQ(WOLFSSL_SUCCESS,
  4593. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4594. WOLFSSL_FILETYPE_PEM));
  4595. WOLFSSL_SESSION *session = nullptr;
  4596. auto session_se = detail::scope_exit([&] {
  4597. if (session) { wolfSSL_SESSION_free(session); }
  4598. });
  4599. // A request over a new connection, resuming `session` when there is one and
  4600. // keeping the connection's own in its place. Tells whether it was answered.
  4601. auto get = [&](int port) {
  4602. auto error = Error::Success;
  4603. auto sock = detail::create_client_socket(
  4604. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4605. /*connection_timeout_sec=*/5, 0,
  4606. /*read_timeout_sec=*/5, 0,
  4607. /*write_timeout_sec=*/5, 0, std::string(), error);
  4608. if (sock == INVALID_SOCKET) { return false; }
  4609. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4610. auto ssl = wolfSSL_new(ctx);
  4611. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4612. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4613. if (session) { wolfSSL_set_session(ssl, session); }
  4614. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4615. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4616. "Connection: close\r\n\r\n";
  4617. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4618. std::string res;
  4619. char buf[256];
  4620. int n;
  4621. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4622. res.append(buf, static_cast<size_t>(n));
  4623. }
  4624. wolfSSL_shutdown(ssl);
  4625. if (session) { wolfSSL_SESSION_free(session); }
  4626. session = wolfSSL_get1_session(ssl);
  4627. return res.find("200 OK") != std::string::npos;
  4628. };
  4629. ASSERT_TRUE(get(PORT));
  4630. EXPECT_FALSE(get(PORT + 1));
  4631. ASSERT_TRUE(get(PORT));
  4632. ASSERT_TRUE(replace_client_ca(svr));
  4633. EXPECT_FALSE(get(PORT));
  4634. }
  4635. #endif
  4636. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4637. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4638. ASSERT_TRUE(svr.is_valid());
  4639. svr.Get("/test", [](const Request &, Response &res) {
  4640. res.set_content("ok", "text/plain");
  4641. });
  4642. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4643. auto se = detail::scope_exit([&] {
  4644. svr.stop();
  4645. t.join();
  4646. ASSERT_FALSE(svr.is_running());
  4647. });
  4648. svr.wait_until_ready();
  4649. // A connection that sends no ClientHello keeps its handshake in progress,
  4650. // once the server has had a moment to start it.
  4651. auto error = Error::Success;
  4652. auto sock = detail::create_client_socket(
  4653. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4654. /*connection_timeout_sec=*/5, 0,
  4655. /*read_timeout_sec=*/5, 0,
  4656. /*write_timeout_sec=*/5, 0, std::string(), error);
  4657. ASSERT_NE(INVALID_SOCKET, sock);
  4658. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4659. std::string cert_pem, key_pem;
  4660. read_file(SERVER_CERT_FILE, cert_pem);
  4661. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4662. auto update = std::async(std::launch::async, [&]() {
  4663. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4664. });
  4665. EXPECT_EQ(std::future_status::timeout,
  4666. update.wait_for(std::chrono::milliseconds(200)));
  4667. detail::close_socket(sock);
  4668. EXPECT_TRUE(update.get());
  4669. SSLClient cli(HOST, PORT);
  4670. cli.enable_server_certificate_verification(false);
  4671. auto res = cli.Get("/test");
  4672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. }
  4675. #endif
  4676. TEST(ErrorHandlerTest, ContentLength) {
  4677. Server svr;
  4678. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4679. res.status = StatusCode::OK_200;
  4680. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4681. "text/html"); // <= Content-Length still 13
  4682. });
  4683. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4684. res.set_content("Hello World!\n", "text/plain");
  4685. res.status = 524;
  4686. });
  4687. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4688. auto se = detail::scope_exit([&] {
  4689. svr.stop();
  4690. thread.join();
  4691. ASSERT_FALSE(svr.is_running());
  4692. });
  4693. svr.wait_until_ready();
  4694. {
  4695. Client cli(HOST, PORT);
  4696. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4698. EXPECT_EQ(StatusCode::OK_200, res->status);
  4699. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4700. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4701. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4702. }
  4703. }
  4704. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4705. TEST(ExceptionTest, WithoutExceptionHandler) {
  4706. Server svr;
  4707. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4708. throw std::runtime_error("exception...");
  4709. });
  4710. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4711. throw std::runtime_error("exception\r\n...");
  4712. });
  4713. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4714. auto se = detail::scope_exit([&] {
  4715. svr.stop();
  4716. listen_thread.join();
  4717. ASSERT_FALSE(svr.is_running());
  4718. });
  4719. svr.wait_until_ready();
  4720. Client cli("localhost", PORT);
  4721. {
  4722. auto res = cli.Get("/exception");
  4723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4724. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4725. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4726. }
  4727. {
  4728. auto res = cli.Get("/unknown");
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4731. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4732. }
  4733. }
  4734. TEST(ExceptionTest, WithExceptionHandler) {
  4735. Server svr;
  4736. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4737. std::exception_ptr ep) {
  4738. EXPECT_FALSE(ep == nullptr);
  4739. try {
  4740. std::rethrow_exception(ep);
  4741. } catch (std::exception &e) {
  4742. EXPECT_EQ("abc", std::string(e.what()));
  4743. } catch (...) {}
  4744. res.status = StatusCode::InternalServerError_500;
  4745. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4746. "text/html"); // <= Content-Length still 13 at this point
  4747. });
  4748. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4749. res.set_content("Hello World!\n", "text/plain");
  4750. throw std::runtime_error("abc");
  4751. });
  4752. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4753. auto se = detail::scope_exit([&] {
  4754. svr.stop();
  4755. thread.join();
  4756. ASSERT_FALSE(svr.is_running());
  4757. });
  4758. svr.wait_until_ready();
  4759. for (size_t i = 0; i < 10; i++) {
  4760. Client cli(HOST, PORT);
  4761. for (size_t j = 0; j < 100; j++) {
  4762. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4764. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4765. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4766. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4767. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4768. }
  4769. cli.set_keep_alive(true);
  4770. for (size_t j = 0; j < 100; j++) {
  4771. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4773. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4774. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4775. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4776. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4777. }
  4778. }
  4779. }
  4780. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4781. Server svr;
  4782. svr.set_exception_handler(
  4783. [](const Request &, Response &res, std::exception_ptr) {
  4784. res.set_content("oops", "text/plain");
  4785. });
  4786. svr.Get("/throw", [](const Request &, Response &) {
  4787. throw std::runtime_error("throw");
  4788. });
  4789. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4790. res.status = StatusCode::Created_201;
  4791. throw std::runtime_error("created-then-throw");
  4792. });
  4793. auto port = svr.bind_to_any_port(HOST);
  4794. ASSERT_GT(port, 0);
  4795. thread t = thread([&] { svr.listen_after_bind(); });
  4796. auto se = detail::scope_exit([&] {
  4797. svr.stop();
  4798. t.join();
  4799. ASSERT_FALSE(svr.is_running());
  4800. });
  4801. svr.wait_until_ready();
  4802. Client cli(HOST, port);
  4803. for (auto path : {"/throw", "/created-then-throw"}) {
  4804. auto res = cli.Get(path);
  4805. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4806. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4807. }
  4808. }
  4809. TEST(ExceptionTest, AndErrorHandler) {
  4810. Server svr;
  4811. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4812. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4813. });
  4814. svr.set_exception_handler(
  4815. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4816. EXPECT_FALSE(ep == nullptr);
  4817. try {
  4818. std::rethrow_exception(ep);
  4819. } catch (std::exception &e) {
  4820. res.set_content(e.what(), "text/html");
  4821. } catch (...) {}
  4822. res.status = StatusCode::InternalServerError_500;
  4823. });
  4824. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4825. throw std::runtime_error("EXCEPTION");
  4826. });
  4827. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4828. res.set_content("ERROR", "text/html");
  4829. res.status = StatusCode::InternalServerError_500;
  4830. });
  4831. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4832. auto se = detail::scope_exit([&] {
  4833. svr.stop();
  4834. thread.join();
  4835. ASSERT_FALSE(svr.is_running());
  4836. });
  4837. svr.wait_until_ready();
  4838. Client cli(HOST, PORT);
  4839. {
  4840. auto res = cli.Get("/exception");
  4841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4842. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4843. EXPECT_EQ("EXCEPTION", res->body);
  4844. }
  4845. {
  4846. auto res = cli.Get("/error");
  4847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4848. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4849. EXPECT_EQ("ERROR", res->body);
  4850. }
  4851. {
  4852. auto res = cli.Get("/invalid");
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4855. EXPECT_EQ("NOT_FOUND", res->body);
  4856. }
  4857. }
  4858. #endif
  4859. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4860. // An exception from a user callback outside process_request()'s try/catch
  4861. // used to unwind into the task queue - which does not catch - and terminate
  4862. // the process. Each test below runs the server on a single worker thread: a
  4863. // guard that catches the exception but still loses the thread would otherwise
  4864. // be hidden by a spare worker serving the follow-up request. Note that a
  4865. // regression here aborts the whole test binary rather than failing one test.
  4866. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4867. Server svr;
  4868. svr.new_task_queue = [] { return new ThreadPool(1); };
  4869. std::atomic<int> reported{0};
  4870. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4871. if (err == Error::UserCallbackException) { reported++; }
  4872. });
  4873. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4874. res.set_content_provider(
  4875. 1024, "text/plain",
  4876. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4877. sink.write("hello", 5);
  4878. throw std::runtime_error("from the content provider");
  4879. });
  4880. });
  4881. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4882. res.set_content("ok", "text/plain");
  4883. });
  4884. auto port = svr.bind_to_any_port(HOST);
  4885. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4886. auto se = detail::scope_exit([&] {
  4887. svr.stop();
  4888. listen_thread.join();
  4889. ASSERT_FALSE(svr.is_running());
  4890. });
  4891. svr.wait_until_ready();
  4892. {
  4893. Client cli(HOST, port);
  4894. cli.set_read_timeout(5, 0);
  4895. EXPECT_FALSE(cli.Get("/throw"));
  4896. }
  4897. EXPECT_TRUE(svr.is_running());
  4898. EXPECT_EQ(1, reported.load());
  4899. // A request on a fresh connection is still served.
  4900. {
  4901. Client cli(HOST, port);
  4902. auto res = cli.Get("/ok");
  4903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4904. EXPECT_EQ(StatusCode::OK_200, res->status);
  4905. EXPECT_EQ("ok", res->body);
  4906. }
  4907. }
  4908. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4909. Server svr;
  4910. svr.new_task_queue = [] { return new ThreadPool(1); };
  4911. std::atomic<bool> should_throw{true};
  4912. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4913. res.set_content("hi", "text/plain");
  4914. });
  4915. svr.set_post_routing_handler(
  4916. [&](const Request & /*req*/, Response & /*res*/) {
  4917. if (should_throw) {
  4918. throw std::runtime_error("from the post-routing handler");
  4919. }
  4920. });
  4921. auto port = svr.bind_to_any_port(HOST);
  4922. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4923. auto se = detail::scope_exit([&] {
  4924. svr.stop();
  4925. listen_thread.join();
  4926. ASSERT_FALSE(svr.is_running());
  4927. });
  4928. svr.wait_until_ready();
  4929. {
  4930. Client cli(HOST, port);
  4931. cli.set_read_timeout(5, 0);
  4932. EXPECT_FALSE(cli.Get("/hi"));
  4933. }
  4934. EXPECT_TRUE(svr.is_running());
  4935. should_throw = false;
  4936. {
  4937. Client cli(HOST, port);
  4938. auto res = cli.Get("/hi");
  4939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. EXPECT_EQ("hi", res->body);
  4942. }
  4943. }
  4944. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4945. // The guard reports the caught exception through the error logger, which is
  4946. // a user callback too. A logger that throws has to be contained as well, or
  4947. // the process would terminate from inside the catch.
  4948. Server svr;
  4949. svr.new_task_queue = [] { return new ThreadPool(1); };
  4950. std::atomic<int> reported{0};
  4951. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4952. if (err == Error::UserCallbackException) {
  4953. reported++;
  4954. throw std::runtime_error("from the error logger");
  4955. }
  4956. });
  4957. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4958. res.set_content_provider(
  4959. 1024, "text/plain",
  4960. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4961. sink.write("hello", 5);
  4962. throw std::runtime_error("from the content provider");
  4963. });
  4964. });
  4965. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4966. res.set_content("ok", "text/plain");
  4967. });
  4968. auto port = svr.bind_to_any_port(HOST);
  4969. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4970. auto se = detail::scope_exit([&] {
  4971. svr.stop();
  4972. listen_thread.join();
  4973. ASSERT_FALSE(svr.is_running());
  4974. });
  4975. svr.wait_until_ready();
  4976. {
  4977. Client cli(HOST, port);
  4978. cli.set_read_timeout(5, 0);
  4979. EXPECT_FALSE(cli.Get("/throw"));
  4980. }
  4981. EXPECT_TRUE(svr.is_running());
  4982. EXPECT_EQ(1, reported.load());
  4983. {
  4984. Client cli(HOST, port);
  4985. auto res = cli.Get("/ok");
  4986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4987. EXPECT_EQ(StatusCode::OK_200, res->status);
  4988. EXPECT_EQ("ok", res->body);
  4989. }
  4990. }
  4991. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4992. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4993. // so the exception unwinds through the ws::WebSocket object on its way to
  4994. // the guard. None of the HTTP cases above cross that.
  4995. Server svr;
  4996. svr.new_task_queue = [] { return new ThreadPool(1); };
  4997. std::atomic<int> reported{0};
  4998. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4999. if (err == Error::UserCallbackException) { reported++; }
  5000. });
  5001. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5002. throw std::runtime_error("from the WebSocket handler");
  5003. });
  5004. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5005. res.set_content("ok", "text/plain");
  5006. });
  5007. auto port = svr.bind_to_any_port(HOST);
  5008. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. listen_thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. {
  5016. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5017. "/ws");
  5018. auto res = client.connect();
  5019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5020. // The server dropped the connection instead of dying.
  5021. std::string msg;
  5022. EXPECT_FALSE(client.read(msg));
  5023. client.close();
  5024. }
  5025. EXPECT_TRUE(svr.is_running());
  5026. EXPECT_EQ(1, reported.load());
  5027. {
  5028. Client cli(HOST, port);
  5029. auto res = cli.Get("/ok");
  5030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. EXPECT_EQ("ok", res->body);
  5033. }
  5034. }
  5035. #ifdef CPPHTTPLIB_SSL_ENABLED
  5036. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5037. // SSLServer::process_and_close_socket() is a separate overload with its own
  5038. // guard, so it is exercised on its own.
  5039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5040. ASSERT_TRUE(svr.is_valid());
  5041. svr.new_task_queue = [] { return new ThreadPool(1); };
  5042. std::atomic<int> reported{0};
  5043. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5044. if (err == Error::UserCallbackException) { reported++; }
  5045. });
  5046. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5047. res.set_content_provider(
  5048. 1024, "text/plain",
  5049. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5050. sink.write("hello", 5);
  5051. throw std::runtime_error("from the content provider");
  5052. });
  5053. });
  5054. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5055. res.set_content("ok", "text/plain");
  5056. });
  5057. auto port = svr.bind_to_any_port(HOST);
  5058. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5059. auto se = detail::scope_exit([&] {
  5060. svr.stop();
  5061. listen_thread.join();
  5062. ASSERT_FALSE(svr.is_running());
  5063. });
  5064. svr.wait_until_ready();
  5065. {
  5066. SSLClient cli(HOST, port);
  5067. cli.enable_server_certificate_verification(false);
  5068. cli.set_read_timeout(5, 0);
  5069. EXPECT_FALSE(cli.Get("/throw"));
  5070. }
  5071. EXPECT_TRUE(svr.is_running());
  5072. EXPECT_EQ(1, reported.load());
  5073. {
  5074. SSLClient cli(HOST, port);
  5075. cli.enable_server_certificate_verification(false);
  5076. auto res = cli.Get("/ok");
  5077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. EXPECT_EQ("ok", res->body);
  5080. }
  5081. }
  5082. #endif
  5083. #endif
  5084. TEST(NoContentTest, ContentLength) {
  5085. Server svr;
  5086. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5087. res.status = StatusCode::NoContent_204;
  5088. });
  5089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5090. auto se = detail::scope_exit([&] {
  5091. svr.stop();
  5092. thread.join();
  5093. ASSERT_FALSE(svr.is_running());
  5094. });
  5095. svr.wait_until_ready();
  5096. {
  5097. Client cli(HOST, PORT);
  5098. auto res = cli.Get("/hi");
  5099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5100. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5101. // RFC 9110 8.6: none in a 204 response
  5102. EXPECT_FALSE(res->has_header("Content-Length"));
  5103. }
  5104. }
  5105. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5106. Server svr;
  5107. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5108. res.set_header("Content-Length", "5");
  5109. res.set_content("hello world", "text/plain");
  5110. });
  5111. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5112. // A body that reads as the last chunk, were it taken as chunked
  5113. res.set_header("Transfer-Encoding", "chunked");
  5114. res.set_content("0\r\n\r\n", "text/plain");
  5115. });
  5116. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5117. res.set_header("Content-Length", "2");
  5118. res.set_content_provider(5, "text/plain",
  5119. [](size_t offset, size_t length, DataSink &sink) {
  5120. sink.write(&"hello"[offset], length);
  5121. return true;
  5122. });
  5123. });
  5124. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5125. res.set_header("Content-Length", "1234");
  5126. });
  5127. thread t = thread([&] { svr.listen(HOST, PORT); });
  5128. auto se = detail::scope_exit([&] {
  5129. svr.stop();
  5130. t.join();
  5131. ASSERT_FALSE(svr.is_running());
  5132. });
  5133. svr.wait_until_ready();
  5134. Client cli(HOST, PORT);
  5135. cli.set_read_timeout(1, 0);
  5136. auto expect_body = [&](const Result &res, const std::string &body) {
  5137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5138. EXPECT_EQ(body, res->body);
  5139. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5140. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5141. };
  5142. Headers identity{{"Accept-Encoding", ""}};
  5143. expect_body(cli.Get("/body", identity), "hello world");
  5144. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5145. expect_body(cli.Get("/body",
  5146. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5147. "he");
  5148. expect_body(cli.Get("/provider", identity), "hello");
  5149. expect_body(cli.Get("/empty", identity), "");
  5150. // A HEAD response may give the length of the body a GET would get.
  5151. auto res = cli.Head("/empty");
  5152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5153. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5154. }
  5155. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5156. Server svr;
  5157. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5158. res.set_content("short", "text/plain");
  5159. });
  5160. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5161. res.body += " with a footer";
  5162. res.set_header("Transfer-Encoding", "chunked");
  5163. });
  5164. thread t = thread([&] { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. t.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. cli.set_read_timeout(1, 0);
  5173. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5175. EXPECT_EQ("short with a footer", res->body);
  5176. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5177. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5178. }
  5179. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5180. Server svr;
  5181. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5182. res.set_header("Content-Length", "3");
  5183. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5184. sink.write("abc", 3);
  5185. sink.done();
  5186. return true;
  5187. });
  5188. });
  5189. thread t = thread([&] { svr.listen(HOST, PORT); });
  5190. auto se = detail::scope_exit([&] {
  5191. svr.stop();
  5192. t.join();
  5193. ASSERT_FALSE(svr.is_running());
  5194. });
  5195. svr.wait_until_ready();
  5196. Client cli(HOST, PORT);
  5197. cli.set_keep_alive(true);
  5198. auto res = cli.Get("/");
  5199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5200. EXPECT_EQ("abc", res->body);
  5201. EXPECT_FALSE(res->has_header("Content-Length"));
  5202. EXPECT_EQ("close", res->get_header_value("Connection"));
  5203. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5204. // No body to delimit
  5205. auto head = cli.Head("/");
  5206. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5207. EXPECT_FALSE(head->has_header("Connection"));
  5208. }
  5209. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5210. #ifdef CPPHTTPLIB_SSL_ENABLED
  5211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5212. ASSERT_TRUE(svr.is_valid());
  5213. #else
  5214. Server svr;
  5215. #endif
  5216. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5217. if (req.path == "/routing_handler") {
  5218. res.set_header("PRE_ROUTING", "on");
  5219. res.set_content("Routing Handler", "text/plain");
  5220. return httplib::Server::HandlerResponse::Handled;
  5221. }
  5222. return httplib::Server::HandlerResponse::Unhandled;
  5223. });
  5224. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5225. res.set_content("Error", "text/html");
  5226. });
  5227. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5228. if (req.path == "/routing_handler") {
  5229. res.set_header("POST_ROUTING", "on");
  5230. }
  5231. });
  5232. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5233. res.set_content("Hello World!\n", "text/plain");
  5234. });
  5235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5236. auto se = detail::scope_exit([&] {
  5237. svr.stop();
  5238. thread.join();
  5239. ASSERT_FALSE(svr.is_running());
  5240. });
  5241. svr.wait_until_ready();
  5242. {
  5243. #ifdef CPPHTTPLIB_SSL_ENABLED
  5244. SSLClient cli(HOST, PORT);
  5245. cli.enable_server_certificate_verification(false);
  5246. #else
  5247. Client cli(HOST, PORT);
  5248. #endif
  5249. auto res = cli.Get("/routing_handler");
  5250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5251. EXPECT_EQ(StatusCode::OK_200, res->status);
  5252. EXPECT_EQ("Routing Handler", res->body);
  5253. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5254. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5255. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5256. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5257. }
  5258. {
  5259. #ifdef CPPHTTPLIB_SSL_ENABLED
  5260. SSLClient cli(HOST, PORT);
  5261. cli.enable_server_certificate_verification(false);
  5262. #else
  5263. Client cli(HOST, PORT);
  5264. #endif
  5265. auto res = cli.Get("/hi");
  5266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5267. EXPECT_EQ(StatusCode::OK_200, res->status);
  5268. EXPECT_EQ("Hello World!\n", res->body);
  5269. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5270. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5271. }
  5272. {
  5273. #ifdef CPPHTTPLIB_SSL_ENABLED
  5274. SSLClient cli(HOST, PORT);
  5275. cli.enable_server_certificate_verification(false);
  5276. #else
  5277. Client cli(HOST, PORT);
  5278. #endif
  5279. auto res = cli.Get("/aaa");
  5280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5282. EXPECT_EQ("Error", res->body);
  5283. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5284. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5285. }
  5286. }
  5287. TEST(RequestHandlerTest, PreRequestHandler) {
  5288. auto route_path = "/user/:user";
  5289. Server svr;
  5290. svr.Get("/hi", [](const Request &, Response &res) {
  5291. res.set_content("hi", "text/plain");
  5292. });
  5293. svr.Get(route_path, [](const Request &req, Response &res) {
  5294. res.set_content(req.path_params.at("user"), "text/plain");
  5295. });
  5296. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5297. if (req.matched_route == route_path) {
  5298. auto user = req.path_params.at("user");
  5299. if (user != "john") {
  5300. res.status = StatusCode::Forbidden_403;
  5301. res.set_content("error", "text/html");
  5302. return Server::HandlerResponse::Handled;
  5303. }
  5304. }
  5305. return Server::HandlerResponse::Unhandled;
  5306. });
  5307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5308. auto se = detail::scope_exit([&] {
  5309. svr.stop();
  5310. thread.join();
  5311. ASSERT_FALSE(svr.is_running());
  5312. });
  5313. svr.wait_until_ready();
  5314. Client cli(HOST, PORT);
  5315. {
  5316. auto res = cli.Get("/hi");
  5317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. EXPECT_EQ("hi", res->body);
  5320. }
  5321. {
  5322. auto res = cli.Get("/user/john");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. EXPECT_EQ(StatusCode::OK_200, res->status);
  5325. EXPECT_EQ("john", res->body);
  5326. }
  5327. {
  5328. auto res = cli.Get("/user/invalid-user");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5331. EXPECT_EQ("error", res->body);
  5332. }
  5333. }
  5334. // The pre-request handler must run before the request body is read, so a
  5335. // rejected request never forces the server to buffer a (potentially large)
  5336. // body. Here the posted body is larger than the payload limit: if the body
  5337. // were read first the server would answer 413, but because the pre-request
  5338. // handler runs first it answers 403 and the body is never read.
  5339. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5340. Server svr;
  5341. svr.set_payload_max_length(8);
  5342. auto handler_ran = false;
  5343. svr.Post("/reject", [&](const Request &req, Response &res) {
  5344. handler_ran = true;
  5345. res.set_content(req.body, "text/plain");
  5346. });
  5347. svr.Post("/accept", [](const Request &req, Response &res) {
  5348. res.set_content(req.body, "text/plain");
  5349. });
  5350. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5351. if (req.matched_route == "/reject") {
  5352. res.status = StatusCode::Forbidden_403;
  5353. res.set_content("denied", "text/plain");
  5354. return Server::HandlerResponse::Handled;
  5355. }
  5356. return Server::HandlerResponse::Unhandled;
  5357. });
  5358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5359. auto se = detail::scope_exit([&] {
  5360. svr.stop();
  5361. thread.join();
  5362. ASSERT_FALSE(svr.is_running());
  5363. });
  5364. svr.wait_until_ready();
  5365. Client cli(HOST, PORT);
  5366. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5367. // rejects with 403 before the body is read, so 413 is never reached.
  5368. {
  5369. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5372. EXPECT_EQ("denied", res->body);
  5373. EXPECT_FALSE(handler_ran);
  5374. }
  5375. // An approved route still reads the body and enforces the payload limit.
  5376. {
  5377. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5380. }
  5381. }
  5382. TEST(UserDataTest, BasicOperations) {
  5383. httplib::UserData ud;
  5384. // Initially empty
  5385. EXPECT_FALSE(ud.has("key"));
  5386. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5387. // set and get
  5388. ud.set("key", 42);
  5389. EXPECT_TRUE(ud.has("key"));
  5390. auto *p = ud.get<int>("key");
  5391. ASSERT_NE(nullptr, p);
  5392. EXPECT_EQ(42, *p);
  5393. // Type mismatch → nullptr
  5394. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5395. // Overwrite with different type
  5396. ud.set("key", std::string("hello"));
  5397. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5398. auto *s = ud.get<std::string>("key");
  5399. ASSERT_NE(nullptr, s);
  5400. EXPECT_EQ("hello", *s);
  5401. // erase
  5402. ud.erase("key");
  5403. EXPECT_FALSE(ud.has("key"));
  5404. // clear
  5405. ud.set("a", 1);
  5406. ud.set("b", 2);
  5407. ud.clear();
  5408. EXPECT_FALSE(ud.has("a"));
  5409. EXPECT_FALSE(ud.has("b"));
  5410. }
  5411. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5412. struct AuthCtx {
  5413. std::string user_id;
  5414. };
  5415. Server svr;
  5416. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5417. res.user_data.set("auth", AuthCtx{"alice"});
  5418. return Server::HandlerResponse::Unhandled;
  5419. });
  5420. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5421. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5422. ASSERT_NE(nullptr, ctx);
  5423. res.set_content("Hello " + ctx->user_id, "text/plain");
  5424. });
  5425. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5426. auto se = detail::scope_exit([&] {
  5427. svr.stop();
  5428. thread.join();
  5429. ASSERT_FALSE(svr.is_running());
  5430. });
  5431. svr.wait_until_ready();
  5432. Client cli(HOST, PORT);
  5433. auto res = cli.Get("/me");
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ("Hello alice", res->body);
  5437. }
  5438. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5439. struct RoleCtx {
  5440. std::string role;
  5441. };
  5442. Server svr;
  5443. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5444. res.user_data.set("role", RoleCtx{"admin"});
  5445. return Server::HandlerResponse::Unhandled;
  5446. });
  5447. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5448. auto *ctx = res.user_data.get<RoleCtx>("role");
  5449. ASSERT_NE(nullptr, ctx);
  5450. res.set_content(ctx->role, "text/plain");
  5451. });
  5452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5453. auto se = detail::scope_exit([&] {
  5454. svr.stop();
  5455. thread.join();
  5456. ASSERT_FALSE(svr.is_running());
  5457. });
  5458. svr.wait_until_ready();
  5459. Client cli(HOST, PORT);
  5460. auto res = cli.Get("/role");
  5461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5462. EXPECT_EQ(StatusCode::OK_200, res->status);
  5463. EXPECT_EQ("admin", res->body);
  5464. }
  5465. TEST(InvalidFormatTest, StatusCode) {
  5466. Server svr;
  5467. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5468. res.set_content("Hello World!\n", "text/plain");
  5469. res.status = 9999; // Status should be a three-digit code...
  5470. });
  5471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5472. auto se = detail::scope_exit([&] {
  5473. svr.stop();
  5474. thread.join();
  5475. ASSERT_FALSE(svr.is_running());
  5476. });
  5477. svr.wait_until_ready();
  5478. {
  5479. Client cli(HOST, PORT);
  5480. auto res = cli.Get("/hi");
  5481. ASSERT_FALSE(res);
  5482. }
  5483. }
  5484. TEST(URLFragmentTest, WithFragment) {
  5485. Server svr;
  5486. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5487. EXPECT_TRUE(req.target == "/hi");
  5488. });
  5489. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5490. auto se = detail::scope_exit([&] {
  5491. svr.stop();
  5492. thread.join();
  5493. ASSERT_FALSE(svr.is_running());
  5494. });
  5495. svr.wait_until_ready();
  5496. {
  5497. Client cli(HOST, PORT);
  5498. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5499. EXPECT_TRUE(res);
  5500. EXPECT_EQ(StatusCode::OK_200, res->status);
  5501. res = cli.Get("/hi%23key1=val1=key2=val2");
  5502. EXPECT_TRUE(res);
  5503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5504. }
  5505. }
  5506. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5507. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5508. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5509. Server svr;
  5510. std::vector<std::string> targets;
  5511. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5512. targets.push_back(req.target);
  5513. });
  5514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5515. auto se = detail::scope_exit([&] {
  5516. svr.stop();
  5517. thread.join();
  5518. ASSERT_FALSE(svr.is_running());
  5519. });
  5520. svr.wait_until_ready();
  5521. Client cli(HOST, PORT);
  5522. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5523. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5524. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5525. // A '?' after the '#' belongs to the fragment, not to the query.
  5526. Request req;
  5527. req.method = "GET";
  5528. req.path = "/hi#f?x=1";
  5529. req.params.emplace("a", "1");
  5530. Response res;
  5531. auto error = Error::Success;
  5532. EXPECT_TRUE(cli.send(req, res, error));
  5533. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5534. "/hi?a=1"}),
  5535. targets);
  5536. }
  5537. TEST(HeaderWriter, SetHeaderWriter) {
  5538. Server svr;
  5539. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5540. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5541. return detail::write_headers(strm, hdrs);
  5542. });
  5543. svr.Get("/hi", [](const Request &req, Response &res) {
  5544. auto it = req.headers.find("CustomClientHeader");
  5545. EXPECT_TRUE(it != req.headers.end());
  5546. EXPECT_EQ(it->second, "CustomClientValue");
  5547. res.set_content("Hello World!\n", "text/plain");
  5548. });
  5549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5550. auto se = detail::scope_exit([&] {
  5551. svr.stop();
  5552. thread.join();
  5553. ASSERT_FALSE(svr.is_running());
  5554. });
  5555. svr.wait_until_ready();
  5556. {
  5557. Client cli(HOST, PORT);
  5558. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5559. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5560. return detail::write_headers(strm, hdrs);
  5561. });
  5562. auto res = cli.Get("/hi");
  5563. EXPECT_TRUE(res);
  5564. EXPECT_EQ(StatusCode::OK_200, res->status);
  5565. auto it = res->headers.find("CustomServerHeader");
  5566. EXPECT_TRUE(it != res->headers.end());
  5567. EXPECT_EQ(it->second, "CustomServerValue");
  5568. }
  5569. }
  5570. class ServerTest : public ::testing::Test {
  5571. protected:
  5572. ServerTest()
  5573. : cli_(HOST, PORT)
  5574. #ifdef CPPHTTPLIB_SSL_ENABLED
  5575. ,
  5576. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5577. #endif
  5578. {
  5579. #ifdef CPPHTTPLIB_SSL_ENABLED
  5580. cli_.enable_server_certificate_verification(false);
  5581. #endif
  5582. // Allow LARGE_DATA (100MB) responses
  5583. cli_.set_payload_max_length(200 * 1024 * 1024);
  5584. }
  5585. virtual void SetUp() {
  5586. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5587. svr_.set_payload_max_length(200 * 1024 * 1024);
  5588. svr_.set_mount_point("/", "./www");
  5589. svr_.set_mount_point("/mount", "./www2");
  5590. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5591. svr_.Get("/hi",
  5592. [&](const Request & /*req*/, Response &res) {
  5593. res.set_content("Hello World!", "text/plain");
  5594. })
  5595. .Get("/file_content",
  5596. [&](const Request & /*req*/, Response &res) {
  5597. res.set_file_content("./www/dir/test.html");
  5598. })
  5599. .Get("/file_content_with_content_type",
  5600. [&](const Request & /*req*/, Response &res) {
  5601. res.set_file_content("./www/file", "text/plain");
  5602. })
  5603. .Get("/invalid_file_content",
  5604. [&](const Request & /*req*/, Response &res) {
  5605. res.set_file_content("./www/dir/invalid_file_path");
  5606. })
  5607. .Get("/http_response_splitting",
  5608. [&](const Request & /*req*/, Response &res) {
  5609. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5610. EXPECT_EQ(0U, res.headers.size());
  5611. EXPECT_FALSE(res.has_header("a"));
  5612. res.set_header("a", "1\nSet-Cookie: a=1");
  5613. EXPECT_EQ(0U, res.headers.size());
  5614. EXPECT_FALSE(res.has_header("a"));
  5615. res.set_header("a", "1\rSet-Cookie: a=1");
  5616. EXPECT_EQ(0U, res.headers.size());
  5617. EXPECT_FALSE(res.has_header("a"));
  5618. res.set_header("a\r\nb", "0");
  5619. EXPECT_EQ(0U, res.headers.size());
  5620. EXPECT_FALSE(res.has_header("a"));
  5621. res.set_header("a\rb", "0");
  5622. EXPECT_EQ(0U, res.headers.size());
  5623. EXPECT_FALSE(res.has_header("a"));
  5624. res.set_header("a\nb", "0");
  5625. EXPECT_EQ(0U, res.headers.size());
  5626. EXPECT_FALSE(res.has_header("a"));
  5627. res.set_redirect("1\r\nSet-Cookie: a=1");
  5628. EXPECT_EQ(0U, res.headers.size());
  5629. EXPECT_FALSE(res.has_header("Location"));
  5630. })
  5631. .Get("/slow",
  5632. [&](const Request & /*req*/, Response &res) {
  5633. std::this_thread::sleep_for(std::chrono::seconds(4));
  5634. res.set_content("slow", "text/plain");
  5635. })
  5636. #if 0
  5637. .Post("/slowpost",
  5638. [&](const Request & /*req*/, Response &res) {
  5639. std::this_thread::sleep_for(std::chrono::seconds(2));
  5640. res.set_content("slow", "text/plain");
  5641. })
  5642. #endif
  5643. .Get("/remote_addr",
  5644. [&](const Request &req, Response &res) {
  5645. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5646. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5647. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5648. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5649. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5650. #endif
  5651. res.set_content(req.remote_addr, "text/plain");
  5652. })
  5653. .Get("/local_addr",
  5654. [&](const Request &req, Response &res) {
  5655. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5656. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5657. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5658. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5659. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5660. #endif
  5661. auto local_addr = req.local_addr;
  5662. auto local_port = std::to_string(req.local_port);
  5663. res.set_content(local_addr.append(":").append(local_port),
  5664. "text/plain");
  5665. })
  5666. .Get("/endwith%",
  5667. [&](const Request & /*req*/, Response &res) {
  5668. res.set_content("Hello World!", "text/plain");
  5669. })
  5670. .Get("/a\\+\\+b",
  5671. [&](const Request &req, Response &res) {
  5672. ASSERT_TRUE(req.has_param("a +b"));
  5673. auto val = req.get_param_value("a +b");
  5674. res.set_content(val, "text/plain");
  5675. })
  5676. .Get("/", [&](const Request & /*req*/,
  5677. Response &res) { res.set_redirect("/hi"); })
  5678. .Post("/1",
  5679. [](const Request & /*req*/, Response &res) {
  5680. res.set_redirect("/2", StatusCode::SeeOther_303);
  5681. })
  5682. .Get("/2",
  5683. [](const Request & /*req*/, Response &res) {
  5684. res.set_content("redirected.", "text/plain");
  5685. res.status = StatusCode::OK_200;
  5686. })
  5687. .Post("/person",
  5688. [&](const Request &req, Response &res) {
  5689. if (req.has_param("name") && req.has_param("note")) {
  5690. persons_[req.get_param_value("name")] =
  5691. req.get_param_value("note");
  5692. } else {
  5693. res.status = StatusCode::BadRequest_400;
  5694. }
  5695. })
  5696. .Put("/person",
  5697. [&](const Request &req, Response &res) {
  5698. if (req.has_param("name") && req.has_param("note")) {
  5699. persons_[req.get_param_value("name")] =
  5700. req.get_param_value("note");
  5701. } else {
  5702. res.status = StatusCode::BadRequest_400;
  5703. }
  5704. })
  5705. .Get("/person/(.*)",
  5706. [&](const Request &req, Response &res) {
  5707. string name = req.matches[1];
  5708. if (persons_.find(name) != persons_.end()) {
  5709. auto note = persons_[name];
  5710. res.set_content(note, "text/plain");
  5711. } else {
  5712. res.status = StatusCode::NotFound_404;
  5713. }
  5714. })
  5715. .Delete("/person",
  5716. [&](const Request &req, Response &res) {
  5717. if (req.has_param("name")) {
  5718. string name = req.get_param_value("name");
  5719. if (persons_.find(name) != persons_.end()) {
  5720. persons_.erase(name);
  5721. res.set_content("DELETED", "text/plain");
  5722. } else {
  5723. res.status = StatusCode::NotFound_404;
  5724. }
  5725. } else {
  5726. res.status = StatusCode::BadRequest_400;
  5727. }
  5728. })
  5729. .Post("/x-www-form-urlencoded-json",
  5730. [&](const Request &req, Response &res) {
  5731. auto json = req.get_param_value("json");
  5732. ASSERT_EQ(JSON_DATA, json);
  5733. res.set_content(json, "appliation/json");
  5734. res.status = StatusCode::OK_200;
  5735. })
  5736. .Get("/streamed-chunked",
  5737. [&](const Request & /*req*/, Response &res) {
  5738. res.set_chunked_content_provider(
  5739. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5740. sink.os << "123";
  5741. sink.os << "456";
  5742. sink.os << "789";
  5743. sink.done();
  5744. return true;
  5745. });
  5746. })
  5747. .Get("/streamed-chunked-with-prohibited-trailer",
  5748. [&](const Request & /*req*/, Response &res) {
  5749. auto i = new int(0);
  5750. // Declare both a prohibited trailer (Content-Length) and an
  5751. // allowed one
  5752. res.set_header("Trailer", "Content-Length, X-Allowed");
  5753. res.set_chunked_content_provider(
  5754. "text/plain",
  5755. [i](size_t /*offset*/, DataSink &sink) {
  5756. switch (*i) {
  5757. case 0: sink.os << "123"; break;
  5758. case 1: sink.os << "456"; break;
  5759. case 2: sink.os << "789"; break;
  5760. case 3: {
  5761. sink.done_with_trailer(
  5762. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5763. } break;
  5764. }
  5765. (*i)++;
  5766. return true;
  5767. },
  5768. [i](bool success) {
  5769. EXPECT_TRUE(success);
  5770. delete i;
  5771. });
  5772. })
  5773. .Get("/streamed-chunked2",
  5774. [&](const Request & /*req*/, Response &res) {
  5775. auto i = new int(0);
  5776. res.set_chunked_content_provider(
  5777. "text/plain",
  5778. [i](size_t /*offset*/, DataSink &sink) {
  5779. switch (*i) {
  5780. case 0: sink.os << "123"; break;
  5781. case 1: sink.os << "456"; break;
  5782. case 2: sink.os << "789"; break;
  5783. case 3: sink.done(); break;
  5784. }
  5785. (*i)++;
  5786. return true;
  5787. },
  5788. [i](bool success) {
  5789. EXPECT_TRUE(success);
  5790. delete i;
  5791. });
  5792. })
  5793. .Get("/streamed-chunked-with-trailer",
  5794. [&](const Request & /*req*/, Response &res) {
  5795. auto i = new int(0);
  5796. res.set_header("Trailer", "Dummy1, Dummy2");
  5797. res.set_chunked_content_provider(
  5798. "text/plain",
  5799. [i](size_t /*offset*/, DataSink &sink) {
  5800. switch (*i) {
  5801. case 0: sink.os << "123"; break;
  5802. case 1: sink.os << "456"; break;
  5803. case 2: sink.os << "789"; break;
  5804. case 3: {
  5805. sink.done_with_trailer(
  5806. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5807. } break;
  5808. }
  5809. (*i)++;
  5810. return true;
  5811. },
  5812. [i](bool success) {
  5813. EXPECT_TRUE(success);
  5814. delete i;
  5815. });
  5816. })
  5817. .Get("/streamed",
  5818. [&](const Request & /*req*/, Response &res) {
  5819. res.set_content_provider(
  5820. 6, "text/plain",
  5821. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5822. sink.os << (offset < 3 ? "a" : "b");
  5823. return true;
  5824. });
  5825. })
  5826. .Get("/streamed-without-length",
  5827. [&](const Request & /*req*/, Response &res) {
  5828. auto data = new std::string("abcdefg");
  5829. res.set_content_provider(
  5830. "text/plain",
  5831. [data](size_t offset, DataSink &sink) {
  5832. if (offset < data->size()) {
  5833. sink.os << data->substr(offset);
  5834. }
  5835. sink.done();
  5836. return true;
  5837. },
  5838. [data](bool success) {
  5839. EXPECT_TRUE(success);
  5840. delete data;
  5841. });
  5842. })
  5843. .Get("/streamed-with-range",
  5844. [&](const Request &req, Response &res) {
  5845. auto data = new std::string("abcdefg");
  5846. // An explicit status keeps the server from picking the 206 it
  5847. // would otherwise choose for a ranged request, so the response
  5848. // is not a partial representation.
  5849. auto status = req.get_param_value("status");
  5850. if (status == "200") {
  5851. res.status = StatusCode::OK_200;
  5852. } else if (status == "403") {
  5853. res.status = StatusCode::Forbidden_403;
  5854. }
  5855. res.set_content_provider(
  5856. data->size(), "text/plain",
  5857. [data](size_t offset, size_t length, DataSink &sink) {
  5858. size_t DATA_CHUNK_SIZE = 4;
  5859. const auto &d = *data;
  5860. auto out_len =
  5861. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5862. auto ret =
  5863. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5864. EXPECT_TRUE(ret);
  5865. return true;
  5866. },
  5867. [data, &req](bool success) {
  5868. EXPECT_EQ(success, !req.has_param("error"));
  5869. delete data;
  5870. });
  5871. })
  5872. .Get("/streamed-cancel",
  5873. [&](const Request & /*req*/, Response &res) {
  5874. res.set_content_provider(
  5875. size_t(-1), "text/plain",
  5876. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5877. sink.os << "data_chunk";
  5878. return true;
  5879. });
  5880. })
  5881. .Get("/regex-with-delimiter",
  5882. [&](const Request &req, Response & /*res*/) {
  5883. ASSERT_TRUE(req.has_param("key"));
  5884. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5885. })
  5886. .Get("/with-range",
  5887. [&](const Request & /*req*/, Response &res) {
  5888. res.set_content("abcdefg", "text/plain");
  5889. })
  5890. .Get("/test-start-time",
  5891. [&](const Request &req, Response & /*res*/) {
  5892. EXPECT_NE(req.start_time_,
  5893. std::chrono::steady_clock::time_point::min());
  5894. })
  5895. .Get("/with-range-customized-response",
  5896. [&](const Request & /*req*/, Response &res) {
  5897. res.status = StatusCode::BadRequest_400;
  5898. res.set_content(JSON_DATA, "application/json");
  5899. })
  5900. .Post("/chunked",
  5901. [&](const Request &req, Response & /*res*/) {
  5902. EXPECT_EQ(req.body, "dechunked post body");
  5903. })
  5904. .Post("/large-chunked",
  5905. [&](const Request &req, Response & /*res*/) {
  5906. std::string expected(6 * 30 * 1024u, 'a');
  5907. EXPECT_EQ(req.body, expected);
  5908. })
  5909. .Post("/multipart",
  5910. [&](const Request &req, Response & /*res*/) {
  5911. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5912. req.form.get_field_count("text2") +
  5913. req.form.get_field_count("file3") +
  5914. req.form.get_field_count("file4"));
  5915. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5916. req.form.get_file_count("file2"));
  5917. ASSERT_TRUE(!req.form.has_file("???"));
  5918. ASSERT_TRUE(!req.form.has_field("???"));
  5919. ASSERT_TRUE(req.body.empty());
  5920. {
  5921. const auto &text = req.form.get_field("text1");
  5922. EXPECT_EQ("text default", text);
  5923. }
  5924. {
  5925. const auto &text = req.form.get_field("text2");
  5926. EXPECT_EQ("aωb", text);
  5927. }
  5928. {
  5929. const auto &file = req.form.get_file("file1");
  5930. EXPECT_EQ("hello.txt", file.filename);
  5931. EXPECT_EQ("text/plain", file.content_type);
  5932. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5933. }
  5934. {
  5935. const auto &file = req.form.get_file("file2");
  5936. EXPECT_EQ("world.json", file.filename);
  5937. EXPECT_EQ("application/json", file.content_type);
  5938. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5939. }
  5940. {
  5941. const auto &text = req.form.get_field("file3");
  5942. EXPECT_EQ(0u, text.size());
  5943. }
  5944. {
  5945. const auto &text = req.form.get_field("file4");
  5946. EXPECT_EQ(0u, text.size());
  5947. }
  5948. })
  5949. .Post("/multipart/multi_file_values",
  5950. [&](const Request &req, Response & /*res*/) {
  5951. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5952. req.form.get_field_count("multi_text1"));
  5953. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5954. ASSERT_TRUE(!req.form.has_file("???"));
  5955. ASSERT_TRUE(!req.form.has_field("???"));
  5956. ASSERT_TRUE(req.body.empty());
  5957. {
  5958. const auto &text = req.form.get_field("text");
  5959. EXPECT_EQ("default text", text);
  5960. }
  5961. {
  5962. const auto &text1_values = req.form.get_fields("multi_text1");
  5963. EXPECT_EQ(2u, text1_values.size());
  5964. EXPECT_EQ("aaaaa", text1_values[0]);
  5965. EXPECT_EQ("bbbbb", text1_values[1]);
  5966. }
  5967. {
  5968. const auto &file1_values = req.form.get_files("multi_file1");
  5969. EXPECT_EQ(2u, file1_values.size());
  5970. auto file1 = file1_values[0];
  5971. EXPECT_EQ(file1.filename, "hello.txt");
  5972. EXPECT_EQ(file1.content_type, "text/plain");
  5973. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5974. auto file2 = file1_values[1];
  5975. EXPECT_EQ(file2.filename, "world.json");
  5976. EXPECT_EQ(file2.content_type, "application/json");
  5977. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5978. }
  5979. })
  5980. .Post("/empty",
  5981. [&](const Request &req, Response &res) {
  5982. EXPECT_EQ(req.body, "");
  5983. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5984. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5985. res.set_content("empty", "text/plain");
  5986. })
  5987. .Post("/empty-no-content-type",
  5988. [&](const Request &req, Response &res) {
  5989. EXPECT_EQ(req.body, "");
  5990. EXPECT_FALSE(req.has_header("Content-Type"));
  5991. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5992. res.set_content("empty-no-content-type", "text/plain");
  5993. })
  5994. .Post("/path-only",
  5995. [&](const Request &req, Response &res) {
  5996. EXPECT_EQ(req.body, "");
  5997. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5998. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5999. res.set_content("path-only", "text/plain");
  6000. })
  6001. .Post("/path-headers-only",
  6002. [&](const Request &req, Response &res) {
  6003. EXPECT_EQ(req.body, "");
  6004. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6005. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6006. EXPECT_EQ("world", req.get_header_value("hello"));
  6007. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6008. res.set_content("path-headers-only", "text/plain");
  6009. })
  6010. .Post("/post-large",
  6011. [&](const Request &req, Response &res) {
  6012. EXPECT_EQ(req.body, LARGE_DATA);
  6013. res.set_content(req.body, "text/plain");
  6014. })
  6015. .Post("/post-loopback",
  6016. [&](const Request &, Response &res,
  6017. ContentReader const &content_reader) {
  6018. std::string body;
  6019. content_reader([&](const char *data, size_t data_length) {
  6020. body.append(data, data_length);
  6021. return true;
  6022. });
  6023. res.set_content(body, "text/plain");
  6024. })
  6025. .Put("/put-loopback",
  6026. [&](const Request &, Response &res,
  6027. ContentReader const &content_reader) {
  6028. std::string body;
  6029. content_reader([&](const char *data, size_t data_length) {
  6030. body.append(data, data_length);
  6031. return true;
  6032. });
  6033. res.set_content(body, "text/plain");
  6034. })
  6035. .Patch("/patch-loopback",
  6036. [&](const Request &, Response &res,
  6037. ContentReader const &content_reader) {
  6038. std::string body;
  6039. content_reader([&](const char *data, size_t data_length) {
  6040. body.append(data, data_length);
  6041. return true;
  6042. });
  6043. res.set_content(body, "text/plain");
  6044. })
  6045. .Put("/empty-no-content-type",
  6046. [&](const Request &req, Response &res) {
  6047. EXPECT_EQ(req.body, "");
  6048. EXPECT_FALSE(req.has_header("Content-Type"));
  6049. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6050. res.set_content("empty-no-content-type", "text/plain");
  6051. })
  6052. .Put("/put",
  6053. [&](const Request &req, Response &res) {
  6054. EXPECT_EQ(req.body, "PUT");
  6055. res.set_content(req.body, "text/plain");
  6056. })
  6057. .Put("/put-large",
  6058. [&](const Request &req, Response &res) {
  6059. EXPECT_EQ(req.body, LARGE_DATA);
  6060. res.set_content(req.body, "text/plain");
  6061. })
  6062. .Patch("/patch",
  6063. [&](const Request &req, Response &res) {
  6064. EXPECT_EQ(req.body, "PATCH");
  6065. res.set_content(req.body, "text/plain");
  6066. })
  6067. .Delete("/delete",
  6068. [&](const Request & /*req*/, Response &res) {
  6069. res.set_content("DELETE", "text/plain");
  6070. })
  6071. .Delete("/delete-body",
  6072. [&](const Request &req, Response &res) {
  6073. EXPECT_EQ(req.body, "content");
  6074. res.set_content(req.body, "text/plain");
  6075. })
  6076. .Options(R"(\*)",
  6077. [&](const Request & /*req*/, Response &res) {
  6078. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6079. })
  6080. .CustomRoute("PROPFIND", "/dav/:id",
  6081. [&](const Request &req, Response &res) {
  6082. res.set_header("x-body-size",
  6083. std::to_string(req.body.size()));
  6084. res.set_header("x-matched-route", req.matched_route);
  6085. res.set_header("x-dav-id", req.path_params.at("id"));
  6086. res.status = StatusCode::MultiStatus_207;
  6087. res.set_content(req.body, "application/xml");
  6088. })
  6089. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6090. [&](const Request &req, Response &res) {
  6091. res.set_header("x-dav-match", req.matches[1]);
  6092. res.status = StatusCode::MultiStatus_207;
  6093. })
  6094. .CustomRoute("MKCOL", "/dav-mkcol",
  6095. [&](const Request &req, Response &res) {
  6096. EXPECT_TRUE(req.body.empty());
  6097. res.status = StatusCode::Created_201;
  6098. })
  6099. .CustomRoute(
  6100. "REPORT", "/dav-report",
  6101. [&](const Request & /*req*/, Response &res,
  6102. const ContentReader &content_reader) {
  6103. std::string body;
  6104. content_reader([&](const char *data, size_t data_length) {
  6105. body.append(data, data_length);
  6106. return true;
  6107. });
  6108. res.set_header("x-body-size", std::to_string(body.size()));
  6109. res.status = StatusCode::MultiStatus_207;
  6110. res.set_content(body, "application/xml");
  6111. })
  6112. .Get("/request-target",
  6113. [&](const Request &req, Response & /*res*/) {
  6114. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6115. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6116. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6117. })
  6118. .Get("/long-query-value",
  6119. [&](const Request &req, Response & /*res*/) {
  6120. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6121. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6122. })
  6123. .Get("/too-long-query-value",
  6124. [&](const Request &req, Response & /*res*/) {
  6125. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6126. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6127. })
  6128. .Get("/array-param",
  6129. [&](const Request &req, Response & /*res*/) {
  6130. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6131. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6132. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6133. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6134. })
  6135. .Get("/array-param-values",
  6136. [&](const Request &req, Response & /*res*/) {
  6137. auto values = req.get_param_values("array");
  6138. EXPECT_EQ(3u, values.size());
  6139. EXPECT_EQ("value1", values[0]);
  6140. EXPECT_EQ("value2", values[1]);
  6141. EXPECT_EQ("value3", values[2]);
  6142. auto empty = req.get_param_values("nonexistent");
  6143. EXPECT_TRUE(empty.empty());
  6144. })
  6145. .Post("/validate-no-multiple-headers",
  6146. [&](const Request &req, Response & /*res*/) {
  6147. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6148. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6149. })
  6150. .Post("/content_receiver",
  6151. [&](const Request &req, Response &res,
  6152. const ContentReader &content_reader) {
  6153. if (req.is_multipart_form_data()) {
  6154. std::vector<FormData> items;
  6155. content_reader(
  6156. [&](const FormData &file) {
  6157. items.push_back(file);
  6158. return true;
  6159. },
  6160. [&](const char *data, size_t data_length) {
  6161. items.back().content.append(data, data_length);
  6162. return true;
  6163. });
  6164. EXPECT_EQ(5u, items.size());
  6165. {
  6166. const auto &file = get_file_value(items, "text1");
  6167. EXPECT_TRUE(file.filename.empty());
  6168. EXPECT_EQ("text default", file.content);
  6169. }
  6170. {
  6171. const auto &file = get_file_value(items, "text2");
  6172. EXPECT_TRUE(file.filename.empty());
  6173. EXPECT_EQ("aωb", file.content);
  6174. }
  6175. {
  6176. const auto &file = get_file_value(items, "file1");
  6177. EXPECT_EQ("hello.txt", file.filename);
  6178. EXPECT_EQ("text/plain", file.content_type);
  6179. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6180. }
  6181. {
  6182. const auto &file = get_file_value(items, "file2");
  6183. EXPECT_EQ("world.json", file.filename);
  6184. EXPECT_EQ("application/json", file.content_type);
  6185. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6186. }
  6187. {
  6188. const auto &file = get_file_value(items, "file3");
  6189. EXPECT_TRUE(file.filename.empty());
  6190. EXPECT_EQ("application/octet-stream", file.content_type);
  6191. EXPECT_EQ(0u, file.content.size());
  6192. }
  6193. } else {
  6194. std::string body;
  6195. content_reader([&](const char *data, size_t data_length) {
  6196. EXPECT_EQ(7U, data_length);
  6197. body.append(data, data_length);
  6198. return true;
  6199. });
  6200. EXPECT_EQ(body, "content");
  6201. res.set_content(body, "text/plain");
  6202. }
  6203. })
  6204. .Put("/content_receiver",
  6205. [&](const Request & /*req*/, Response &res,
  6206. const ContentReader &content_reader) {
  6207. std::string body;
  6208. content_reader([&](const char *data, size_t data_length) {
  6209. body.append(data, data_length);
  6210. return true;
  6211. });
  6212. EXPECT_EQ(body, "content");
  6213. res.set_content(body, "text/plain");
  6214. })
  6215. .Patch("/content_receiver",
  6216. [&](const Request & /*req*/, Response &res,
  6217. const ContentReader &content_reader) {
  6218. std::string body;
  6219. content_reader([&](const char *data, size_t data_length) {
  6220. body.append(data, data_length);
  6221. return true;
  6222. });
  6223. EXPECT_EQ(body, "content");
  6224. res.set_content(body, "text/plain");
  6225. })
  6226. .Post("/query-string-and-body",
  6227. [&](const Request &req, Response & /*res*/) {
  6228. ASSERT_TRUE(req.has_param("key"));
  6229. EXPECT_EQ(req.get_param_value("key"), "value");
  6230. EXPECT_EQ(req.body, "content");
  6231. })
  6232. .Get("/last-request",
  6233. [&](const Request &req, Response & /*res*/) {
  6234. EXPECT_EQ("close", req.get_header_value("Connection"));
  6235. })
  6236. .Get(R"(/redirect/(\d+))",
  6237. [&](const Request &req, Response &res) {
  6238. auto num = std::stoi(req.matches[1]) + 1;
  6239. std::string url = "/redirect/" + std::to_string(num);
  6240. res.set_redirect(url);
  6241. })
  6242. .Post("/binary",
  6243. [&](const Request &req, Response &res) {
  6244. EXPECT_EQ(4U, req.body.size());
  6245. EXPECT_EQ("application/octet-stream",
  6246. req.get_header_value("Content-Type"));
  6247. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6248. res.set_content(req.body, "application/octet-stream");
  6249. })
  6250. .Put("/binary",
  6251. [&](const Request &req, Response &res) {
  6252. EXPECT_EQ(4U, req.body.size());
  6253. EXPECT_EQ("application/octet-stream",
  6254. req.get_header_value("Content-Type"));
  6255. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6256. res.set_content(req.body, "application/octet-stream");
  6257. })
  6258. .Patch("/binary",
  6259. [&](const Request &req, Response &res) {
  6260. EXPECT_EQ(4U, req.body.size());
  6261. EXPECT_EQ("application/octet-stream",
  6262. req.get_header_value("Content-Type"));
  6263. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6264. res.set_content(req.body, "application/octet-stream");
  6265. })
  6266. .Delete("/binary",
  6267. [&](const Request &req, Response &res) {
  6268. EXPECT_EQ(4U, req.body.size());
  6269. EXPECT_EQ("application/octet-stream",
  6270. req.get_header_value("Content-Type"));
  6271. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6272. res.set_content(req.body, "application/octet-stream");
  6273. })
  6274. .Get("/issue1772",
  6275. [&](const Request & /*req*/, Response &res) {
  6276. res.status = 401;
  6277. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6278. })
  6279. .Delete("/issue609",
  6280. [](const httplib::Request &, httplib::Response &res,
  6281. const httplib::ContentReader &) {
  6282. res.set_content("ok", "text/plain");
  6283. })
  6284. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6285. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6286. .Get("/compress",
  6287. [&](const Request & /*req*/, Response &res) {
  6288. res.set_content(
  6289. "12345678901234567890123456789012345678901234567890123456789"
  6290. "01234567890123456789012345678901234567890",
  6291. "text/plain");
  6292. })
  6293. .Get("/compress-with-charset",
  6294. [&](const Request & /*req*/, Response &res) {
  6295. res.set_content(
  6296. "12345678901234567890123456789012345678901234567890123456789"
  6297. "01234567890123456789012345678901234567890",
  6298. "application/json; charset=utf-8");
  6299. })
  6300. .Get("/nocompress",
  6301. [&](const Request & /*req*/, Response &res) {
  6302. res.set_content(
  6303. "12345678901234567890123456789012345678901234567890123456789"
  6304. "01234567890123456789012345678901234567890",
  6305. "application/octet-stream");
  6306. })
  6307. .Post("/compress-multipart",
  6308. [&](const Request &req, Response & /*res*/) {
  6309. EXPECT_EQ(2u, req.form.fields.size());
  6310. ASSERT_TRUE(!req.form.has_field("???"));
  6311. {
  6312. const auto &text = req.form.get_field("key1");
  6313. EXPECT_EQ("test", text);
  6314. }
  6315. {
  6316. const auto &text = req.form.get_field("key2");
  6317. EXPECT_EQ("--abcdefg123", text);
  6318. }
  6319. })
  6320. #endif
  6321. ;
  6322. persons_["john"] = "programmer";
  6323. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6324. svr_.wait_until_ready();
  6325. }
  6326. virtual void TearDown() {
  6327. svr_.stop();
  6328. if (!request_threads_.empty()) {
  6329. std::this_thread::sleep_for(std::chrono::seconds(1));
  6330. for (auto &t : request_threads_) {
  6331. t.join();
  6332. }
  6333. }
  6334. t_.join();
  6335. }
  6336. map<string, string> persons_;
  6337. #ifdef CPPHTTPLIB_SSL_ENABLED
  6338. SSLClient cli_;
  6339. SSLServer svr_;
  6340. #else
  6341. Client cli_;
  6342. Server svr_;
  6343. #endif
  6344. thread t_;
  6345. std::vector<thread> request_threads_;
  6346. };
  6347. TEST_F(ServerTest, GetMethod200) {
  6348. auto res = cli_.Get("/hi");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ("HTTP/1.1", res->version);
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. EXPECT_EQ("OK", res->reason);
  6353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6354. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6355. EXPECT_EQ("Hello World!", res->body);
  6356. }
  6357. TEST_F(ServerTest, GetEmptyFile) {
  6358. auto res = cli_.Get("/empty_file");
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. EXPECT_EQ(StatusCode::OK_200, res->status);
  6361. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6362. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6363. EXPECT_EQ("", res->body);
  6364. }
  6365. TEST_F(ServerTest, GetFileContent) {
  6366. auto res = cli_.Get("/file_content");
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. EXPECT_EQ(StatusCode::OK_200, res->status);
  6369. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6370. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6371. EXPECT_EQ("test.html", res->body);
  6372. }
  6373. TEST_F(ServerTest, GetFileContentWithRange) {
  6374. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6376. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6378. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6379. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6380. EXPECT_EQ("est", res->body);
  6381. }
  6382. TEST_F(ServerTest, GetFileContentWithContentType) {
  6383. auto res = cli_.Get("/file_content_with_content_type");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::OK_200, res->status);
  6386. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6387. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6388. EXPECT_EQ("file\n", res->body);
  6389. }
  6390. TEST_F(ServerTest, GetInvalidFileContent) {
  6391. auto res = cli_.Get("/invalid_file_content");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6394. }
  6395. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6396. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. EXPECT_EQ("HTTP/1.1", res->version);
  6399. EXPECT_EQ(StatusCode::OK_200, res->status);
  6400. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6401. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6402. EXPECT_EQ("Hello World!", res->body);
  6403. }
  6404. TEST_F(ServerTest, GetMethod302) {
  6405. auto res = cli_.Get("/");
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. EXPECT_EQ(StatusCode::Found_302, res->status);
  6408. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6409. }
  6410. TEST_F(ServerTest, GetMethod302Redirect) {
  6411. cli_.set_follow_location(true);
  6412. auto res = cli_.Get("/");
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::OK_200, res->status);
  6415. EXPECT_EQ("Hello World!", res->body);
  6416. EXPECT_EQ("/hi", res->location);
  6417. }
  6418. TEST_F(ServerTest, GetMethod404) {
  6419. auto res = cli_.Get("/invalid");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6422. }
  6423. TEST_F(ServerTest, HeadMethod200) {
  6424. auto res = cli_.Head("/hi");
  6425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6426. EXPECT_EQ(StatusCode::OK_200, res->status);
  6427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6428. EXPECT_TRUE(res->body.empty());
  6429. }
  6430. TEST_F(ServerTest, HeadMethod200Static) {
  6431. auto res = cli_.Head("/mount/dir/index.html");
  6432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6433. EXPECT_EQ(StatusCode::OK_200, res->status);
  6434. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6435. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6436. EXPECT_TRUE(res->body.empty());
  6437. }
  6438. TEST_F(ServerTest, HeadMethod404) {
  6439. auto res = cli_.Head("/invalid");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6442. EXPECT_TRUE(res->body.empty());
  6443. }
  6444. TEST_F(ServerTest, GetMethodPersonJohn) {
  6445. auto res = cli_.Get("/person/john");
  6446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6447. EXPECT_EQ(StatusCode::OK_200, res->status);
  6448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6449. EXPECT_EQ("programmer", res->body);
  6450. }
  6451. TEST_F(ServerTest, PostMethod1) {
  6452. auto res = cli_.Get("/person/john1");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6455. res = cli_.Post("/person", "name=john1&note=coder",
  6456. "application/x-www-form-urlencoded");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. ASSERT_EQ(StatusCode::OK_200, res->status);
  6459. res = cli_.Get("/person/john1");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. ASSERT_EQ(StatusCode::OK_200, res->status);
  6462. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6463. ASSERT_EQ("coder", res->body);
  6464. }
  6465. TEST_F(ServerTest, PostMethod2) {
  6466. auto res = cli_.Get("/person/john2");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6469. Params params;
  6470. params.emplace("name", "john2");
  6471. params.emplace("note", "coder");
  6472. res = cli_.Post("/person", params);
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. ASSERT_EQ(StatusCode::OK_200, res->status);
  6475. res = cli_.Get("/person/john2");
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. ASSERT_EQ(StatusCode::OK_200, res->status);
  6478. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6479. ASSERT_EQ("coder", res->body);
  6480. }
  6481. TEST_F(ServerTest, PutMethod3) {
  6482. auto res = cli_.Get("/person/john3");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6485. Params params;
  6486. params.emplace("name", "john3");
  6487. params.emplace("note", "coder");
  6488. res = cli_.Put("/person", params);
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. res = cli_.Get("/person/john3");
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. ASSERT_EQ(StatusCode::OK_200, res->status);
  6494. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6495. ASSERT_EQ("coder", res->body);
  6496. }
  6497. TEST_F(ServerTest, DeleteMethod1) {
  6498. auto res = cli_.Get("/person/john4");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6501. Params params;
  6502. params.emplace("name", "john4");
  6503. params.emplace("note", "coder");
  6504. res = cli_.Post("/person", params);
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. ASSERT_EQ(StatusCode::OK_200, res->status);
  6507. res = cli_.Get("/person/john4");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6511. ASSERT_EQ("coder", res->body);
  6512. Params delete_params;
  6513. delete_params.emplace("name", "john4");
  6514. res = cli_.Delete("/person", delete_params);
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. ASSERT_EQ(StatusCode::OK_200, res->status);
  6517. ASSERT_EQ("DELETED", res->body);
  6518. res = cli_.Get("/person/john4");
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6521. }
  6522. TEST_F(ServerTest, DeleteMethod2) {
  6523. auto res = cli_.Get("/person/john5");
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6526. Params params;
  6527. params.emplace("name", "john5");
  6528. params.emplace("note", "developer");
  6529. res = cli_.Post("/person", params);
  6530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6531. ASSERT_EQ(StatusCode::OK_200, res->status);
  6532. res = cli_.Get("/person/john5");
  6533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6534. ASSERT_EQ(StatusCode::OK_200, res->status);
  6535. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6536. ASSERT_EQ("developer", res->body);
  6537. Params delete_params;
  6538. delete_params.emplace("name", "john5");
  6539. Headers headers;
  6540. headers.emplace("Custom-Header", "test-value");
  6541. res = cli_.Delete("/person", headers, delete_params);
  6542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6543. ASSERT_EQ(StatusCode::OK_200, res->status);
  6544. ASSERT_EQ("DELETED", res->body);
  6545. res = cli_.Get("/person/john5");
  6546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6547. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6548. }
  6549. TEST_F(ServerTest, DeleteMethod3) {
  6550. auto res = cli_.Get("/person/john6");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6553. Params params;
  6554. params.emplace("name", "john6");
  6555. params.emplace("note", "tester");
  6556. res = cli_.Post("/person", params);
  6557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6558. ASSERT_EQ(StatusCode::OK_200, res->status);
  6559. res = cli_.Get("/person/john6");
  6560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6561. ASSERT_EQ(StatusCode::OK_200, res->status);
  6562. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6563. ASSERT_EQ("tester", res->body);
  6564. Params delete_params;
  6565. delete_params.emplace("name", "john6");
  6566. Headers headers;
  6567. headers.emplace("Custom-Header", "test-value");
  6568. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6570. ASSERT_EQ(StatusCode::OK_200, res->status);
  6571. ASSERT_EQ("DELETED", res->body);
  6572. res = cli_.Get("/person/john6");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6575. }
  6576. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6577. Params params;
  6578. params.emplace("json", JSON_DATA);
  6579. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6581. ASSERT_EQ(StatusCode::OK_200, res->status);
  6582. ASSERT_EQ(JSON_DATA, res->body);
  6583. }
  6584. TEST_F(ServerTest, PostEmptyContent) {
  6585. auto res = cli_.Post("/empty", "", "text/plain");
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. ASSERT_EQ(StatusCode::OK_200, res->status);
  6588. ASSERT_EQ("empty", res->body);
  6589. }
  6590. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6591. auto res = cli_.Post("/empty-no-content-type");
  6592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6593. ASSERT_EQ(StatusCode::OK_200, res->status);
  6594. ASSERT_EQ("empty-no-content-type", res->body);
  6595. }
  6596. TEST_F(ServerTest, PostPathOnly) {
  6597. auto res = cli_.Post("/path-only");
  6598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6599. ASSERT_EQ(StatusCode::OK_200, res->status);
  6600. ASSERT_EQ("path-only", res->body);
  6601. }
  6602. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6603. auto res = cli_.Post("/path-headers-only",
  6604. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. ASSERT_EQ(StatusCode::OK_200, res->status);
  6607. ASSERT_EQ("path-headers-only", res->body);
  6608. }
  6609. TEST_F(ServerTest, PostLarge) {
  6610. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. ASSERT_EQ(StatusCode::OK_200, res->status);
  6613. EXPECT_EQ(LARGE_DATA, res->body);
  6614. }
  6615. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6616. auto res = cli_.Put("/empty-no-content-type");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. ASSERT_EQ(StatusCode::OK_200, res->status);
  6619. ASSERT_EQ("empty-no-content-type", res->body);
  6620. }
  6621. TEST_F(ServerTest, GetMethodDir) {
  6622. auto res = cli_.Get("/dir/");
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. EXPECT_EQ(StatusCode::OK_200, res->status);
  6625. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6626. auto body = R"(<html>
  6627. <head>
  6628. </head>
  6629. <body>
  6630. <a href="/dir/test.html">Test</a>
  6631. <a href="/hi">hi</a>
  6632. </body>
  6633. </html>
  6634. )";
  6635. EXPECT_EQ(body, res->body);
  6636. }
  6637. TEST_F(ServerTest, GetMethodDirTest) {
  6638. auto res = cli_.Get("/dir/test.html");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. EXPECT_EQ(StatusCode::OK_200, res->status);
  6641. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6642. EXPECT_EQ("test.html", res->body);
  6643. }
  6644. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6645. auto res = cli_.Get("/dir/../dir/test.html");
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6648. }
  6649. TEST_F(ServerTest, GetMethodInvalidPath) {
  6650. auto res = cli_.Get("/dir/../test.html");
  6651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6653. }
  6654. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6655. auto res = cli_.Get("/../www/dir/test.html");
  6656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6657. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6658. }
  6659. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6660. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6663. }
  6664. TEST_F(ServerTest, GetMethodDirMountTest) {
  6665. auto res = cli_.Get("/mount/dir/test.html");
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::OK_200, res->status);
  6668. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6669. EXPECT_EQ("test.html", res->body);
  6670. }
  6671. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6672. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6675. }
  6676. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6677. auto res = cli_.Get("/mount/dir/../test.html");
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6680. }
  6681. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6682. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6685. }
  6686. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6687. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6689. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6690. }
  6691. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6692. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6694. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6695. }
  6696. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6697. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6699. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6700. }
  6701. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6702. auto res = cli_.Get("/mount/dir");
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6705. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6706. }
  6707. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6708. auto res = cli_.Get("//dir");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6711. EXPECT_FALSE(res->has_header("Location"));
  6712. }
  6713. TEST_F(ServerTest, PostMethod303) {
  6714. auto res = cli_.Post("/1", "body", "text/plain");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6717. EXPECT_EQ("/2", res->get_header_value("Location"));
  6718. }
  6719. TEST_F(ServerTest, PostMethod303Redirect) {
  6720. cli_.set_follow_location(true);
  6721. auto res = cli_.Post("/1", "body", "text/plain");
  6722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6723. EXPECT_EQ(StatusCode::OK_200, res->status);
  6724. EXPECT_EQ("redirected.", res->body);
  6725. EXPECT_EQ("/2", res->location);
  6726. }
  6727. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6728. auto res = cli_.Get("/dir/test.abcde");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6732. EXPECT_EQ("abcde", res->body);
  6733. }
  6734. TEST_F(ServerTest, StaticFileRange) {
  6735. auto res =
  6736. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6739. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6740. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6741. EXPECT_EQ(true, res->has_header("Content-Range"));
  6742. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6743. EXPECT_EQ(std::string("cd"), res->body);
  6744. }
  6745. TEST_F(ServerTest, StaticFileRanges) {
  6746. auto res = cli_.Get("/dir/test.abcde",
  6747. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6750. EXPECT_TRUE(
  6751. res->get_header_value("Content-Type")
  6752. .find(
  6753. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6754. 0);
  6755. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6756. }
  6757. TEST_F(ServerTest, StaticFileRangeHead) {
  6758. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6761. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6762. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6763. EXPECT_EQ(true, res->has_header("Content-Range"));
  6764. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6765. }
  6766. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6767. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6769. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6770. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6771. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6772. EXPECT_EQ(true, res->has_header("Content-Range"));
  6773. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6774. res->get_header_value("Content-Range"));
  6775. EXPECT_EQ("LAST\n", res->body);
  6776. }
  6777. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6778. auto res =
  6779. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6782. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6783. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6784. EXPECT_EQ(true, res->has_header("Content-Range"));
  6785. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6786. }
  6787. TEST_F(ServerTest, StaticFileBigFile) {
  6788. auto res = cli_.Get("/dir/1MB.txt");
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6792. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6793. }
  6794. TEST_F(ServerTest, InvalidBaseDirMount) {
  6795. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6796. }
  6797. TEST_F(ServerTest, Binary) {
  6798. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6799. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6800. "application/octet-stream");
  6801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6802. ASSERT_EQ(StatusCode::OK_200, res->status);
  6803. ASSERT_EQ(4U, res->body.size());
  6804. res = cli_.Put("/binary", binary.data(), binary.size(),
  6805. "application/octet-stream");
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. ASSERT_EQ(StatusCode::OK_200, res->status);
  6808. ASSERT_EQ(4U, res->body.size());
  6809. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6810. "application/octet-stream");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. ASSERT_EQ(StatusCode::OK_200, res->status);
  6813. ASSERT_EQ(4U, res->body.size());
  6814. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6815. "application/octet-stream");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. ASSERT_EQ(StatusCode::OK_200, res->status);
  6818. ASSERT_EQ(4U, res->body.size());
  6819. }
  6820. TEST_F(ServerTest, BinaryString) {
  6821. auto binary = std::string("\x00\x01\x02\x03", 4);
  6822. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6824. ASSERT_EQ(StatusCode::OK_200, res->status);
  6825. ASSERT_EQ(4U, res->body.size());
  6826. res = cli_.Put("/binary", binary, "application/octet-stream");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. ASSERT_EQ(StatusCode::OK_200, res->status);
  6829. ASSERT_EQ(4U, res->body.size());
  6830. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6832. ASSERT_EQ(StatusCode::OK_200, res->status);
  6833. ASSERT_EQ(4U, res->body.size());
  6834. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6836. ASSERT_EQ(StatusCode::OK_200, res->status);
  6837. ASSERT_EQ(4U, res->body.size());
  6838. }
  6839. TEST_F(ServerTest, EmptyRequest) {
  6840. auto res = cli_.Get("");
  6841. ASSERT_TRUE(!res);
  6842. EXPECT_EQ(Error::Connection, res.error());
  6843. }
  6844. TEST_F(ServerTest, LongRequest) {
  6845. std::string request;
  6846. for (size_t i = 0; i < 545; i++) {
  6847. request += "/TooLongRequest";
  6848. }
  6849. request += "OK";
  6850. auto res = cli_.Get(request.c_str());
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6853. }
  6854. TEST_F(ServerTest, TooLongRequest) {
  6855. std::string request;
  6856. for (size_t i = 0; i < 546; i++) {
  6857. request += "/TooLongRequest";
  6858. }
  6859. request += "_NG";
  6860. auto start = std::chrono::high_resolution_clock::now();
  6861. cli_.set_keep_alive(true);
  6862. auto res = cli_.Get(request.c_str());
  6863. auto end = std::chrono::high_resolution_clock::now();
  6864. auto elapsed =
  6865. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6866. .count();
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6869. EXPECT_LE(elapsed, 1000);
  6870. EXPECT_EQ("close", res->get_header_value("Connection"));
  6871. EXPECT_FALSE(cli_.is_socket_open());
  6872. }
  6873. TEST_F(ServerTest, AlmostTooLongRequest) {
  6874. // test for #2046 - URI length check shouldn't include other content on req
  6875. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6876. // leading /, space, HTTP/1.1)
  6877. std::string request =
  6878. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6879. auto res = cli_.Get(request.c_str());
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6882. }
  6883. TEST_F(ServerTest, LongHeader) {
  6884. Request req;
  6885. req.method = "GET";
  6886. req.path = "/hi";
  6887. std::string host_and_port;
  6888. host_and_port += HOST;
  6889. host_and_port += ":";
  6890. host_and_port += std::to_string(PORT);
  6891. req.headers.emplace("Host", host_and_port.c_str());
  6892. req.headers.emplace("Accept", "*/*");
  6893. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6894. req.headers.emplace(
  6895. "Header-Name",
  6896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6924. "@@@@@@@@@@@@@@@@");
  6925. auto res = std::make_shared<Response>();
  6926. auto error = Error::Success;
  6927. auto ret = cli_.send(req, *res, error);
  6928. ASSERT_TRUE(ret);
  6929. EXPECT_EQ(StatusCode::OK_200, res->status);
  6930. }
  6931. TEST_F(ServerTest, LongQueryValue) {
  6932. auto start = std::chrono::high_resolution_clock::now();
  6933. cli_.set_keep_alive(true);
  6934. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6935. auto end = std::chrono::high_resolution_clock::now();
  6936. auto elapsed =
  6937. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6938. .count();
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6941. EXPECT_LE(elapsed, 1000);
  6942. EXPECT_EQ("close", res->get_header_value("Connection"));
  6943. EXPECT_FALSE(cli_.is_socket_open());
  6944. }
  6945. TEST_F(ServerTest, TooLongQueryValue) {
  6946. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6947. ASSERT_FALSE(res);
  6948. EXPECT_EQ(Error::Read, res.error());
  6949. }
  6950. TEST_F(ServerTest, TooLongHeader) {
  6951. Request req;
  6952. req.method = "GET";
  6953. req.path = "/hi";
  6954. std::string host_and_port;
  6955. host_and_port += HOST;
  6956. host_and_port += ":";
  6957. host_and_port += std::to_string(PORT);
  6958. req.headers.emplace("Host", host_and_port.c_str());
  6959. req.headers.emplace("Accept", "*/*");
  6960. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6961. req.headers.emplace(
  6962. "Header-Name",
  6963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6991. "@@@@@@@@@@@@@@@@@");
  6992. auto res = std::make_shared<Response>();
  6993. auto error = Error::Success;
  6994. auto ret = cli_.send(req, *res, error);
  6995. ASSERT_TRUE(ret);
  6996. EXPECT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. TEST_F(ServerTest, HeaderCountAtLimit) {
  6999. // Test with headers just under the 100 limit
  7000. httplib::Headers headers;
  7001. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7002. // This should keep us just under the 100 header limit
  7003. for (int i = 0; i < 95; i++) {
  7004. std::string name = "X-Test-Header-" + std::to_string(i);
  7005. std::string value = "value" + std::to_string(i);
  7006. headers.emplace(name, value);
  7007. }
  7008. // This should work fine as we're under the limit
  7009. auto res = cli_.Get("/hi", headers);
  7010. EXPECT_TRUE(res);
  7011. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7012. }
  7013. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7014. // Test with many headers to exceed the 100 limit
  7015. httplib::Headers headers;
  7016. // Add 150 headers to definitely exceed the 100 limit
  7017. for (int i = 0; i < 150; i++) {
  7018. std::string name = "X-Test-Header-" + std::to_string(i);
  7019. std::string value = "value" + std::to_string(i);
  7020. headers.emplace(name, value);
  7021. }
  7022. // This should fail due to exceeding header count limit
  7023. cli_.set_keep_alive(true);
  7024. auto res = cli_.Get("/hi", headers);
  7025. // The server should respond with 400 Bad Request
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7028. EXPECT_EQ("close", res->get_header_value("Connection"));
  7029. EXPECT_FALSE(cli_.is_socket_open());
  7030. }
  7031. TEST_F(ServerTest, PercentEncoding) {
  7032. auto res = cli_.Get("/e%6edwith%");
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. }
  7036. TEST_F(ServerTest, PercentEncodingUnicode) {
  7037. auto res = cli_.Get("/e%u006edwith%");
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::OK_200, res->status);
  7040. }
  7041. TEST_F(ServerTest, InvalidPercentEncoding) {
  7042. auto res = cli_.Get("/%endwith%");
  7043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7044. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7045. }
  7046. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7047. auto res = cli_.Get("/%uendwith%");
  7048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7049. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7050. }
  7051. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7052. auto res = cli_.Get("/hello?aaa=bbb%");
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7055. }
  7056. TEST_F(ServerTest, PlusSignEncoding) {
  7057. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7059. EXPECT_EQ(StatusCode::OK_200, res->status);
  7060. EXPECT_EQ("a +b", res->body);
  7061. }
  7062. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7063. // This test simulates a potential DoS attack using many headers
  7064. // to verify our security fix prevents memory exhaustion
  7065. httplib::Headers attack_headers;
  7066. // Attempt to add many headers like an attacker would (200 headers to far
  7067. // exceed limit)
  7068. for (int i = 0; i < 200; i++) {
  7069. std::string name = "X-Attack-Header-" + std::to_string(i);
  7070. std::string value = "attack_payload_" + std::to_string(i);
  7071. attack_headers.emplace(name, value);
  7072. }
  7073. // Try to POST with excessive headers
  7074. cli_.set_keep_alive(true);
  7075. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7076. // Should either fail or return 400 Bad Request due to security limit
  7077. if (res) {
  7078. // If we get a response, it should be 400 Bad Request
  7079. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7080. EXPECT_EQ("close", res->get_header_value("Connection"));
  7081. }
  7082. EXPECT_FALSE(cli_.is_socket_open());
  7083. }
  7084. TEST_F(ServerTest, MultipartFormData) {
  7085. UploadFormDataItems items = {
  7086. {"text1", "text default", "", ""},
  7087. {"text2", "aωb", "", ""},
  7088. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7089. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7090. {"file3", "", "", "application/octet-stream"},
  7091. {"file4", "", "", " application/json tmp-string "}};
  7092. auto res = cli_.Post("/multipart", items);
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. EXPECT_EQ(StatusCode::OK_200, res->status);
  7095. }
  7096. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7097. UploadFormDataItems items = {
  7098. {"text", "default text", "", ""},
  7099. {"multi_text1", "aaaaa", "", ""},
  7100. {"multi_text1", "bbbbb", "", ""},
  7101. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7102. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7103. "application/json"},
  7104. };
  7105. auto res = cli_.Post("/multipart/multi_file_values", items);
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. EXPECT_EQ(StatusCode::OK_200, res->status);
  7108. }
  7109. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7110. auto res = cli_.Get("/hi");
  7111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7112. EXPECT_EQ(StatusCode::OK_200, res->status);
  7113. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7114. EXPECT_EQ("Hello World!", res->body);
  7115. }
  7116. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7117. Request req;
  7118. req.method = "POST";
  7119. req.path = "/chunked";
  7120. std::string host_and_port;
  7121. host_and_port += HOST;
  7122. host_and_port += ":";
  7123. host_and_port += std::to_string(PORT);
  7124. req.headers.emplace("Host", host_and_port.c_str());
  7125. req.headers.emplace("Accept", "*/*");
  7126. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7127. req.headers.emplace("Content-Type", "text/plain");
  7128. req.headers.emplace("Content-Length", "0");
  7129. req.headers.emplace(
  7130. "Transfer-Encoding",
  7131. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7132. // Client does not chunk, so make a chunked body manually.
  7133. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7134. auto res = std::make_shared<Response>();
  7135. auto error = Error::Success;
  7136. auto ret = cli_.send(req, *res, error);
  7137. ASSERT_TRUE(ret);
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. }
  7140. template <typename ClientT>
  7141. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7142. int expected_status) {
  7143. Request req;
  7144. req.method = "POST";
  7145. req.path = "/chunked";
  7146. std::string host_and_port;
  7147. host_and_port += HOST;
  7148. host_and_port += ":";
  7149. host_and_port += std::to_string(PORT);
  7150. req.headers.emplace("Host", host_and_port.c_str());
  7151. req.headers.emplace("Content-Length", "0");
  7152. req.headers.emplace("Transfer-Encoding", "chunked");
  7153. req.body = body;
  7154. auto res = std::make_shared<Response>();
  7155. auto error = Error::Success;
  7156. ASSERT_TRUE(cli.send(req, *res, error));
  7157. EXPECT_EQ(expected_status, res->status);
  7158. }
  7159. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7160. // rather than treat them as valid lengths.
  7161. template <typename ClientT>
  7162. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7163. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7164. }
  7165. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7166. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7167. }
  7168. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7169. expect_chunked_body_rejected(
  7170. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7171. }
  7172. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7173. // chunk-size line carries no CR, LF or other control character ahead of its
  7174. // terminator. Such a line must be refused rather than read as extension text.
  7175. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7176. expect_chunked_body_rejected(
  7177. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7178. }
  7179. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7180. expect_chunked_body_rejected(
  7181. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7182. }
  7183. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7184. expect_chunked_body_rejected(
  7185. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7186. }
  7187. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7188. // The literal stays split: a hex escape consumes every hex digit that
  7189. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7190. expect_chunked_body_rejected(
  7191. cli_, "4;a\x01"
  7192. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7193. }
  7194. // The bytes around chunk data are no payload, so they cannot ride on the
  7195. // payload limit
  7196. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7197. // Small enough that the whole request is sent before the server turns it
  7198. // down, yet past the limit by the last chunks
  7199. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7200. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7201. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7202. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7203. SCOPED_TRACE(size_line.substr(0, 2));
  7204. std::string body;
  7205. for (auto c : std::string("dechunked post body")) {
  7206. body += size_line + "\r\n" + c + "\r\n";
  7207. }
  7208. body += "0\r\n\r\n";
  7209. expect_chunked_body_rejected(cli_, body.c_str());
  7210. }
  7211. }
  7212. TEST_F(ServerTest, AcceptsChunkExtension) {
  7213. expect_chunked_body_status(cli_,
  7214. "4;name=value\r\ndech\r\n"
  7215. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7216. "0;last\r\n\r\n",
  7217. StatusCode::OK_200);
  7218. }
  7219. TEST_F(ServerTest, GetStreamed2) {
  7220. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7222. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7223. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7224. EXPECT_EQ(true, res->has_header("Content-Range"));
  7225. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7226. EXPECT_EQ(std::string("ab"), res->body);
  7227. }
  7228. TEST_F(ServerTest, GetStreamed) {
  7229. auto res = cli_.Get("/streamed");
  7230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7231. EXPECT_EQ(StatusCode::OK_200, res->status);
  7232. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7233. EXPECT_EQ(std::string("aaabbb"), res->body);
  7234. }
  7235. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7236. auto res = cli_.Get("/streamed-without-length",
  7237. Headers{make_range_header({{0, -1}})});
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. EXPECT_EQ(false, res->has_header("Content-Length"));
  7241. EXPECT_EQ(false, res->has_header("Content-Range"));
  7242. EXPECT_EQ(std::string("abcdefg"), res->body);
  7243. }
  7244. TEST_F(ServerTest, GetStreamedWithRange1) {
  7245. auto res =
  7246. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7249. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7250. EXPECT_EQ(true, res->has_header("Content-Range"));
  7251. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7252. EXPECT_EQ(std::string("def"), res->body);
  7253. }
  7254. TEST_F(ServerTest, GetStreamedWithRange2) {
  7255. auto res =
  7256. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7259. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7260. EXPECT_EQ(true, res->has_header("Content-Range"));
  7261. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7262. EXPECT_EQ(std::string("bcdefg"), res->body);
  7263. }
  7264. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7265. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7267. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7268. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7269. EXPECT_EQ(true, res->has_header("Content-Range"));
  7270. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7271. EXPECT_EQ(std::string("efg"), res->body);
  7272. }
  7273. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7274. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7275. // the entire representation.
  7276. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7277. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7279. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7280. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7281. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7282. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7283. }
  7284. }
  7285. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7286. auto res =
  7287. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7289. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7290. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7291. EXPECT_EQ(false, res->has_header("Content-Range"));
  7292. EXPECT_EQ(0U, res->body.size());
  7293. }
  7294. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7295. // Only a 206 is served as a partial representation. Under any other status
  7296. // `apply_ranges()` reported the full content length, so the body must match
  7297. // that header, and the content provider must never be asked for an offset
  7298. // outside the representation.
  7299. auto check = [&](int status, const char *range) {
  7300. auto path =
  7301. std::string("/streamed-with-range?status=") + std::to_string(status);
  7302. auto ctx = path + " Range: " + range;
  7303. auto res = cli_.Get(path, Headers{{"Range", range}});
  7304. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7305. EXPECT_EQ(status, res->status) << ctx;
  7306. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7308. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7309. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7310. };
  7311. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7312. check(403, "bytes=3-5");
  7313. // The offset is far past the representation.
  7314. check(403, "bytes=100000-100200");
  7315. // `first_pos` is still -1 here, and the bounds asserts in
  7316. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7317. check(403, "bytes=-3");
  7318. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7319. // multipart branch would have written one that is empty.
  7320. check(403, "bytes=1-2, 4-5");
  7321. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7322. // covers the whole representation.
  7323. check(200, "bytes=3-5");
  7324. check(200, "bytes=1-2, 4-5");
  7325. }
  7326. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7327. auto res =
  7328. cli_.Get("/streamed-with-range",
  7329. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7330. "92233720368547758079223372036854775807"}});
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7333. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7334. EXPECT_EQ(false, res->has_header("Content-Range"));
  7335. EXPECT_EQ(0U, res->body.size());
  7336. }
  7337. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7338. auto res = cli_.Get(
  7339. "/with-range",
  7340. Headers{{"Range",
  7341. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7342. {"Accept-Encoding", ""}});
  7343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7344. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7345. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7346. EXPECT_EQ(true, res->has_header("Content-Range"));
  7347. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7348. EXPECT_EQ(std::string("abcdefg"), res->body);
  7349. }
  7350. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7351. auto res = cli_.Get("/with-range", Headers{
  7352. {"Range", "bytes=0-"},
  7353. {"Accept-Encoding", ""},
  7354. });
  7355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7356. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7357. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7358. EXPECT_EQ(true, res->has_header("Content-Range"));
  7359. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7360. EXPECT_EQ(std::string("abcdefg"), res->body);
  7361. }
  7362. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7363. auto res = cli_.Get("/streamed-with-range",
  7364. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7367. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7368. EXPECT_EQ(false, res->has_header("Content-Range"));
  7369. EXPECT_EQ(267U, res->body.size());
  7370. // Check that both range contents are present
  7371. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7372. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7373. // Check that Content-Range headers are present for both ranges
  7374. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7375. std::string::npos);
  7376. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7377. std::string::npos);
  7378. }
  7379. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7380. Ranges ranges;
  7381. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7382. ranges.emplace_back(0, -1);
  7383. }
  7384. auto res = cli_.Get("/streamed-with-range?error",
  7385. Headers{{make_range_header(ranges)}});
  7386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7387. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7388. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7389. EXPECT_EQ(false, res->has_header("Content-Range"));
  7390. EXPECT_EQ(0U, res->body.size());
  7391. }
  7392. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7393. auto res = cli_.Get("/streamed-with-range",
  7394. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7397. EXPECT_EQ(5U, res->body.size());
  7398. // Check that overlapping ranges are coalesced into a single range
  7399. EXPECT_EQ("bcdef", res->body);
  7400. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7401. // Should be single range, not multipart
  7402. EXPECT_TRUE(res->has_header("Content-Range"));
  7403. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7404. }
  7405. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7406. auto res = cli_.Get("/streamed-with-range",
  7407. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7409. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7410. EXPECT_EQ(268U, res->body.size());
  7411. // Check that both range contents are present
  7412. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7413. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7414. // Check that Content-Range headers are present for both ranges
  7415. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7416. std::string::npos);
  7417. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7418. std::string::npos);
  7419. }
  7420. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7421. auto res = cli_.Get("/streamed-with-range",
  7422. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7424. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7425. EXPECT_EQ(269U, res->body.size());
  7426. // Check that both duplicate range contents are present
  7427. size_t first_abc = res->body.find("abc\r\n");
  7428. EXPECT_TRUE(first_abc != std::string::npos);
  7429. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7430. EXPECT_TRUE(second_abc != std::string::npos);
  7431. // Check that Content-Range headers are present for both ranges
  7432. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7433. EXPECT_TRUE(first_range != std::string::npos);
  7434. size_t second_range =
  7435. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7436. EXPECT_TRUE(second_range != std::string::npos);
  7437. }
  7438. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7439. auto res =
  7440. cli_.Get("/streamed-with-range?error",
  7441. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7443. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7444. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7445. EXPECT_EQ(false, res->has_header("Content-Range"));
  7446. EXPECT_EQ(0U, res->body.size());
  7447. }
  7448. TEST_F(ServerTest, GetStreamedEndless) {
  7449. uint64_t offset = 0;
  7450. auto res = cli_.Get("/streamed-cancel",
  7451. [&](const char * /*data*/, uint64_t data_length) {
  7452. if (offset < 100) {
  7453. offset += data_length;
  7454. return true;
  7455. }
  7456. return false;
  7457. });
  7458. ASSERT_TRUE(!res);
  7459. EXPECT_EQ(Error::Canceled, res.error());
  7460. }
  7461. TEST_F(ServerTest, ClientStop) {
  7462. std::atomic_size_t count{4};
  7463. std::vector<std::thread> threads;
  7464. for (auto i = count.load(); i != 0; --i) {
  7465. threads.emplace_back([&]() {
  7466. auto res = cli_.Get("/streamed-cancel",
  7467. [&](const char *, uint64_t) { return true; });
  7468. --count;
  7469. ASSERT_TRUE(!res);
  7470. EXPECT_TRUE(res.error() == Error::Canceled ||
  7471. res.error() == Error::Read || res.error() == Error::Write);
  7472. });
  7473. }
  7474. std::this_thread::sleep_for(std::chrono::seconds(2));
  7475. while (count != 0) {
  7476. cli_.stop();
  7477. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7478. }
  7479. for (auto &t : threads) {
  7480. t.join();
  7481. }
  7482. }
  7483. TEST_F(ServerTest, GetWithRange1) {
  7484. auto res = cli_.Get("/with-range", Headers{
  7485. make_range_header({{3, 5}}),
  7486. {"Accept-Encoding", ""},
  7487. });
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7490. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7491. EXPECT_EQ(true, res->has_header("Content-Range"));
  7492. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7493. EXPECT_EQ(std::string("def"), res->body);
  7494. }
  7495. TEST_F(ServerTest, GetWithRange2) {
  7496. auto res = cli_.Get("/with-range", Headers{
  7497. make_range_header({{1, -1}}),
  7498. {"Accept-Encoding", ""},
  7499. });
  7500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7501. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7502. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7503. EXPECT_EQ(true, res->has_header("Content-Range"));
  7504. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7505. EXPECT_EQ(std::string("bcdefg"), res->body);
  7506. }
  7507. TEST_F(ServerTest, GetWithRange3) {
  7508. auto res = cli_.Get("/with-range", Headers{
  7509. make_range_header({{0, 0}}),
  7510. {"Accept-Encoding", ""},
  7511. });
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7514. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7515. EXPECT_EQ(true, res->has_header("Content-Range"));
  7516. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7517. EXPECT_EQ(std::string("a"), res->body);
  7518. }
  7519. TEST_F(ServerTest, GetWithRange4) {
  7520. auto res = cli_.Get("/with-range", Headers{
  7521. make_range_header({{-1, 2}}),
  7522. {"Accept-Encoding", ""},
  7523. });
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7526. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7527. EXPECT_EQ(true, res->has_header("Content-Range"));
  7528. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7529. EXPECT_EQ(std::string("fg"), res->body);
  7530. }
  7531. TEST_F(ServerTest, GetWithRange5) {
  7532. auto res = cli_.Get("/with-range", Headers{
  7533. make_range_header({{0, 5}}),
  7534. {"Accept-Encoding", ""},
  7535. });
  7536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7537. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7538. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7539. EXPECT_EQ(true, res->has_header("Content-Range"));
  7540. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7541. EXPECT_EQ(std::string("abcdef"), res->body);
  7542. }
  7543. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7544. auto res =
  7545. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7548. }
  7549. TEST_F(ServerTest, GetWithRangeMultipart) {
  7550. auto res =
  7551. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7553. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7554. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7555. EXPECT_EQ(false, res->has_header("Content-Range"));
  7556. EXPECT_EQ(267U, res->body.size());
  7557. }
  7558. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7559. auto res = cli_.Get("/with-range",
  7560. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7562. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7563. }
  7564. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7565. auto res = cli_.Get("/with-range-customized-response",
  7566. Headers{{make_range_header({{1, 2}})}});
  7567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7568. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7569. EXPECT_EQ(true, res->has_header("Content-Length"));
  7570. EXPECT_EQ(false, res->has_header("Content-Range"));
  7571. EXPECT_EQ(JSON_DATA, res->body);
  7572. }
  7573. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7574. auto res = cli_.Get("/with-range-customized-response",
  7575. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7577. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7578. EXPECT_EQ(true, res->has_header("Content-Length"));
  7579. EXPECT_EQ(false, res->has_header("Content-Range"));
  7580. EXPECT_EQ(JSON_DATA, res->body);
  7581. }
  7582. TEST_F(ServerTest, Issue1772) {
  7583. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7585. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7586. }
  7587. TEST_F(ServerTest, Issue609) {
  7588. auto res = cli_.Delete("/issue609");
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. EXPECT_EQ(std::string("ok"), res->body);
  7592. }
  7593. TEST_F(ServerTest, GetStreamedChunked) {
  7594. auto res = cli_.Get("/streamed-chunked");
  7595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7596. EXPECT_EQ(StatusCode::OK_200, res->status);
  7597. EXPECT_EQ(std::string("123456789"), res->body);
  7598. }
  7599. TEST_F(ServerTest, GetStreamedChunked2) {
  7600. auto res = cli_.Get("/streamed-chunked2");
  7601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7602. EXPECT_EQ(StatusCode::OK_200, res->status);
  7603. EXPECT_EQ(std::string("123456789"), res->body);
  7604. }
  7605. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7606. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7608. EXPECT_EQ(StatusCode::OK_200, res->status);
  7609. EXPECT_EQ(std::string("123456789"), res->body);
  7610. EXPECT_TRUE(res->has_header("Trailer"));
  7611. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7612. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7613. // Trailers are now stored separately from headers (security fix)
  7614. EXPECT_EQ(2U, res->trailers.size());
  7615. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7616. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7617. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7618. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7619. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7620. // Verify trailers are NOT in headers (security verification)
  7621. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7622. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7623. }
  7624. TEST_F(ServerTest, LargeChunkedPost) {
  7625. Request req;
  7626. req.method = "POST";
  7627. req.path = "/large-chunked";
  7628. std::string host_and_port;
  7629. host_and_port += HOST;
  7630. host_and_port += ":";
  7631. host_and_port += std::to_string(PORT);
  7632. req.headers.emplace("Host", host_and_port.c_str());
  7633. req.headers.emplace("Accept", "*/*");
  7634. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7635. req.headers.emplace("Content-Type", "text/plain");
  7636. req.headers.emplace("Content-Length", "0");
  7637. req.headers.emplace("Transfer-Encoding", "chunked");
  7638. std::string long_string(30 * 1024u, 'a');
  7639. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7640. // Attempt to make a large enough post to exceed OS buffers, to test that
  7641. // the server handles short reads if the full chunk data isn't available.
  7642. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7643. auto res = std::make_shared<Response>();
  7644. auto error = Error::Success;
  7645. auto ret = cli_.send(req, *res, error);
  7646. ASSERT_TRUE(ret);
  7647. EXPECT_EQ(StatusCode::OK_200, res->status);
  7648. }
  7649. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7650. auto res = cli_.Get("/remote_addr");
  7651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7652. EXPECT_EQ(StatusCode::OK_200, res->status);
  7653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7654. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7655. }
  7656. TEST_F(ServerTest, GetMethodLocalAddr) {
  7657. auto res = cli_.Get("/local_addr");
  7658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7659. EXPECT_EQ(StatusCode::OK_200, res->status);
  7660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7661. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7662. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7663. }
  7664. TEST_F(ServerTest, HTTPResponseSplitting) {
  7665. auto res = cli_.Get("/http_response_splitting");
  7666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7667. EXPECT_EQ(StatusCode::OK_200, res->status);
  7668. }
  7669. TEST_F(ServerTest, SlowRequest) {
  7670. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7671. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7672. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7673. }
  7674. #if 0
  7675. TEST_F(ServerTest, SlowPost) {
  7676. char buffer[64 * 1024];
  7677. memset(buffer, 0x42, sizeof(buffer));
  7678. auto res = cli_.Post(
  7679. "/slowpost", 64 * 1024 * 1024,
  7680. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7681. auto ret = sink.write(buffer, sizeof(buffer));
  7682. EXPECT_TRUE(ret);
  7683. return true;
  7684. },
  7685. "text/plain");
  7686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7687. EXPECT_EQ(StatusCode::OK_200, res->status);
  7688. }
  7689. TEST_F(ServerTest, SlowPostFail) {
  7690. char buffer[64 * 1024];
  7691. memset(buffer, 0x42, sizeof(buffer));
  7692. cli_.set_write_timeout(std::chrono::seconds(0));
  7693. auto res = cli_.Post(
  7694. "/slowpost", 64 * 1024 * 1024,
  7695. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7696. sink.write(buffer, sizeof(buffer));
  7697. return true;
  7698. },
  7699. "text/plain");
  7700. ASSERT_TRUE(!res);
  7701. EXPECT_EQ(Error::Write, res.error());
  7702. }
  7703. #endif
  7704. TEST_F(ServerTest, Put) {
  7705. auto res = cli_.Put("/put", "PUT", "text/plain");
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::OK_200, res->status);
  7708. EXPECT_EQ("PUT", res->body);
  7709. }
  7710. TEST_F(ServerTest, PutWithContentProvider) {
  7711. auto res = cli_.Put(
  7712. "/put", 3,
  7713. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7714. sink.os << "PUT";
  7715. return true;
  7716. },
  7717. "text/plain");
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. EXPECT_EQ("PUT", res->body);
  7721. }
  7722. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7723. auto res = cli_.Post(
  7724. "/post", 42,
  7725. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7726. return false;
  7727. },
  7728. "text/plain");
  7729. ASSERT_TRUE(!res);
  7730. EXPECT_EQ(Error::Canceled, res.error());
  7731. }
  7732. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7733. auto res = cli_.Put(
  7734. "/put",
  7735. [](size_t /*offset*/, DataSink &sink) {
  7736. sink.os << "PUT";
  7737. sink.done();
  7738. return true;
  7739. },
  7740. "text/plain");
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ("PUT", res->body);
  7744. }
  7745. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7746. auto res = cli_.Post(
  7747. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7748. "text/plain");
  7749. ASSERT_TRUE(!res);
  7750. EXPECT_EQ(Error::Canceled, res.error());
  7751. }
  7752. TEST_F(ServerTest, PostLoopBack) {
  7753. std::string body;
  7754. auto res = cli_.Post(
  7755. "/post-loopback", 9,
  7756. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7757. EXPECT_EQ(9u, length);
  7758. sink.write("123", 3);
  7759. sink.write("456", 3);
  7760. sink.write("789", 3);
  7761. return true;
  7762. },
  7763. "text/plain",
  7764. [&body](const char *data, size_t data_length) {
  7765. body.append(data, data_length);
  7766. return true;
  7767. });
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. EXPECT_EQ("123456789", body);
  7771. }
  7772. TEST_F(ServerTest, PutLoopBack) {
  7773. std::string body;
  7774. auto res = cli_.Put(
  7775. "/put-loopback", 9,
  7776. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7777. EXPECT_EQ(9u, length);
  7778. sink.write("123", 3);
  7779. sink.write("456", 3);
  7780. sink.write("789", 3);
  7781. return true;
  7782. },
  7783. "text/plain",
  7784. [&body](const char *data, size_t data_length) {
  7785. body.append(data, data_length);
  7786. return true;
  7787. });
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ("123456789", body);
  7791. }
  7792. TEST_F(ServerTest, PatchLoopBack) {
  7793. std::string body;
  7794. auto res = cli_.Patch(
  7795. "/patch-loopback", 9,
  7796. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7797. EXPECT_EQ(9u, length);
  7798. sink.write("123", 3);
  7799. sink.write("456", 3);
  7800. sink.write("789", 3);
  7801. return true;
  7802. },
  7803. "text/plain",
  7804. [&body](const char *data, size_t data_length) {
  7805. body.append(data, data_length);
  7806. return true;
  7807. });
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::OK_200, res->status);
  7810. EXPECT_EQ("123456789", body);
  7811. }
  7812. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7813. std::string body;
  7814. auto res = cli_.Post(
  7815. "/post-loopback",
  7816. [](size_t /*offset*/, DataSink &sink) {
  7817. sink.write("123", 3);
  7818. sink.write("456", 3);
  7819. sink.write("789", 3);
  7820. sink.done();
  7821. return true;
  7822. },
  7823. "text/plain",
  7824. [&body](const char *data, size_t data_length) {
  7825. body.append(data, data_length);
  7826. return true;
  7827. });
  7828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7829. EXPECT_EQ(StatusCode::OK_200, res->status);
  7830. EXPECT_EQ("123456789", body);
  7831. }
  7832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7833. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7834. cli_.set_compress(true);
  7835. auto res = cli_.Put(
  7836. "/put", 3,
  7837. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7838. sink.os << "PUT";
  7839. return true;
  7840. },
  7841. "text/plain");
  7842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7843. EXPECT_EQ(StatusCode::OK_200, res->status);
  7844. EXPECT_EQ("PUT", res->body);
  7845. }
  7846. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7847. cli_.set_compress(true);
  7848. auto res = cli_.Post(
  7849. "/post", 42,
  7850. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7851. return false;
  7852. },
  7853. "text/plain");
  7854. ASSERT_TRUE(!res);
  7855. EXPECT_EQ(Error::Canceled, res.error());
  7856. }
  7857. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7858. cli_.set_compress(true);
  7859. auto res = cli_.Put(
  7860. "/put",
  7861. [](size_t /*offset*/, DataSink &sink) {
  7862. sink.os << "PUT";
  7863. sink.done();
  7864. return true;
  7865. },
  7866. "text/plain");
  7867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. EXPECT_EQ("PUT", res->body);
  7870. }
  7871. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7872. cli_.set_compress(true);
  7873. auto res = cli_.Post(
  7874. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7875. "text/plain");
  7876. ASSERT_TRUE(!res);
  7877. EXPECT_EQ(Error::Canceled, res.error());
  7878. }
  7879. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7880. cli_.set_compress(true);
  7881. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. EXPECT_EQ(StatusCode::OK_200, res->status);
  7884. EXPECT_EQ(LARGE_DATA, res->body);
  7885. }
  7886. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7887. #ifdef CPPHTTPLIB_SSL_ENABLED
  7888. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7889. Client cli(s.c_str());
  7890. cli.enable_server_certificate_verification(false);
  7891. #else
  7892. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7893. Client cli(s.c_str());
  7894. #endif
  7895. cli.set_compress(true);
  7896. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7898. EXPECT_EQ(StatusCode::OK_200, res->status);
  7899. EXPECT_EQ(LARGE_DATA, res->body);
  7900. // The compressed size should be less than a 10th of the original. May vary
  7901. // depending on the zlib library.
  7902. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7903. static_cast<uint64_t>(10 * 1024 * 1024));
  7904. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7905. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7906. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7907. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7908. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7909. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7910. #endif
  7911. }
  7912. TEST_F(ServerTest, PutContentWithDeflate) {
  7913. cli_.set_compress(false);
  7914. Headers headers;
  7915. headers.emplace("Content-Encoding", "deflate");
  7916. // PUT in deflate format:
  7917. auto res = cli_.Put("/put", headers,
  7918. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. EXPECT_EQ("PUT", res->body);
  7922. }
  7923. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7924. Headers headers;
  7925. headers.emplace("Accept-Encoding", "gzip, deflate");
  7926. auto res = cli_.Get("/streamed-chunked", headers);
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. EXPECT_EQ(std::string("123456789"), res->body);
  7930. }
  7931. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7932. Headers headers;
  7933. headers.emplace("Accept-Encoding", "gzip, deflate");
  7934. auto res = cli_.Get("/streamed-chunked2", headers);
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. EXPECT_EQ(std::string("123456789"), res->body);
  7938. }
  7939. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7940. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7942. EXPECT_EQ(StatusCode::OK_200, res->status);
  7943. }
  7944. TEST(GzipDecompressor, ChunkedDecompression) {
  7945. std::string data;
  7946. for (size_t i = 0; i < 32 * 1024; ++i) {
  7947. data.push_back(static_cast<char>('a' + i % 26));
  7948. }
  7949. std::string compressed_data;
  7950. {
  7951. httplib::detail::gzip_compressor compressor;
  7952. bool result = compressor.compress(
  7953. data.data(), data.size(),
  7954. /*last=*/true,
  7955. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7956. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7957. compressed_data_size);
  7958. return true;
  7959. });
  7960. ASSERT_TRUE(result);
  7961. }
  7962. std::string decompressed_data;
  7963. {
  7964. httplib::detail::gzip_decompressor decompressor;
  7965. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7966. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7967. size_t chunk_size = 130;
  7968. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7969. chunk_begin += chunk_size) {
  7970. size_t current_chunk_size =
  7971. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7972. bool result = decompressor.decompress(
  7973. compressed_data.data() + chunk_begin, current_chunk_size,
  7974. [&](const char *decompressed_data_chunk,
  7975. size_t decompressed_data_chunk_size) {
  7976. decompressed_data.insert(decompressed_data.size(),
  7977. decompressed_data_chunk,
  7978. decompressed_data_chunk_size);
  7979. return true;
  7980. });
  7981. ASSERT_TRUE(result);
  7982. }
  7983. }
  7984. ASSERT_EQ(data, decompressed_data);
  7985. }
  7986. TEST(GzipDecompressor, DeflateDecompression) {
  7987. std::string original_text = "Raw deflate without gzip";
  7988. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7989. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7990. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7991. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7992. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7993. std::string decompressed_data;
  7994. {
  7995. httplib::detail::gzip_decompressor decompressor;
  7996. bool result = decompressor.decompress(
  7997. compressed_data.data(), compressed_data.size(),
  7998. [&](const char *decompressed_data_chunk,
  7999. size_t decompressed_data_chunk_size) {
  8000. decompressed_data.insert(decompressed_data.size(),
  8001. decompressed_data_chunk,
  8002. decompressed_data_chunk_size);
  8003. return true;
  8004. });
  8005. ASSERT_TRUE(result);
  8006. }
  8007. ASSERT_EQ(original_text, decompressed_data);
  8008. }
  8009. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8010. std::string original_text = "Raw deflate without gzip";
  8011. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8012. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8013. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8014. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8015. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8016. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8017. std::string decompressed_data;
  8018. {
  8019. httplib::detail::gzip_decompressor decompressor;
  8020. bool result = decompressor.decompress(
  8021. compressed_data.data(), compressed_data.size(),
  8022. [&](const char *decompressed_data_chunk,
  8023. size_t decompressed_data_chunk_size) {
  8024. decompressed_data.insert(decompressed_data.size(),
  8025. decompressed_data_chunk,
  8026. decompressed_data_chunk_size);
  8027. return true;
  8028. });
  8029. ASSERT_TRUE(result);
  8030. }
  8031. ASSERT_EQ(original_text, decompressed_data);
  8032. }
  8033. #endif
  8034. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8035. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8036. Headers headers;
  8037. headers.emplace("Accept-Encoding", "br");
  8038. auto res = cli_.Get("/streamed-chunked", headers);
  8039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. EXPECT_EQ(std::string("123456789"), res->body);
  8042. }
  8043. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8044. Headers headers;
  8045. headers.emplace("Accept-Encoding", "br");
  8046. auto res = cli_.Get("/streamed-chunked2", headers);
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_EQ(std::string("123456789"), res->body);
  8050. }
  8051. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8052. cli_.set_compress(true);
  8053. auto res = cli_.Put(
  8054. "/put", 3,
  8055. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8056. sink.os << "PUT";
  8057. return true;
  8058. },
  8059. "text/plain");
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("PUT", res->body);
  8063. }
  8064. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8065. cli_.set_compress(true);
  8066. auto res = cli_.Put(
  8067. "/put",
  8068. [](size_t /*offset*/, DataSink &sink) {
  8069. sink.os << "PUT";
  8070. sink.done();
  8071. return true;
  8072. },
  8073. "text/plain");
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ(StatusCode::OK_200, res->status);
  8076. EXPECT_EQ("PUT", res->body);
  8077. }
  8078. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8079. cli_.set_compress(true);
  8080. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. EXPECT_EQ(LARGE_DATA, res->body);
  8084. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8085. }
  8086. #endif
  8087. TEST_F(ServerTest, Patch) {
  8088. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. EXPECT_EQ("PATCH", res->body);
  8092. }
  8093. TEST_F(ServerTest, Delete) {
  8094. auto res = cli_.Delete("/delete");
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. EXPECT_EQ("DELETE", res->body);
  8098. }
  8099. TEST_F(ServerTest, DeleteContentReceiver) {
  8100. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8102. EXPECT_EQ(StatusCode::OK_200, res->status);
  8103. EXPECT_EQ("content", res->body);
  8104. }
  8105. TEST_F(ServerTest, Options) {
  8106. auto res = cli_.Options("*");
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8110. EXPECT_TRUE(res->body.empty());
  8111. }
  8112. TEST_F(ServerTest, URL) {
  8113. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. }
  8117. TEST_F(ServerTest, ArrayParam) {
  8118. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8120. EXPECT_EQ(StatusCode::OK_200, res->status);
  8121. }
  8122. TEST_F(ServerTest, ArrayParamValues) {
  8123. auto res =
  8124. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8126. EXPECT_EQ(StatusCode::OK_200, res->status);
  8127. }
  8128. TEST_F(ServerTest, NoMultipleHeaders) {
  8129. Headers headers = {{"Content-Length", "5"}};
  8130. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8131. "text/plain");
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. }
  8135. TEST_F(ServerTest, PostContentReceiver) {
  8136. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. ASSERT_EQ(StatusCode::OK_200, res->status);
  8139. ASSERT_EQ("content", res->body);
  8140. }
  8141. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8142. UploadFormDataItems items = {
  8143. {"text1", "text default", "", ""},
  8144. {"text2", "aωb", "", ""},
  8145. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8146. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8147. {"file3", "", "", "application/octet-stream"},
  8148. };
  8149. auto res = cli_.Post("/content_receiver", items);
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. }
  8153. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8154. UploadFormDataItems items = {
  8155. {"text1", "text default", "", ""},
  8156. {"text2", "aωb", "", ""},
  8157. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8158. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8159. {"file3", "", "", "application/octet-stream"},
  8160. };
  8161. auto boundary = std::string("+++++");
  8162. std::string body;
  8163. for (const auto &item : items) {
  8164. body += "--" + boundary + "\r\n";
  8165. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8166. if (!item.filename.empty()) {
  8167. body += "; filename=\"" + item.filename + "\"";
  8168. }
  8169. body += "\r\n";
  8170. if (!item.content_type.empty()) {
  8171. body += "Content-Type: " + item.content_type + "\r\n";
  8172. }
  8173. body += "\r\n";
  8174. body += item.content + "\r\n";
  8175. }
  8176. body += "--" + boundary + "--\r\n";
  8177. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8178. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. }
  8182. TEST(MultipartFormDataTest, FieldEscaping) {
  8183. Server svr;
  8184. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8185. const ContentReader &content_reader) {
  8186. ASSERT_TRUE(req.is_multipart_form_data());
  8187. std::vector<FormData> received;
  8188. content_reader(
  8189. [&](const FormData &file) {
  8190. received.push_back(file);
  8191. return true;
  8192. },
  8193. [&](const char *data, size_t data_length) {
  8194. received.back().content.append(data, data_length);
  8195. return true;
  8196. });
  8197. // '"', CR and LF in names and filenames are escaped following the
  8198. // WHATWG HTML standard, so each part still parses as a single part
  8199. // with no injected headers. Content types get CR/LF escaped too,
  8200. // while '"' (legal there, e.g. quoted charset) is preserved.
  8201. ASSERT_EQ(4U, received.size());
  8202. EXPECT_EQ("na%22me", received[0].name);
  8203. EXPECT_EQ("quoted name", received[0].content);
  8204. EXPECT_EQ("file", received[1].name);
  8205. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8206. received[1].filename);
  8207. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8208. EXPECT_EQ("injected", received[1].content);
  8209. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8210. EXPECT_EQ("my%22file.txt", received[2].filename);
  8211. EXPECT_EQ("cr lf name", received[2].content);
  8212. EXPECT_EQ("typed", received[3].name);
  8213. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8214. received[3].content_type);
  8215. EXPECT_EQ("typed content", received[3].content);
  8216. });
  8217. auto port = svr.bind_to_any_port("localhost");
  8218. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8219. auto se = detail::scope_exit([&] {
  8220. svr.stop();
  8221. t.join();
  8222. ASSERT_FALSE(svr.is_running());
  8223. });
  8224. svr.wait_until_ready();
  8225. Client cli("localhost", port);
  8226. UploadFormDataItems items = {
  8227. {"na\"me", "quoted name", "", ""},
  8228. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8229. "application/octet-stream"},
  8230. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8231. {"typed", "typed content", "",
  8232. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8233. };
  8234. auto res = cli.Post("/post", items);
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. }
  8238. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8239. const UploadFormDataItems items = {
  8240. {"name1", "Content 1", "", ""},
  8241. {"name2", "Content 2", "file2.txt", "text/plain"},
  8242. };
  8243. Server svr;
  8244. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8245. const ContentReader &content_reader) {
  8246. ASSERT_TRUE(req.is_multipart_form_data());
  8247. std::vector<FormData> received;
  8248. content_reader(
  8249. [&](const FormData &file) {
  8250. received.push_back(file);
  8251. return true;
  8252. },
  8253. [&](const char *data, size_t data_length) {
  8254. received.back().content.append(data, data_length);
  8255. return true;
  8256. });
  8257. ASSERT_EQ(2U, received.size());
  8258. EXPECT_EQ("name1", received[0].name);
  8259. EXPECT_EQ("Content 1", received[0].content);
  8260. EXPECT_EQ("name2", received[1].name);
  8261. EXPECT_EQ("Content 2", received[1].content);
  8262. EXPECT_EQ("file2.txt", received[1].filename);
  8263. EXPECT_EQ("text/plain", received[1].content_type);
  8264. });
  8265. auto port = svr.bind_to_any_port("localhost");
  8266. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8267. auto se = detail::scope_exit([&] {
  8268. svr.stop();
  8269. t.join();
  8270. ASSERT_FALSE(svr.is_running());
  8271. });
  8272. svr.wait_until_ready();
  8273. Client cli("localhost", port);
  8274. // Whole-body serialization with a generated boundary
  8275. {
  8276. MultipartFormDataWriter writer;
  8277. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8278. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8279. writer.content_type());
  8280. auto body = writer.serialize(items);
  8281. EXPECT_EQ(body.size(), writer.content_length(items));
  8282. auto res = cli.Post("/post", body, writer.content_type());
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ(StatusCode::OK_200, res->status);
  8285. }
  8286. // Per-part framing with a custom boundary via a content provider
  8287. {
  8288. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8289. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8290. MultipartFormDataWriter writer("custom-boundary_123");
  8291. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8292. std::string body;
  8293. for (const auto &item : items) {
  8294. body += writer.item_begin(item);
  8295. body += item.content;
  8296. body += MultipartFormDataWriter::item_end();
  8297. }
  8298. body += writer.finish();
  8299. EXPECT_EQ(body.size(), writer.content_length(items));
  8300. auto res = cli.Post(
  8301. "/post", body.size(),
  8302. [&](size_t offset, size_t length, DataSink &sink) {
  8303. sink.write(body.data() + offset, length);
  8304. return true;
  8305. },
  8306. writer.content_type());
  8307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8308. EXPECT_EQ(StatusCode::OK_200, res->status);
  8309. }
  8310. }
  8311. TEST_F(ServerTest, PostContentReceiverGzip) {
  8312. cli_.set_compress(true);
  8313. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8315. ASSERT_EQ(StatusCode::OK_200, res->status);
  8316. ASSERT_EQ("content", res->body);
  8317. }
  8318. TEST_F(ServerTest, PutContentReceiver) {
  8319. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. ASSERT_EQ(StatusCode::OK_200, res->status);
  8322. ASSERT_EQ("content", res->body);
  8323. }
  8324. TEST_F(ServerTest, PatchContentReceiver) {
  8325. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8327. ASSERT_EQ(StatusCode::OK_200, res->status);
  8328. ASSERT_EQ("content", res->body);
  8329. }
  8330. template <typename ClientType>
  8331. void TestWithHeadersAndContentReceiver(
  8332. ClientType &cli,
  8333. std::function<Result(ClientType &, const std::string &, const Headers &,
  8334. const std::string &, const std::string &,
  8335. ContentReceiver, DownloadProgress)>
  8336. request_func) {
  8337. Headers headers;
  8338. headers.emplace("X-Custom-Header", "test-value");
  8339. std::string received_body;
  8340. auto res = request_func(
  8341. cli, "/content_receiver", headers, "content", "application/json",
  8342. [&](const char *data, size_t data_length) {
  8343. received_body.append(data, data_length);
  8344. return true;
  8345. },
  8346. nullptr);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::OK_200, res->status);
  8349. EXPECT_EQ("content", received_body);
  8350. }
  8351. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8352. #ifdef CPPHTTPLIB_SSL_ENABLED
  8353. using ClientT = SSLClient;
  8354. #else
  8355. using ClientT = Client;
  8356. #endif
  8357. TestWithHeadersAndContentReceiver<ClientT>(
  8358. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8359. const std::string &body, const std::string &content_type,
  8360. ContentReceiver receiver, DownloadProgress progress) {
  8361. return cli.Post(path, headers, body, content_type, receiver, progress);
  8362. });
  8363. }
  8364. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8365. #ifdef CPPHTTPLIB_SSL_ENABLED
  8366. using ClientT = SSLClient;
  8367. #else
  8368. using ClientT = Client;
  8369. #endif
  8370. TestWithHeadersAndContentReceiver<ClientT>(
  8371. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8372. const std::string &body, const std::string &content_type,
  8373. ContentReceiver receiver, DownloadProgress progress) {
  8374. return cli.Put(path, headers, body, content_type, receiver, progress);
  8375. });
  8376. }
  8377. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8378. #ifdef CPPHTTPLIB_SSL_ENABLED
  8379. using ClientT = SSLClient;
  8380. #else
  8381. using ClientT = Client;
  8382. #endif
  8383. TestWithHeadersAndContentReceiver<ClientT>(
  8384. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8385. const std::string &body, const std::string &content_type,
  8386. ContentReceiver receiver, DownloadProgress progress) {
  8387. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8388. });
  8389. }
  8390. template <typename ClientType>
  8391. void TestWithHeadersAndContentReceiverWithProgress(
  8392. ClientType &cli,
  8393. std::function<Result(ClientType &, const std::string &, const Headers &,
  8394. const std::string &, const std::string &,
  8395. ContentReceiver, DownloadProgress)>
  8396. request_func) {
  8397. Headers headers;
  8398. headers.emplace("X-Test-Header", "progress-test");
  8399. std::string received_body;
  8400. auto progress_called = false;
  8401. auto res = request_func(
  8402. cli, "/content_receiver", headers, "content", "text/plain",
  8403. [&](const char *data, size_t data_length) {
  8404. received_body.append(data, data_length);
  8405. return true;
  8406. },
  8407. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8408. progress_called = true;
  8409. return true;
  8410. });
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. EXPECT_EQ("content", received_body);
  8414. EXPECT_TRUE(progress_called);
  8415. }
  8416. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8417. #ifdef CPPHTTPLIB_SSL_ENABLED
  8418. using ClientT = SSLClient;
  8419. #else
  8420. using ClientT = Client;
  8421. #endif
  8422. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8423. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8424. const std::string &body, const std::string &content_type,
  8425. ContentReceiver receiver, DownloadProgress progress) {
  8426. return cli.Post(path, headers, body, content_type, receiver, progress);
  8427. });
  8428. }
  8429. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8430. #ifdef CPPHTTPLIB_SSL_ENABLED
  8431. using ClientT = SSLClient;
  8432. #else
  8433. using ClientT = Client;
  8434. #endif
  8435. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8436. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8437. const std::string &body, const std::string &content_type,
  8438. ContentReceiver receiver, DownloadProgress progress) {
  8439. return cli.Put(path, headers, body, content_type, receiver, progress);
  8440. });
  8441. }
  8442. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8443. #ifdef CPPHTTPLIB_SSL_ENABLED
  8444. using ClientT = SSLClient;
  8445. #else
  8446. using ClientT = Client;
  8447. #endif
  8448. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8449. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8450. const std::string &body, const std::string &content_type,
  8451. ContentReceiver receiver, DownloadProgress progress) {
  8452. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8453. });
  8454. }
  8455. template <typename ClientType>
  8456. void TestWithHeadersAndContentReceiverError(
  8457. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8458. const Headers &, const std::string &,
  8459. const std::string &, ContentReceiver)>
  8460. request_func) {
  8461. Headers headers;
  8462. headers.emplace("X-Error-Test", "true");
  8463. std::string received_body;
  8464. auto receiver_failed = false;
  8465. auto res =
  8466. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8467. [&](const char *data, size_t data_length) {
  8468. received_body.append(data, data_length);
  8469. receiver_failed = true;
  8470. return false;
  8471. });
  8472. ASSERT_FALSE(res);
  8473. EXPECT_TRUE(receiver_failed);
  8474. }
  8475. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8476. #ifdef CPPHTTPLIB_SSL_ENABLED
  8477. using ClientT = SSLClient;
  8478. #else
  8479. using ClientT = Client;
  8480. #endif
  8481. TestWithHeadersAndContentReceiverError<ClientT>(
  8482. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8483. const std::string &body, const std::string &content_type,
  8484. ContentReceiver receiver) {
  8485. return cli.Post(path, headers, body, content_type, receiver);
  8486. });
  8487. }
  8488. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8489. #ifdef CPPHTTPLIB_SSL_ENABLED
  8490. using ClientT = SSLClient;
  8491. #else
  8492. using ClientT = Client;
  8493. #endif
  8494. TestWithHeadersAndContentReceiverError<ClientT>(
  8495. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8496. const std::string &body, const std::string &content_type,
  8497. ContentReceiver receiver) {
  8498. return cli.Put(path, headers, body, content_type, receiver);
  8499. });
  8500. }
  8501. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8502. #ifdef CPPHTTPLIB_SSL_ENABLED
  8503. using ClientT = SSLClient;
  8504. #else
  8505. using ClientT = Client;
  8506. #endif
  8507. TestWithHeadersAndContentReceiverError<ClientT>(
  8508. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8509. const std::string &body, const std::string &content_type,
  8510. ContentReceiver receiver) {
  8511. return cli.Patch(path, headers, body, content_type, receiver);
  8512. });
  8513. }
  8514. TEST_F(ServerTest, PostQueryStringAndBody) {
  8515. auto res =
  8516. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. ASSERT_EQ(StatusCode::OK_200, res->status);
  8519. }
  8520. TEST_F(ServerTest, HTTP2Magic) {
  8521. Request req;
  8522. req.method = "PRI";
  8523. req.path = "*";
  8524. req.body = "SM";
  8525. auto res = std::make_shared<Response>();
  8526. auto error = Error::Success;
  8527. auto ret = cli_.send(req, *res, error);
  8528. ASSERT_TRUE(ret);
  8529. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8530. }
  8531. TEST_F(ServerTest, KeepAlive) {
  8532. auto res = cli_.Get("/hi");
  8533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8534. EXPECT_EQ(StatusCode::OK_200, res->status);
  8535. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8536. EXPECT_EQ("Hello World!", res->body);
  8537. res = cli_.Get("/hi");
  8538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8539. EXPECT_EQ(StatusCode::OK_200, res->status);
  8540. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8541. EXPECT_EQ("Hello World!", res->body);
  8542. res = cli_.Get("/hi");
  8543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8544. EXPECT_EQ(StatusCode::OK_200, res->status);
  8545. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8546. EXPECT_EQ("Hello World!", res->body);
  8547. res = cli_.Get("/not-exist");
  8548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8550. res = cli_.Post("/empty", "", "text/plain");
  8551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8552. EXPECT_EQ(StatusCode::OK_200, res->status);
  8553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8554. EXPECT_EQ("empty", res->body);
  8555. EXPECT_EQ("close", res->get_header_value("Connection"));
  8556. res = cli_.Post(
  8557. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8558. "text/plain");
  8559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8560. EXPECT_EQ(StatusCode::OK_200, res->status);
  8561. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8562. EXPECT_EQ("empty", res->body);
  8563. cli_.set_keep_alive(false);
  8564. res = cli_.Get("/last-request");
  8565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8566. EXPECT_EQ(StatusCode::OK_200, res->status);
  8567. EXPECT_EQ("close", res->get_header_value("Connection"));
  8568. }
  8569. TEST_F(ServerTest, TooManyRedirect) {
  8570. cli_.set_follow_location(true);
  8571. auto res = cli_.Get("/redirect/0");
  8572. ASSERT_TRUE(!res);
  8573. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8574. }
  8575. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8576. Request req;
  8577. req.method = "FOOBAR";
  8578. req.path = "/hi";
  8579. cli_.set_keep_alive(true);
  8580. auto res = cli_.send(req);
  8581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8582. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8583. EXPECT_EQ("close", res->get_header_value("Connection"));
  8584. EXPECT_FALSE(cli_.is_socket_open());
  8585. }
  8586. TEST_F(ServerTest, CustomRouteReadsBody) {
  8587. const std::string xml =
  8588. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8589. Request req;
  8590. req.method = "PROPFIND";
  8591. req.path = "/dav/dir";
  8592. req.set_header("Depth", "1");
  8593. req.body = xml;
  8594. auto res = cli_.send(req);
  8595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8596. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8597. EXPECT_EQ(xml, res->body);
  8598. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8599. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8600. }
  8601. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8602. Request req;
  8603. req.method = "PROPFIND";
  8604. req.path = "/dav/42";
  8605. auto res = cli_.send(req);
  8606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8607. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8608. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8609. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8610. }
  8611. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8612. Request req;
  8613. req.method = "PROPFIND";
  8614. req.path = "/dav-re/123";
  8615. auto res = cli_.send(req);
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8618. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8619. }
  8620. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8621. Request req;
  8622. req.method = "MKCOL";
  8623. req.path = "/dav-mkcol";
  8624. auto res = cli_.send(req);
  8625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8626. EXPECT_EQ(StatusCode::Created_201, res->status);
  8627. }
  8628. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8629. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8630. Request req;
  8631. req.method = "REPORT";
  8632. req.path = "/dav-report";
  8633. req.body = xml;
  8634. auto res = cli_.send(req);
  8635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8636. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8637. EXPECT_EQ(xml, res->body);
  8638. }
  8639. // A content reader route must fire even when the request carries no body,
  8640. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8641. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8642. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8643. Request req;
  8644. req.method = "REPORT";
  8645. req.path = "/dav-report";
  8646. auto res = cli_.send(req);
  8647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8648. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8649. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8650. }
  8651. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8652. Request req;
  8653. req.method = "PROPFIND";
  8654. req.path = "/not-dav";
  8655. auto res = cli_.send(req);
  8656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8657. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8658. }
  8659. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8660. Request req;
  8661. req.method = "UNLOCK";
  8662. req.path = "/dav/dir";
  8663. cli_.set_keep_alive(true);
  8664. auto res = cli_.send(req);
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8667. EXPECT_EQ("close", res->get_header_value("Connection"));
  8668. EXPECT_FALSE(cli_.is_socket_open());
  8669. }
  8670. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8671. // The mount point serves this path, but only for GET and HEAD.
  8672. auto get_res = cli_.Get("/dir/index.html");
  8673. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8674. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8675. Request req;
  8676. req.method = "PROPFIND";
  8677. req.path = "/dir/index.html";
  8678. auto res = cli_.send(req);
  8679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8681. }
  8682. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8683. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8684. cli_.set_keep_alive(true);
  8685. for (auto i = 0; i < 2; i++) {
  8686. Request req;
  8687. req.method = "PROPFIND";
  8688. req.path = "/dav/dir";
  8689. req.body = xml;
  8690. auto res = cli_.send(req);
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8693. EXPECT_EQ(xml, res->body);
  8694. EXPECT_TRUE(cli_.is_socket_open());
  8695. }
  8696. // A built-in method must still be served on the same connection.
  8697. cli_.set_keep_alive(false);
  8698. auto res = cli_.Get("/hi");
  8699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8700. EXPECT_EQ(StatusCode::OK_200, res->status);
  8701. EXPECT_EQ("close", res->get_header_value("Connection"));
  8702. }
  8703. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8704. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8705. Request req;
  8706. req.method = "PROPFIND";
  8707. req.path = "/dav/dir";
  8708. req.set_header("Expect", "100-continue");
  8709. req.body = xml;
  8710. auto res = cli_.send(req);
  8711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8712. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8713. EXPECT_EQ(xml, res->body);
  8714. }
  8715. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8716. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8717. TEST_F(ServerTest, Gzip) {
  8718. Headers headers;
  8719. headers.emplace("Accept-Encoding", "gzip, deflate");
  8720. auto res = cli_.Get("/compress", headers);
  8721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8722. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8724. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8725. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8726. "7890123456789012345678901234567890",
  8727. res->body);
  8728. EXPECT_EQ(StatusCode::OK_200, res->status);
  8729. }
  8730. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8731. Headers headers;
  8732. headers.emplace("Accept-Encoding", "gzip, deflate");
  8733. auto res = cli_.Get("/compress-with-charset", headers);
  8734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8735. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8736. EXPECT_EQ("application/json; charset=utf-8",
  8737. res->get_header_value("Content-Type"));
  8738. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8739. "7890123456789012345678901234567890",
  8740. res->body);
  8741. EXPECT_EQ(StatusCode::OK_200, res->status);
  8742. }
  8743. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8744. Headers headers;
  8745. headers.emplace("Accept-Encoding", "");
  8746. auto res = cli_.Get("/compress", headers);
  8747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8748. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8749. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8750. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8751. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8752. "7890123456789012345678901234567890",
  8753. res->body);
  8754. EXPECT_EQ(StatusCode::OK_200, res->status);
  8755. }
  8756. TEST_F(ServerTest, GzipWithContentReceiver) {
  8757. Headers headers;
  8758. headers.emplace("Accept-Encoding", "gzip, deflate");
  8759. std::string body;
  8760. auto res =
  8761. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8762. EXPECT_EQ(100U, data_length);
  8763. body.append(data, data_length);
  8764. return true;
  8765. });
  8766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8767. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8769. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8770. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8771. "7890123456789012345678901234567890",
  8772. body);
  8773. EXPECT_EQ(StatusCode::OK_200, res->status);
  8774. }
  8775. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8776. Headers headers;
  8777. headers.emplace("Accept-Encoding", "gzip, deflate");
  8778. cli_.set_decompress(false);
  8779. auto res = cli_.Get("/compress", headers);
  8780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8782. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8783. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8784. EXPECT_EQ(33U, res->body.size());
  8785. EXPECT_EQ(StatusCode::OK_200, res->status);
  8786. }
  8787. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8788. Headers headers;
  8789. headers.emplace("Accept-Encoding", "");
  8790. std::string body;
  8791. auto res =
  8792. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8793. EXPECT_EQ(100U, data_length);
  8794. body.append(data, data_length);
  8795. return true;
  8796. });
  8797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8798. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8799. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8800. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8801. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8802. "7890123456789012345678901234567890",
  8803. body);
  8804. EXPECT_EQ(StatusCode::OK_200, res->status);
  8805. }
  8806. TEST_F(ServerTest, NoGzip) {
  8807. Headers headers;
  8808. headers.emplace("Accept-Encoding", "gzip, deflate");
  8809. auto res = cli_.Get("/nocompress", headers);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8812. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8813. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8814. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8815. "7890123456789012345678901234567890",
  8816. res->body);
  8817. EXPECT_EQ(StatusCode::OK_200, res->status);
  8818. }
  8819. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "gzip, deflate");
  8822. std::string body;
  8823. auto res = cli_.Get("/nocompress", headers,
  8824. [&](const char *data, size_t data_length) {
  8825. EXPECT_EQ(100U, data_length);
  8826. body.append(data, data_length);
  8827. return true;
  8828. });
  8829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8830. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8831. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8832. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8833. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8834. "7890123456789012345678901234567890",
  8835. body);
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. }
  8838. TEST_F(ServerTest, MultipartFormDataGzip) {
  8839. UploadFormDataItems items = {
  8840. {"key1", "test", "", ""},
  8841. {"key2", "--abcdefg123", "", ""},
  8842. };
  8843. cli_.set_compress(true);
  8844. auto res = cli_.Post("/compress-multipart", items);
  8845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. #endif
  8849. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8850. // Static file compression is opt-in, so these run their own server rather than
  8851. // flipping it on for the shared ServerTest fixture, which would silently
  8852. // rewrite what every other static file test is asserting.
  8853. class StaticFileCompressionTest : public ::testing::Test {
  8854. protected:
  8855. void TearDown() override {
  8856. if (t_.joinable()) {
  8857. svr_.stop();
  8858. t_.join();
  8859. }
  8860. }
  8861. int start(const std::function<void(Server &)> &configure = nullptr) {
  8862. // Serves the same tree as a directory of build-time compressed assets
  8863. // would be served: the mount point names the coding the files are already
  8864. // stored in. Registered before "/" so it is the one that matches.
  8865. svr_.set_mount_point("/pre-encoded", "./www",
  8866. {{"Content-Encoding", "gzip"}});
  8867. svr_.set_mount_point("/", "./www");
  8868. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8869. res.set_file_content("./www/dir/index.html", "text/html");
  8870. });
  8871. svr_.Get("/pre-encoded-file-content",
  8872. [](const Request & /*req*/, Response &res) {
  8873. res.set_header("Content-Encoding", "gzip");
  8874. res.set_file_content("./www/dir/index.html", "text/html");
  8875. });
  8876. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8877. res.set_content_provider(
  8878. 6, "text/plain",
  8879. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8880. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8881. return true;
  8882. });
  8883. });
  8884. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8885. res.set_content_provider(
  8886. 1000, "text/plain",
  8887. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8888. if (offset < 100) {
  8889. std::string data(100, 'A');
  8890. sink.write(data.data(), data.size());
  8891. return true;
  8892. }
  8893. std::this_thread::sleep_for(std::chrono::seconds(2));
  8894. std::string data(900, 'B');
  8895. sink.write(data.data(), data.size());
  8896. return true;
  8897. });
  8898. });
  8899. if (configure) { configure(svr_); }
  8900. auto port = svr_.bind_to_any_port(HOST);
  8901. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8902. svr_.wait_until_ready();
  8903. return port;
  8904. }
  8905. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8906. // Every file under ./www except 1MB.txt is smaller than the default
  8907. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8908. // it out of the way.
  8909. static void enable_without_floor(Server &svr) {
  8910. svr.set_static_file_compression(true);
  8911. svr.set_static_file_compression_min_length(0);
  8912. }
  8913. Server svr_;
  8914. std::thread t_;
  8915. };
  8916. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8917. auto port = start();
  8918. Client cli(HOST, port);
  8919. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8921. EXPECT_EQ(StatusCode::OK_200, res->status);
  8922. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8923. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8924. EXPECT_EQ(1048576U, res->body.size());
  8925. }
  8926. TEST_F(StaticFileCompressionTest, MountPoint) {
  8927. auto port = start(enable);
  8928. Client cli(HOST, port);
  8929. cli.set_decompress(false);
  8930. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8932. EXPECT_EQ(StatusCode::OK_200, res->status);
  8933. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8934. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8935. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8936. // The response stays self-delimiting: a length, not a chunked body.
  8937. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8938. EXPECT_EQ(std::to_string(res->body.size()),
  8939. res->get_header_value("Content-Length"));
  8940. EXPECT_LT(res->body.size(), 1048576U);
  8941. EXPECT_FALSE(res->body.empty());
  8942. }
  8943. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8944. auto port = start(enable);
  8945. Client cli(HOST, port);
  8946. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8948. EXPECT_EQ(StatusCode::OK_200, res->status);
  8949. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8950. EXPECT_EQ(1048576U, res->body.size());
  8951. }
  8952. TEST_F(StaticFileCompressionTest, FileContent) {
  8953. auto port = start(enable_without_floor);
  8954. Client cli(HOST, port);
  8955. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8957. EXPECT_EQ(StatusCode::OK_200, res->status);
  8958. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8959. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8960. EXPECT_EQ(104U, res->body.size());
  8961. }
  8962. // A handler that serves an already-encoded file names the coding itself. The
  8963. // file-backed path decided its coding from Accept-Encoding and the content
  8964. // type alone, so it compressed the stored bytes a second time and appended a
  8965. // second Content-Encoding field line.
  8966. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8967. auto port = start(enable_without_floor);
  8968. Client cli(HOST, port);
  8969. cli.set_decompress(false);
  8970. auto res = cli.Get("/pre-encoded-file-content",
  8971. Headers{{"Accept-Encoding", "gzip"}});
  8972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8973. EXPECT_EQ(StatusCode::OK_200, res->status);
  8974. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8975. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8976. // Vary belongs to a coding the server chose, and it chose none here.
  8977. EXPECT_FALSE(res->has_header("Vary"));
  8978. // The file travels exactly as it is stored on disk.
  8979. EXPECT_EQ(104U, res->body.size());
  8980. }
  8981. // The 1MB file clears the default floor, so this one runs the configuration a
  8982. // deployment would actually have.
  8983. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8984. auto port = start(enable);
  8985. Client cli(HOST, port);
  8986. cli.set_decompress(false);
  8987. auto res =
  8988. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8990. EXPECT_EQ(StatusCode::OK_200, res->status);
  8991. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8992. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8993. EXPECT_FALSE(res->has_header("Vary"));
  8994. EXPECT_EQ(1048576U, res->body.size());
  8995. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8996. }
  8997. TEST_F(StaticFileCompressionTest, Head) {
  8998. auto port = start(enable);
  8999. Client cli(HOST, port);
  9000. cli.set_decompress(false);
  9001. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9002. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9003. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9005. EXPECT_EQ(StatusCode::OK_200, res->status);
  9006. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9007. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9008. // HEAD still reports the size a GET would return.
  9009. EXPECT_EQ(get->get_header_value("Content-Length"),
  9010. res->get_header_value("Content-Length"));
  9011. EXPECT_TRUE(res->body.empty());
  9012. }
  9013. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9014. auto port = start(enable);
  9015. Client cli(HOST, port);
  9016. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9017. {"Accept-Encoding", "gzip"}});
  9018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9020. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9021. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9022. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9023. EXPECT_EQ("cd", res->body);
  9024. }
  9025. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9026. auto port = start(enable);
  9027. Client cli(HOST, port);
  9028. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9030. EXPECT_EQ(StatusCode::OK_200, res->status);
  9031. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9032. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9033. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9034. }
  9035. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9036. auto port = start(enable);
  9037. Client cli(HOST, port);
  9038. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9040. EXPECT_EQ(StatusCode::OK_200, res->status);
  9041. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9042. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9043. EXPECT_TRUE(res->body.empty());
  9044. }
  9045. TEST_F(StaticFileCompressionTest, MinLength) {
  9046. auto port = start(enable);
  9047. Client cli(HOST, port);
  9048. // 104 bytes, well under the default floor. Compressing it would add the
  9049. // gzip header and trailer to a body that already fits in one packet.
  9050. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9052. EXPECT_EQ(StatusCode::OK_200, res->status);
  9053. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9054. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9055. }
  9056. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9057. auto port = start([](Server &svr) {
  9058. svr.set_static_file_compression(true);
  9059. svr.set_static_file_compression_min_length(1);
  9060. });
  9061. Client cli(HOST, port);
  9062. cli.set_decompress(false);
  9063. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9065. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9066. // A 9-byte file comes back larger than it went in, because gzip's header and
  9067. // trailer outweigh anything deflate can save. That is the end of the range
  9068. // the floor exists to keep out.
  9069. EXPECT_GT(res->body.size(), 9U);
  9070. }
  9071. TEST_F(StaticFileCompressionTest, MaxLength) {
  9072. auto port = start([](Server &svr) {
  9073. svr.set_static_file_compression(true);
  9074. svr.set_static_file_compression_min_length(0);
  9075. svr.set_static_file_compression_max_length(1024);
  9076. });
  9077. Client cli(HOST, port);
  9078. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9079. // defines `small` as a macro on Windows.
  9080. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9081. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9082. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9083. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9084. // Under it: compressed.
  9085. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9086. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9087. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9088. }
  9089. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9090. auto port = start(enable_without_floor);
  9091. Client cli(HOST, port);
  9092. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9093. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9094. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9095. auto identity_etag = identity->get_header_value("ETag");
  9096. ASSERT_FALSE(identity_etag.empty());
  9097. auto gzipped =
  9098. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9099. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9100. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9101. auto gzip_etag = gzipped->get_header_value("ETag");
  9102. ASSERT_FALSE(gzip_etag.empty());
  9103. // Two representations, two validators.
  9104. EXPECT_NE(identity_etag, gzip_etag);
  9105. // Each one revalidates against the request that would produce it...
  9106. auto fresh =
  9107. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9108. {"If-None-Match", gzip_etag}});
  9109. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9110. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9111. auto fresh_identity =
  9112. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9113. {"If-None-Match", identity_etag}});
  9114. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9115. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9116. // ...and not against the other representation.
  9117. auto crossed =
  9118. cli.Get("/dir/index.html",
  9119. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9120. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9121. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9122. }
  9123. // The opt-in covers responses the server reads off disk itself. A caller's own
  9124. // known-length provider keeps its Content-Length and, more importantly, keeps
  9125. // delivering incrementally: routing it through a compressor would hold every
  9126. // write back until zlib's window filled.
  9127. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9128. auto port = start(enable);
  9129. Client cli(HOST, port);
  9130. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9132. EXPECT_EQ(StatusCode::OK_200, res->status);
  9133. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9134. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9135. EXPECT_EQ("aaabbb", res->body);
  9136. }
  9137. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9138. auto port = start(enable);
  9139. Client cli(HOST, port);
  9140. cli.set_read_timeout(1, 0);
  9141. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9142. Headers{{"Accept-Encoding", "gzip"}});
  9143. ASSERT_TRUE(handle.is_valid());
  9144. // The provider writes 100 bytes and then stalls for longer than the read
  9145. // timeout. Those first bytes have to arrive anyway: run the response through
  9146. // a compressor and zlib holds them until its window fills, so the read would
  9147. // come back empty instead.
  9148. char buf[256];
  9149. auto n = handle.read(buf, sizeof(buf));
  9150. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9151. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9152. }
  9153. #endif
  9154. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9155. TEST_F(ServerTest, Brotli) {
  9156. Headers headers;
  9157. headers.emplace("Accept-Encoding", "br");
  9158. auto res = cli_.Get("/compress", headers);
  9159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9160. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9162. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9164. "7890123456789012345678901234567890",
  9165. res->body);
  9166. EXPECT_EQ(StatusCode::OK_200, res->status);
  9167. }
  9168. #endif
  9169. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9170. TEST_F(ServerTest, Zstd) {
  9171. Headers headers;
  9172. headers.emplace("Accept-Encoding", "zstd");
  9173. auto res = cli_.Get("/compress", headers);
  9174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9175. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9177. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9178. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9179. "7890123456789012345678901234567890",
  9180. res->body);
  9181. EXPECT_EQ(StatusCode::OK_200, res->status);
  9182. }
  9183. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9184. Headers headers;
  9185. headers.emplace("Accept-Encoding", "");
  9186. auto res = cli_.Get("/compress", headers);
  9187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9188. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9190. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9191. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9192. "7890123456789012345678901234567890",
  9193. res->body);
  9194. EXPECT_EQ(StatusCode::OK_200, res->status);
  9195. }
  9196. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9197. Headers headers;
  9198. headers.emplace("Accept-Encoding", "zstd");
  9199. std::string body;
  9200. auto res =
  9201. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9202. EXPECT_EQ(100U, data_length);
  9203. body.append(data, data_length);
  9204. return true;
  9205. });
  9206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9207. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9209. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9210. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9211. "7890123456789012345678901234567890",
  9212. body);
  9213. EXPECT_EQ(StatusCode::OK_200, res->status);
  9214. }
  9215. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9216. Headers headers;
  9217. headers.emplace("Accept-Encoding", "zstd");
  9218. cli_.set_decompress(false);
  9219. auto res = cli_.Get("/compress", headers);
  9220. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9221. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9222. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9223. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9225. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9227. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9228. EXPECT_EQ(StatusCode::OK_200, res->status);
  9229. ASSERT_EQ(26U, res->body.size());
  9230. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9231. 0);
  9232. }
  9233. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9234. Headers headers;
  9235. headers.emplace("Accept-Encoding", "");
  9236. std::string body;
  9237. auto res =
  9238. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9239. EXPECT_EQ(100U, data_length);
  9240. body.append(data, data_length);
  9241. return true;
  9242. });
  9243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9244. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9246. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9247. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9248. "7890123456789012345678901234567890",
  9249. body);
  9250. EXPECT_EQ(StatusCode::OK_200, res->status);
  9251. }
  9252. TEST_F(ServerTest, NoZstd) {
  9253. Headers headers;
  9254. headers.emplace("Accept-Encoding", "zstd");
  9255. auto res = cli_.Get("/nocompress", headers);
  9256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9257. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9258. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9259. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9260. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9261. "7890123456789012345678901234567890",
  9262. res->body);
  9263. EXPECT_EQ(StatusCode::OK_200, res->status);
  9264. }
  9265. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9266. Headers headers;
  9267. headers.emplace("Accept-Encoding", "zstd");
  9268. std::string body;
  9269. auto res = cli_.Get("/nocompress", headers,
  9270. [&](const char *data, size_t data_length) {
  9271. EXPECT_EQ(100U, data_length);
  9272. body.append(data, data_length);
  9273. return true;
  9274. });
  9275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9276. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9277. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9278. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9279. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9280. "7890123456789012345678901234567890",
  9281. body);
  9282. EXPECT_EQ(StatusCode::OK_200, res->status);
  9283. }
  9284. // TODO: How to enable zstd ??
  9285. TEST_F(ServerTest, MultipartFormDataZstd) {
  9286. UploadFormDataItems items = {
  9287. {"key1", "test", "", ""},
  9288. {"key2", "--abcdefg123", "", ""},
  9289. };
  9290. Headers headers;
  9291. headers.emplace("Accept-Encoding", "zstd");
  9292. cli_.set_compress(true);
  9293. auto res = cli_.Post("/compress-multipart", headers, items);
  9294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9295. EXPECT_EQ(StatusCode::OK_200, res->status);
  9296. }
  9297. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9298. Headers headers;
  9299. headers.emplace("Accept-Encoding", "zstd");
  9300. cli_.set_compress(true);
  9301. auto res = cli_.Put(
  9302. "/put", headers, 3,
  9303. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9304. sink.os << "PUT";
  9305. return true;
  9306. },
  9307. "text/plain");
  9308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9309. EXPECT_EQ(StatusCode::OK_200, res->status);
  9310. EXPECT_EQ("PUT", res->body);
  9311. }
  9312. // Pre-compression logging tests
  9313. TEST_F(ServerTest, PreCompressionLogging) {
  9314. // Test data for compression (matches the actual /compress endpoint content)
  9315. const std::string test_content =
  9316. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9317. "3456789012345678901234567890";
  9318. // Variables to capture logging data
  9319. std::string pre_compression_body;
  9320. std::string pre_compression_content_type;
  9321. std::string pre_compression_content_encoding;
  9322. std::string post_compression_body;
  9323. std::string post_compression_content_type;
  9324. std::string post_compression_content_encoding;
  9325. // Set up pre-compression logger
  9326. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9327. const Response &res) {
  9328. pre_compression_body = res.body;
  9329. pre_compression_content_type = res.get_header_value("Content-Type");
  9330. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9331. });
  9332. // Set up post-compression logger
  9333. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9334. post_compression_body = res.body;
  9335. post_compression_content_type = res.get_header_value("Content-Type");
  9336. post_compression_content_encoding =
  9337. res.get_header_value("Content-Encoding");
  9338. });
  9339. // Test with gzip compression
  9340. Headers headers;
  9341. headers.emplace("Accept-Encoding", "gzip");
  9342. auto res = cli_.Get("/compress", headers);
  9343. // Verify response was compressed
  9344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9345. EXPECT_EQ(StatusCode::OK_200, res->status);
  9346. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9347. // Verify pre-compression logger captured uncompressed content
  9348. EXPECT_EQ(test_content, pre_compression_body);
  9349. EXPECT_EQ("text/plain", pre_compression_content_type);
  9350. EXPECT_TRUE(pre_compression_content_encoding
  9351. .empty()); // No encoding header before compression
  9352. // Verify post-compression logger captured compressed content
  9353. EXPECT_NE(test_content,
  9354. post_compression_body); // Should be different after compression
  9355. EXPECT_EQ("text/plain", post_compression_content_type);
  9356. EXPECT_EQ("gzip", post_compression_content_encoding);
  9357. // Verify compressed content is smaller
  9358. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9359. }
  9360. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9361. const std::string test_content =
  9362. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9363. "3456789012345678901234567890";
  9364. std::string pre_compression_body;
  9365. std::string post_compression_body;
  9366. svr_.set_pre_compression_logger(
  9367. [&](const Request & /*req*/, const Response &res) {
  9368. pre_compression_body = res.body;
  9369. });
  9370. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9371. post_compression_body = res.body;
  9372. });
  9373. Headers headers;
  9374. headers.emplace("Accept-Encoding", "br");
  9375. auto res = cli_.Get("/compress", headers);
  9376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9377. EXPECT_EQ(StatusCode::OK_200, res->status);
  9378. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9379. // Verify pre-compression content is uncompressed
  9380. EXPECT_EQ(test_content, pre_compression_body);
  9381. // Verify post-compression content is compressed
  9382. EXPECT_NE(test_content, post_compression_body);
  9383. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9384. }
  9385. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9386. const std::string test_content =
  9387. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9388. "3456789012345678901234567890";
  9389. std::string pre_compression_body;
  9390. std::string post_compression_body;
  9391. svr_.set_pre_compression_logger(
  9392. [&](const Request & /*req*/, const Response &res) {
  9393. pre_compression_body = res.body;
  9394. });
  9395. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9396. post_compression_body = res.body;
  9397. });
  9398. // Request without compression (use /nocompress endpoint)
  9399. Headers headers;
  9400. auto res = cli_.Get("/nocompress", headers);
  9401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9402. EXPECT_EQ(StatusCode::OK_200, res->status);
  9403. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9404. // Pre-compression logger should not be called when no compression is applied
  9405. EXPECT_TRUE(
  9406. pre_compression_body.empty()); // Pre-compression logger not called
  9407. EXPECT_EQ(
  9408. test_content,
  9409. post_compression_body); // Post-compression logger captures final content
  9410. }
  9411. TEST_F(ServerTest, LoggerSeesContentLength) {
  9412. size_t logged_content_length = 0;
  9413. std::string logged_content_length_header;
  9414. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9415. logged_content_length = res.content_length_;
  9416. logged_content_length_header = res.get_header_value("Content-Length");
  9417. });
  9418. auto res = cli_.Get("/nocompress");
  9419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9420. EXPECT_EQ(StatusCode::OK_200, res->status);
  9421. EXPECT_EQ(res->body.size(), logged_content_length);
  9422. EXPECT_EQ(std::to_string(logged_content_length),
  9423. logged_content_length_header);
  9424. }
  9425. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9426. const std::string test_content =
  9427. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9428. "3456789012345678901234567890";
  9429. std::string pre_compression_body;
  9430. bool pre_logger_called = false;
  9431. // Set only pre-compression logger
  9432. svr_.set_pre_compression_logger(
  9433. [&](const Request & /*req*/, const Response &res) {
  9434. pre_compression_body = res.body;
  9435. pre_logger_called = true;
  9436. });
  9437. Headers headers;
  9438. headers.emplace("Accept-Encoding", "gzip");
  9439. auto res = cli_.Get("/compress", headers);
  9440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9441. EXPECT_EQ(StatusCode::OK_200, res->status);
  9442. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9443. // Verify pre-compression logger was called
  9444. EXPECT_TRUE(pre_logger_called);
  9445. EXPECT_EQ(test_content, pre_compression_body);
  9446. }
  9447. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9448. {
  9449. // Test with Expect: 100-continue header - success case
  9450. // Server returns 100 Continue, client sends body, server returns 200 OK
  9451. Request req;
  9452. req.method = "POST";
  9453. req.path = "/post-large";
  9454. req.set_header("Expect", "100-continue");
  9455. req.body = LARGE_DATA;
  9456. Response res;
  9457. auto error = Error::Success;
  9458. cli_.set_keep_alive(true);
  9459. auto ret = cli_.send(req, res, error);
  9460. EXPECT_TRUE(ret);
  9461. EXPECT_EQ(StatusCode::OK_200, res.status);
  9462. EXPECT_EQ(LARGE_DATA, res.body);
  9463. }
  9464. {
  9465. // Test with Expect: 100-continue header - error case
  9466. // Client should not send the body when server returns an error
  9467. Request req;
  9468. req.method = "POST";
  9469. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9470. req.set_header("Expect", "100-continue");
  9471. req.body = LARGE_DATA;
  9472. Response res;
  9473. auto error = Error::Success;
  9474. auto start = std::chrono::high_resolution_clock::now();
  9475. cli_.set_keep_alive(true);
  9476. auto ret = cli_.send(req, res, error);
  9477. auto end = std::chrono::high_resolution_clock::now();
  9478. auto elapsed =
  9479. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9480. .count();
  9481. // With Expect: 100-continue, request completes successfully but with error
  9482. EXPECT_TRUE(ret);
  9483. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9484. EXPECT_EQ("close", res.get_header_value("Connection"));
  9485. EXPECT_FALSE(cli_.is_socket_open());
  9486. EXPECT_LE(elapsed, 2000);
  9487. }
  9488. {
  9489. // Send an extra GET request to ensure error recovery without hanging
  9490. Request req;
  9491. req.method = "GET";
  9492. req.path = "/hi";
  9493. auto start = std::chrono::high_resolution_clock::now();
  9494. auto res = cli_.send(req);
  9495. auto end = std::chrono::high_resolution_clock::now();
  9496. auto elapsed =
  9497. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9498. .count();
  9499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9500. EXPECT_EQ(StatusCode::OK_200, res->status);
  9501. EXPECT_EQ("Hello World!", res->body);
  9502. EXPECT_LE(elapsed, 500);
  9503. }
  9504. }
  9505. TEST(ZstdDecompressor, ChunkedDecompression) {
  9506. std::string data;
  9507. for (size_t i = 0; i < 32 * 1024; ++i) {
  9508. data.push_back(static_cast<char>('a' + i % 26));
  9509. }
  9510. std::string compressed_data;
  9511. {
  9512. httplib::detail::zstd_compressor compressor;
  9513. bool result = compressor.compress(
  9514. data.data(), data.size(),
  9515. /*last=*/true,
  9516. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9517. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9518. compressed_data_size);
  9519. return true;
  9520. });
  9521. ASSERT_TRUE(result);
  9522. }
  9523. std::string decompressed_data;
  9524. {
  9525. httplib::detail::zstd_decompressor decompressor;
  9526. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9527. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9528. size_t chunk_size = 130;
  9529. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9530. chunk_begin += chunk_size) {
  9531. size_t current_chunk_size =
  9532. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9533. bool result = decompressor.decompress(
  9534. compressed_data.data() + chunk_begin, current_chunk_size,
  9535. [&](const char *decompressed_data_chunk,
  9536. size_t decompressed_data_chunk_size) {
  9537. decompressed_data.insert(decompressed_data.size(),
  9538. decompressed_data_chunk,
  9539. decompressed_data_chunk_size);
  9540. return true;
  9541. });
  9542. ASSERT_TRUE(result);
  9543. }
  9544. }
  9545. ASSERT_EQ(data, decompressed_data);
  9546. }
  9547. TEST(ZstdDecompressor, Decompress) {
  9548. std::string original_text = "Compressed with ZSTD";
  9549. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9550. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9551. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9552. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9553. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9554. std::string decompressed_data;
  9555. {
  9556. httplib::detail::zstd_decompressor decompressor;
  9557. bool result = decompressor.decompress(
  9558. compressed_data.data(), compressed_data.size(),
  9559. [&](const char *decompressed_data_chunk,
  9560. size_t decompressed_data_chunk_size) {
  9561. decompressed_data.insert(decompressed_data.size(),
  9562. decompressed_data_chunk,
  9563. decompressed_data_chunk_size);
  9564. return true;
  9565. });
  9566. ASSERT_TRUE(result);
  9567. }
  9568. ASSERT_EQ(original_text, decompressed_data);
  9569. }
  9570. #endif
  9571. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9572. // separate chunks so that the server sees each part in its own read(). Used to
  9573. // place a read boundary at a specific offset of a request body.
  9574. static bool send_request_in_parts(time_t read_timeout_sec,
  9575. const std::vector<std::string> &parts,
  9576. std::string *resp = nullptr,
  9577. int port = PORT) {
  9578. auto error = Error::Success;
  9579. auto client_sock = detail::create_client_socket(
  9580. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9581. /*connection_timeout_sec=*/5, 0,
  9582. /*read_timeout_sec=*/5, 0,
  9583. /*write_timeout_sec=*/5, 0, std::string(), error);
  9584. if (client_sock == INVALID_SOCKET) { return false; }
  9585. auto ret = detail::process_client_socket(
  9586. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9587. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9588. for (size_t i = 0; i < parts.size(); i++) {
  9589. const auto &part = parts[i];
  9590. if (part.size() !=
  9591. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9592. return false;
  9593. }
  9594. if (i + 1 < parts.size()) {
  9595. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9596. }
  9597. }
  9598. char buf[512];
  9599. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9600. while (line_reader.getline()) {
  9601. if (resp) { *resp += line_reader.ptr(); }
  9602. }
  9603. return true;
  9604. });
  9605. detail::close_socket(client_sock);
  9606. return ret;
  9607. }
  9608. // Sends a raw request to a server listening at HOST:PORT.
  9609. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9610. std::string *resp = nullptr, int port = PORT) {
  9611. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9612. }
  9613. #ifdef CPPHTTPLIB_SSL_ENABLED
  9614. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9615. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9616. ASSERT_TRUE(svr.is_valid());
  9617. svr.set_read_timeout(1, 0);
  9618. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9619. auto se = detail::scope_exit([&] {
  9620. svr.stop();
  9621. t.join();
  9622. ASSERT_FALSE(svr.is_running());
  9623. });
  9624. svr.wait_until_ready();
  9625. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9626. // keeps each wait well within the read timeout. The server gives up a
  9627. // second in, so the bytes sent after that fail.
  9628. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9629. parts.resize(26, std::string(1, '\0'));
  9630. EXPECT_FALSE(send_request_in_parts(5, parts));
  9631. }
  9632. #endif
  9633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9634. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9635. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9636. const std::vector<std::string> &parts,
  9637. std::string *resp = nullptr,
  9638. int port = PORT) {
  9639. auto error = Error::Success;
  9640. auto sock = detail::create_client_socket(
  9641. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9642. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9643. /*write_timeout_sec=*/5, 0, std::string(), error);
  9644. if (sock == INVALID_SOCKET) { return false; }
  9645. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9646. auto ctx = SSL_CTX_new(TLS_client_method());
  9647. auto ssl = SSL_new(ctx);
  9648. auto ssl_se = detail::scope_exit([&] {
  9649. SSL_free(ssl);
  9650. SSL_CTX_free(ctx);
  9651. });
  9652. SSL_set_fd(ssl, static_cast<int>(sock));
  9653. if (SSL_connect(ssl) != 1) { return false; }
  9654. for (size_t i = 0; i < parts.size(); i++) {
  9655. const auto &part = parts[i];
  9656. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9657. static_cast<int>(part.size())) {
  9658. return false;
  9659. }
  9660. if (i + 1 < parts.size()) {
  9661. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9662. }
  9663. }
  9664. char buf[512];
  9665. int n;
  9666. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9667. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9668. }
  9669. return true;
  9670. }
  9671. #endif
  9672. // The request line, then a header value a byte at a time.
  9673. static std::vector<std::string> slow_request_head_parts() {
  9674. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9675. parts.resize(26, "a");
  9676. parts.emplace_back("\r\n\r\n");
  9677. return parts;
  9678. }
  9679. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9680. // within the one-second read timeout. The server gives up a second in, before
  9681. // the head is complete.
  9682. static void
  9683. expect_slow_request_head_dropped(Server &svr,
  9684. const std::function<std::string()> &send) {
  9685. std::atomic<bool> handled(false);
  9686. svr.Get("/", [&](const Request &, Response &res) {
  9687. handled = true;
  9688. res.set_content("ok", "text/plain");
  9689. });
  9690. svr.set_read_timeout(1, 0);
  9691. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9692. auto se = detail::scope_exit([&] {
  9693. svr.stop();
  9694. t.join();
  9695. ASSERT_FALSE(svr.is_running());
  9696. });
  9697. svr.wait_until_ready();
  9698. auto resp = send();
  9699. EXPECT_FALSE(handled);
  9700. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9701. }
  9702. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9703. Server svr;
  9704. expect_slow_request_head_dropped(svr, [] {
  9705. std::string resp;
  9706. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9707. return resp;
  9708. });
  9709. }
  9710. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9711. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9713. ASSERT_TRUE(svr.is_valid());
  9714. expect_slow_request_head_dropped(svr, [] {
  9715. std::string resp;
  9716. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9717. return resp;
  9718. });
  9719. }
  9720. #endif
  9721. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9722. Server svr;
  9723. std::string header_value;
  9724. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9725. header_value = req.get_header_value("foo");
  9726. res.set_content("ok", "text/plain");
  9727. });
  9728. thread t = thread([&] { svr.listen(HOST, PORT); });
  9729. auto se = detail::scope_exit([&] {
  9730. svr.stop();
  9731. t.join();
  9732. ASSERT_FALSE(svr.is_running());
  9733. });
  9734. svr.wait_until_ready();
  9735. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9736. // like characters are not treated the same - use vertical tab and escape.
  9737. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9738. "foo: \t \v bar \x1B\t \r\n"
  9739. "Connection: close\r\n"
  9740. "\r\n";
  9741. std::string res;
  9742. ASSERT_TRUE(send_request(5, req, &res));
  9743. EXPECT_EQ(header_value, "");
  9744. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9745. }
  9746. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9747. Server svr;
  9748. std::string received;
  9749. svr.Get("/order", [&](const Request &req, Response &res) {
  9750. received = entries_to_string(req.headers);
  9751. res.set_content("ok", "text/plain");
  9752. });
  9753. auto port = svr.bind_to_any_port(HOST);
  9754. thread t = thread([&] { svr.listen_after_bind(); });
  9755. auto se = detail::scope_exit([&] {
  9756. svr.stop();
  9757. t.join();
  9758. ASSERT_FALSE(svr.is_running());
  9759. });
  9760. svr.wait_until_ready();
  9761. const std::string req = "GET /order HTTP/1.1\r\n"
  9762. "Host: localhost\r\n"
  9763. "X-First: 1\r\n"
  9764. "X-Dup: a\r\n"
  9765. "X-Second: 2\r\n"
  9766. "X-Dup: b\r\n"
  9767. "Connection: close\r\n"
  9768. "\r\n";
  9769. std::string res;
  9770. ASSERT_TRUE(send_request(5, req, &res, port));
  9771. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9772. EXPECT_EQ(
  9773. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9774. received);
  9775. }
  9776. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9777. Server svr;
  9778. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9779. res.set_header("Set-Cookie", "first=1");
  9780. res.set_header("X-Between", "y");
  9781. res.set_header("Set-Cookie", "second=2");
  9782. res.set_content("ok", "text/plain");
  9783. });
  9784. auto port = svr.bind_to_any_port(HOST);
  9785. thread t = thread([&] { svr.listen_after_bind(); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. t.join();
  9789. ASSERT_FALSE(svr.is_running());
  9790. });
  9791. svr.wait_until_ready();
  9792. Client cli(HOST, port);
  9793. auto res = cli.Get("/cookies");
  9794. ASSERT_TRUE(res);
  9795. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9796. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9797. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9798. }
  9799. // A stream may send a byte at a time with a small extension on each chunk,
  9800. // however long it runs
  9801. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9802. Server svr;
  9803. svr.Post("/count", [](const Request &req, Response &res) {
  9804. res.set_content(std::to_string(req.body.size()), "text/plain");
  9805. });
  9806. auto port = svr.bind_to_any_port(HOST);
  9807. ASSERT_LT(0, port);
  9808. thread t = thread([&] { svr.listen_after_bind(); });
  9809. auto se = detail::scope_exit([&] {
  9810. svr.stop();
  9811. t.join();
  9812. ASSERT_FALSE(svr.is_running());
  9813. });
  9814. svr.wait_until_ready();
  9815. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9816. "\r\nTransfer-Encoding: chunked\r\n"
  9817. "Connection: close\r\n\r\n";
  9818. for (auto i = 0; i < 4096; i++) {
  9819. req += "1;a=b\r\nx\r\n";
  9820. }
  9821. req += "0\r\n\r\n";
  9822. std::string res;
  9823. ASSERT_TRUE(send_request(5, req, &res, port));
  9824. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9825. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9826. }
  9827. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9828. Server svr;
  9829. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9830. auto i = new int(0);
  9831. res.set_header("Trailer", "X-Safe, X-Reflected");
  9832. res.set_chunked_content_provider(
  9833. "text/plain",
  9834. [i](size_t /*offset*/, DataSink &sink) {
  9835. if (*i == 0) {
  9836. sink.os << "body";
  9837. } else {
  9838. Headers trailer;
  9839. // A valid trailer that must survive.
  9840. trailer.emplace("X-Safe", "safe");
  9841. // Attacker-controlled value carrying CR/LF (response splitting).
  9842. trailer.emplace("X-Reflected",
  9843. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9844. // Attacker-controlled name carrying CR/LF.
  9845. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9846. sink.done_with_trailer(trailer);
  9847. }
  9848. (*i)++;
  9849. return true;
  9850. },
  9851. [i](bool /*success*/) { delete i; });
  9852. });
  9853. thread t = thread([&] { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. });
  9859. svr.wait_until_ready();
  9860. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9861. "Host: " + HOST +
  9862. "\r\n"
  9863. "Connection: close\r\n"
  9864. "\r\n";
  9865. std::string res;
  9866. ASSERT_TRUE(send_request(5, req, &res));
  9867. // The injected fields must not appear anywhere in the raw response.
  9868. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9869. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9870. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9871. // Invalid trailers are dropped entirely, matching set_header().
  9872. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9873. // The valid trailer still passes through.
  9874. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9875. }
  9876. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9877. // A custom header writer gets only the fields the default one writes
  9878. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9879. std::string s;
  9880. for (const auto &h : hdrs) {
  9881. s += h.first + ": " + h.second + "\r\n";
  9882. }
  9883. s += "\r\n";
  9884. return strm.write(s.data(), s.size());
  9885. };
  9886. for (auto custom_writer : {false, true}) {
  9887. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9888. Server svr;
  9889. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9890. svr.set_post_routing_handler([](const Request &, Response &res) {
  9891. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9892. });
  9893. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9894. // res.headers is a public field an application can populate directly,
  9895. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9896. // A valid header that must survive.
  9897. res.headers.emplace("X-Safe", "safe");
  9898. // Attacker-controlled value carrying CR/LF (response splitting).
  9899. res.headers.emplace("X-Reflected",
  9900. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9901. // Attacker-controlled name carrying CR/LF.
  9902. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9903. res.set_content("body", "text/plain");
  9904. });
  9905. thread t = thread([&] { svr.listen(HOST, PORT); });
  9906. auto se = detail::scope_exit([&] {
  9907. svr.stop();
  9908. t.join();
  9909. ASSERT_FALSE(svr.is_running());
  9910. });
  9911. svr.wait_until_ready();
  9912. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9913. "Host: " + HOST +
  9914. "\r\n"
  9915. "Connection: close\r\n"
  9916. "\r\n";
  9917. std::string res;
  9918. ASSERT_TRUE(send_request(5, req, &res));
  9919. // The injected fields must not appear anywhere in the raw response.
  9920. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9921. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9922. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9923. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9924. // Invalid headers are dropped entirely, matching set_header().
  9925. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9926. // The valid header still passes through.
  9927. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9928. }
  9929. }
  9930. // Forward declaration: in split builds split.py strips `inline` and moves the
  9931. // definition into httplib.cc, so detail::write_request_line is not visible from
  9932. // the public httplib.h. Re-declaring it here lets the tests link against the
  9933. // symbol in both header-only and split builds.
  9934. namespace httplib {
  9935. namespace detail {
  9936. ssize_t write_request_line(Stream &strm, const std::string &method,
  9937. const std::string &path);
  9938. } // namespace detail
  9939. } // namespace httplib
  9940. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9941. // A well-formed target is written verbatim.
  9942. {
  9943. detail::BufferStream strm;
  9944. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9945. EXPECT_GT(n, 0);
  9946. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9947. }
  9948. // A target carrying CR/LF, SP or other control octets must be rejected
  9949. // before anything reaches the wire, otherwise it splits the request line and
  9950. // injects a header or a whole request.
  9951. const std::string evil_targets[] = {
  9952. "/a\r\nInjected: pwned",
  9953. "/a\rInjected",
  9954. "/a\nInjected",
  9955. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9956. "/a b",
  9957. "/a\tb",
  9958. "/a\x7f",
  9959. };
  9960. for (const auto &evil : evil_targets) {
  9961. detail::BufferStream strm;
  9962. auto n = detail::write_request_line(strm, "GET", evil);
  9963. EXPECT_LT(n, 0);
  9964. EXPECT_TRUE(strm.get_buffer().empty());
  9965. }
  9966. }
  9967. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9968. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9969. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9970. // target reaches write_request. The client must fail cleanly with
  9971. // Error::Write instead of putting a request-line-less, header-injecting
  9972. // request on the wire.
  9973. Server svr;
  9974. svr.Get("/a", [](const Request &, Response &res) {
  9975. res.set_content("ok", "text/plain");
  9976. });
  9977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9978. auto se = detail::scope_exit([&] {
  9979. svr.stop();
  9980. thread.join();
  9981. ASSERT_FALSE(svr.is_running());
  9982. });
  9983. svr.wait_until_ready();
  9984. {
  9985. Client cli(HOST, PORT);
  9986. cli.set_path_encode(false);
  9987. // The request is rejected before anything is written, so the connection
  9988. // stays silent and the subsequent response read would otherwise block for
  9989. // the full default read timeout. Shorten it -- the assertion is on the
  9990. // error, not the timeout.
  9991. cli.set_read_timeout(1, 0);
  9992. auto res = cli.Get("/a\r\nInjected: pwned");
  9993. EXPECT_FALSE(res);
  9994. EXPECT_EQ(Error::Write, res.error());
  9995. }
  9996. }
  9997. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9998. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9999. // including extension methods.
  10000. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10001. for (const auto &method : good_methods) {
  10002. detail::BufferStream strm;
  10003. auto n = detail::write_request_line(strm, method, "/");
  10004. EXPECT_GT(n, 0);
  10005. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10006. }
  10007. // A method carrying CR/LF would split the request line and smuggle a whole
  10008. // request ahead of the real one. A space or an empty method corrupts the
  10009. // request line. All must be rejected before anything reaches the wire.
  10010. const std::string evil_methods[] = {
  10011. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10012. "GET\r\nInjected: pwned",
  10013. "GET\r",
  10014. "GET\n",
  10015. "GE T",
  10016. "",
  10017. };
  10018. for (const auto &evil : evil_methods) {
  10019. detail::BufferStream strm;
  10020. auto n = detail::write_request_line(strm, evil, "/");
  10021. EXPECT_LT(n, 0);
  10022. EXPECT_TRUE(strm.get_buffer().empty());
  10023. }
  10024. }
  10025. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10026. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10027. // through Client::send must fail with Error::Write and no request, neither
  10028. // the smuggled one nor the real one, may reach the server.
  10029. Server svr;
  10030. std::atomic<int> request_count(0);
  10031. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10032. request_count++;
  10033. res.status = StatusCode::OK_200;
  10034. return Server::HandlerResponse::Handled;
  10035. });
  10036. auto port = svr.bind_to_any_port(HOST);
  10037. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10038. auto se = detail::scope_exit([&] {
  10039. svr.stop();
  10040. thread.join();
  10041. ASSERT_FALSE(svr.is_running());
  10042. });
  10043. svr.wait_until_ready();
  10044. {
  10045. Client cli(HOST, port);
  10046. const std::string evil_methods[] = {
  10047. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10048. "GE T",
  10049. "",
  10050. };
  10051. for (const auto &evil : evil_methods) {
  10052. Request req;
  10053. req.method = evil;
  10054. req.path = "/";
  10055. auto res = cli.send(req);
  10056. EXPECT_FALSE(res);
  10057. EXPECT_EQ(Error::Write, res.error());
  10058. }
  10059. auto handle =
  10060. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10061. EXPECT_FALSE(handle.is_valid());
  10062. EXPECT_EQ(Error::Write, handle.error);
  10063. // A valid request on the same client still goes through.
  10064. auto res = cli.Get("/");
  10065. ASSERT_TRUE(res);
  10066. EXPECT_EQ(StatusCode::OK_200, res->status);
  10067. }
  10068. EXPECT_EQ(1, request_count.load());
  10069. }
  10070. // Sends a raw request and verifies that there isn't a crash or exception.
  10071. static void test_raw_request(const std::string &req,
  10072. std::string *out = nullptr) {
  10073. Server svr;
  10074. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10075. res.set_content("ok", "text/plain");
  10076. });
  10077. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10078. res.set_content("ok", "text/plain");
  10079. });
  10080. svr.Get("/header_field_value_check",
  10081. [&](const Request & /*req*/, Response &res) {
  10082. res.set_content("ok", "text/plain");
  10083. });
  10084. svr.CustomRoute("PROPFIND", "/dav",
  10085. [&](const Request & /*req*/, Response &res) {
  10086. res.status = StatusCode::MultiStatus_207;
  10087. });
  10088. // Server read timeout must be longer than the client read timeout for the
  10089. // bug to reproduce, probably to force the server to process a request
  10090. // without a trailing blank line.
  10091. const time_t client_read_timeout_sec = 1;
  10092. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10093. bool listen_thread_ok = false;
  10094. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10095. auto se = detail::scope_exit([&] {
  10096. svr.stop();
  10097. t.join();
  10098. ASSERT_FALSE(svr.is_running());
  10099. EXPECT_TRUE(listen_thread_ok);
  10100. });
  10101. svr.wait_until_ready();
  10102. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10103. }
  10104. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10105. // A certain header line causes an exception if the header property is parsed
  10106. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10107. test_raw_request(
  10108. "GET /hi HTTP/1.1\r\n"
  10109. " : "
  10110. " "
  10111. " ");
  10112. }
  10113. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10114. // A certain header line causes an exception if the header property *name* is
  10115. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10116. // greedy matcher and requires backtracking when there are a lot of ":"
  10117. // characters.
  10118. // This occurs with libc++ but not libstdc++.
  10119. test_raw_request(
  10120. "GET /hi HTTP/1.1\r\n"
  10121. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10122. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10123. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10124. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10125. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10126. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10127. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10128. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10129. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10130. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10131. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10132. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10133. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10134. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10135. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10136. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10137. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10138. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10139. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10140. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10141. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10142. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10143. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10144. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10145. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10146. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10147. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10148. "&&&%%%");
  10149. }
  10150. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10151. // Make sure this doesn't crash the server.
  10152. // In a previous version of the header line regex, the "\r" rendered the line
  10153. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10154. // a new position where the leading white space ended and the field value
  10155. // began.
  10156. // The crash occurs with libc++ but not libstdc++.
  10157. test_raw_request("GET /hi HTTP/1.1\r\n"
  10158. "a:" +
  10159. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10160. "\r\n"
  10161. "\r\n");
  10162. }
  10163. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10164. const char *rejected[] = {
  10165. // RFC 9112 §3: one SP between the parts, and nothing else
  10166. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10167. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10168. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10169. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10170. // A request-target has no fragment
  10171. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10172. // An HTTP/1.1 request needs a Host
  10173. "GET /hi HTTP/1.1\r\n\r\n",
  10174. };
  10175. for (auto request : rejected) {
  10176. std::string out;
  10177. test_raw_request(request, &out);
  10178. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10179. }
  10180. std::string out;
  10181. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10182. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10183. }
  10184. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10185. // RFC 9112 §6.1
  10186. const char *requests[] = {
  10187. "PUT /put_hi HTTP/1.1\r\n"
  10188. "Host: localhost\r\n"
  10189. "Content-Length: 0\r\n"
  10190. "Transfer-Encoding: chunked\r\n"
  10191. "\r\n"
  10192. "0\r\n\r\n",
  10193. "PUT /put_hi HTTP/1.0\r\n"
  10194. "Connection: keep-alive\r\n"
  10195. "Transfer-Encoding: chunked\r\n"
  10196. "\r\n"
  10197. "0\r\n\r\n",
  10198. };
  10199. for (auto request : requests) {
  10200. std::string out;
  10201. test_raw_request(request, &out);
  10202. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10203. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10204. }
  10205. }
  10206. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10207. std::string out;
  10208. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10209. "Content-Type: text/plain\r\n"
  10210. "Transfer-Encoding: chunked\r\n"
  10211. "\r\n"
  10212. "nothex\r\n",
  10213. &out);
  10214. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10215. }
  10216. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10217. std::string out;
  10218. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10219. "Content-Type: text/plain\r\n"
  10220. "Transfer-Encoding: chunked\r\n"
  10221. "\r\n"
  10222. "3\r\n"
  10223. "xyz\r\n"
  10224. "NaN\r\n",
  10225. &out);
  10226. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10227. }
  10228. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10229. std::string out;
  10230. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10231. "Content-Type: text/plain\r\n"
  10232. "Transfer-Encoding: chunked\r\n"
  10233. "\r\n"
  10234. // Length is too large for 64 bits.
  10235. "1ffffffffffffffff\r\n"
  10236. "xyz\r\n",
  10237. &out);
  10238. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10239. }
  10240. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10241. test_raw_request("GET /hi HTTP/1.1\r\n"
  10242. "Content-Type: text/plain\r\n\r");
  10243. }
  10244. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10245. std::string out;
  10246. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10247. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10248. }
  10249. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10250. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10251. std::string out;
  10252. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10253. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10254. }
  10255. }
  10256. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10257. std::string out;
  10258. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10259. "Host: localhost\r\n"
  10260. "Connection: close\r\n\r\n",
  10261. &out);
  10262. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10263. }
  10264. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10265. Server svr;
  10266. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10267. EXPECT_TRUE(!req.remote_addr.empty());
  10268. });
  10269. thread t = thread([&] { svr.listen(HOST, PORT); });
  10270. auto se = detail::scope_exit([&] {
  10271. svr.stop();
  10272. t.join();
  10273. ASSERT_FALSE(svr.is_running());
  10274. });
  10275. svr.wait_until_ready();
  10276. // Send an invalid request line to trigger Bad Request
  10277. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10278. std::string out;
  10279. ASSERT_TRUE(send_request(5, bad_req, &out));
  10280. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10281. }
  10282. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10283. // answered right away rather than blocking on a read that waits for EOF.
  10284. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10285. std::string out;
  10286. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10287. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10288. }
  10289. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10290. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10291. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10292. for (const auto *method : methods) {
  10293. Server svr;
  10294. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10295. EXPECT_FALSE(svr.is_valid()) << method;
  10296. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10297. }
  10298. }
  10299. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10300. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10301. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10302. for (const auto *method : methods) {
  10303. Server svr;
  10304. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10305. EXPECT_FALSE(svr.is_valid()) << method;
  10306. }
  10307. }
  10308. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10309. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10310. "COPY", "MOVE", "LOCK",
  10311. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10312. Server svr;
  10313. for (const auto *method : methods) {
  10314. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10315. }
  10316. EXPECT_TRUE(svr.is_valid());
  10317. }
  10318. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10319. Server svr;
  10320. svr.CustomRoute("POST", "/x",
  10321. [](const Request &, Response &, const ContentReader &) {});
  10322. EXPECT_FALSE(svr.is_valid());
  10323. }
  10324. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10325. Server svr;
  10326. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10327. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10328. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10329. EXPECT_FALSE(svr.is_valid());
  10330. }
  10331. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10332. Server svr;
  10333. auto captured = Error::Success;
  10334. svr.set_error_logger(
  10335. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10336. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10337. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10338. }
  10339. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10340. std::string out;
  10341. std::string request(
  10342. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10343. test_raw_request(request, &out);
  10344. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10345. }
  10346. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10347. std::string out;
  10348. std::string request(
  10349. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10350. test_raw_request(request, &out);
  10351. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10352. }
  10353. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10354. std::string out;
  10355. std::string request(
  10356. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10357. test_raw_request(request, &out);
  10358. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10359. }
  10360. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10361. std::string out;
  10362. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10363. "Host: localhost\r\n"
  10364. "Test: \r\n\r\n",
  10365. &out);
  10366. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10367. }
  10368. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10369. Server svr;
  10370. std::string x_custom;
  10371. std::string cookie;
  10372. std::string xff;
  10373. std::string x_unicode;
  10374. std::string x_iis;
  10375. svr.Get("/check", [&](const Request &req, Response &res) {
  10376. x_custom = req.get_header_value("X-Custom");
  10377. cookie = req.get_header_value("Cookie");
  10378. xff = req.get_header_value("X-Forwarded-For");
  10379. x_unicode = req.get_header_value("X-Unicode");
  10380. x_iis = req.get_header_value("X-IIS");
  10381. res.set_content("ok", "text/plain");
  10382. });
  10383. thread t = thread([&] { svr.listen(HOST, PORT); });
  10384. auto se = detail::scope_exit([&] {
  10385. svr.stop();
  10386. t.join();
  10387. ASSERT_FALSE(svr.is_running());
  10388. });
  10389. svr.wait_until_ready();
  10390. const std::string req = "GET /check HTTP/1.1\r\n"
  10391. "Host: localhost\r\n"
  10392. "X-Custom: a%0D%0AInjected: b\r\n"
  10393. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10394. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10395. "X-Unicode: %E3%81%82\r\n"
  10396. "X-IIS: %u00E9\r\n"
  10397. "Connection: close\r\n"
  10398. "\r\n";
  10399. std::string res;
  10400. ASSERT_TRUE(send_request(5, req, &res));
  10401. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10402. // Every value must be returned verbatim (wire form), with no decoding.
  10403. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10404. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10405. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10406. EXPECT_EQ("%E3%81%82", x_unicode);
  10407. EXPECT_EQ("%u00E9", x_iis);
  10408. }
  10409. // Applications that previously relied on automatic percent-decoding can
  10410. // reproduce the old behavior by explicitly calling decode_path_component()
  10411. // or, for RFC 3986 conformance, decode_uri_component().
  10412. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10413. Server svr;
  10414. std::string decoded;
  10415. svr.Get("/check", [&](const Request &req, Response &res) {
  10416. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10417. res.set_content("ok", "text/plain");
  10418. });
  10419. thread t = thread([&] { svr.listen(HOST, PORT); });
  10420. auto se = detail::scope_exit([&] {
  10421. svr.stop();
  10422. t.join();
  10423. ASSERT_FALSE(svr.is_running());
  10424. });
  10425. svr.wait_until_ready();
  10426. const std::string req = "GET /check HTTP/1.1\r\n"
  10427. "Host: localhost\r\n"
  10428. "X-Custom: hello%20world\r\n"
  10429. "Connection: close\r\n"
  10430. "\r\n";
  10431. std::string res;
  10432. ASSERT_TRUE(send_request(5, req, &res));
  10433. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10434. EXPECT_EQ("hello world", decoded);
  10435. }
  10436. // Regression test for #2033. Browsers send Referer values that include
  10437. // percent-encoded characters such as %0A inside the URL. Decoding the
  10438. // header value would either trip the post-decode CR/LF/NUL guard (the
  10439. // original bug, returning 400) or, after that guard was relaxed, silently
  10440. // store a literal LF — both unacceptable. The wire form must round-trip.
  10441. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10442. Server svr;
  10443. std::string referer;
  10444. svr.Get("/check", [&](const Request &req, Response &res) {
  10445. referer = req.get_header_value("Referer");
  10446. res.set_content("ok", "text/plain");
  10447. });
  10448. thread t = thread([&] { svr.listen(HOST, PORT); });
  10449. auto se = detail::scope_exit([&] {
  10450. svr.stop();
  10451. t.join();
  10452. ASSERT_FALSE(svr.is_running());
  10453. });
  10454. svr.wait_until_ready();
  10455. const std::string req = "GET /check HTTP/1.1\r\n"
  10456. "Host: localhost\r\n"
  10457. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10458. "Connection: close\r\n"
  10459. "\r\n";
  10460. std::string res;
  10461. ASSERT_TRUE(send_request(5, req, &res));
  10462. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10463. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10464. }
  10465. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10466. Server svr;
  10467. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10468. res.set_header("Cache-Control", "no-cache");
  10469. res.set_chunked_content_provider(
  10470. "text/event-stream", [](size_t offset, DataSink &sink) {
  10471. std::string s = "data:";
  10472. s += std::to_string(offset);
  10473. s += "\n\n";
  10474. auto ret = sink.write(s.data(), s.size());
  10475. EXPECT_TRUE(ret);
  10476. std::this_thread::sleep_for(std::chrono::seconds(1));
  10477. return true;
  10478. });
  10479. });
  10480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10481. svr.wait_until_ready();
  10482. Client client(HOST, PORT);
  10483. const Headers headers = {{"Accept", "text/event-stream"}};
  10484. auto get_thread = std::thread([&client, &headers]() {
  10485. auto res = client.Get(
  10486. "/events", headers,
  10487. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10488. });
  10489. auto se = detail::scope_exit([&] {
  10490. svr.stop();
  10491. get_thread.join();
  10492. listen_thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. // Give GET time to get a few messages.
  10496. std::this_thread::sleep_for(std::chrono::seconds(2));
  10497. }
  10498. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10499. httplib::Server svr;
  10500. svr.Post("/hi",
  10501. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10502. res.status = StatusCode::OK_200;
  10503. });
  10504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10505. svr.wait_until_ready();
  10506. Client cli(HOST, PORT);
  10507. auto res = cli.Post("/hi", "data", "text/plain");
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(StatusCode::OK_200, res->status);
  10510. svr.stop();
  10511. thread.join();
  10512. ASSERT_FALSE(svr.is_running());
  10513. res = cli.Post("/hi", "data", "text/plain");
  10514. ASSERT_FALSE(res);
  10515. }
  10516. TEST(ServerStopTest, ListenFailure) {
  10517. Server svr;
  10518. auto t = thread([&]() {
  10519. auto ret = svr.listen("????", PORT);
  10520. EXPECT_FALSE(ret);
  10521. });
  10522. svr.wait_until_ready();
  10523. svr.stop();
  10524. t.join();
  10525. }
  10526. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10527. TEST(ServerStopTest, Decommision) {
  10528. Server svr;
  10529. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10530. for (int i = 0; i < 4; i++) {
  10531. auto is_even = !(i % 2);
  10532. std::thread t{[&] {
  10533. try {
  10534. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10535. if (is_even) {
  10536. throw std::runtime_error("Some thing that happens to go wrong.");
  10537. }
  10538. svr.listen(HOST, PORT);
  10539. } catch (...) { svr.decommission(); }
  10540. }};
  10541. svr.wait_until_ready();
  10542. // Server is up
  10543. {
  10544. Client cli(HOST, PORT);
  10545. auto res = cli.Get("/hi");
  10546. if (is_even) {
  10547. EXPECT_FALSE(res);
  10548. } else {
  10549. EXPECT_TRUE(res);
  10550. EXPECT_EQ("hi...", res->body);
  10551. }
  10552. }
  10553. svr.stop();
  10554. t.join();
  10555. // Server is down...
  10556. {
  10557. Client cli(HOST, PORT);
  10558. auto res = cli.Get("/hi");
  10559. EXPECT_FALSE(res);
  10560. }
  10561. }
  10562. }
  10563. #endif
  10564. // Helper function for string body upload progress tests
  10565. template <typename SetupHandler, typename ClientCall>
  10566. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10567. ClientCall &&client_call,
  10568. const string &body) {
  10569. Server svr;
  10570. setup_handler(svr);
  10571. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10572. auto se = detail::scope_exit([&] {
  10573. svr.stop();
  10574. t.join();
  10575. });
  10576. svr.wait_until_ready();
  10577. Client cli(HOST, PORT);
  10578. vector<uint64_t> progress_values;
  10579. bool progress_called = false;
  10580. auto res =
  10581. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10582. progress_values.push_back(current);
  10583. progress_called = true;
  10584. return true;
  10585. });
  10586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10587. EXPECT_EQ(200, res->status);
  10588. EXPECT_TRUE(progress_called);
  10589. }
  10590. TEST(UploadProgressTest, PostStringBodyBasic) {
  10591. TestStringBodyUploadProgress(
  10592. [](Server &svr) {
  10593. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10594. res.set_content("received", "text/plain");
  10595. });
  10596. },
  10597. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10598. return cli.Post("/test", body, "text/plain", progress_callback);
  10599. },
  10600. "test data for upload progress");
  10601. }
  10602. TEST(UploadProgressTest, PutStringBodyBasic) {
  10603. TestStringBodyUploadProgress(
  10604. [](Server &svr) {
  10605. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10606. res.set_content("put received", "text/plain");
  10607. });
  10608. },
  10609. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10610. return cli.Put("/test", body, "text/plain", progress_callback);
  10611. },
  10612. "put test data for upload progress");
  10613. }
  10614. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10615. TestStringBodyUploadProgress(
  10616. [](Server &svr) {
  10617. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10618. res.set_content("patch received", "text/plain");
  10619. });
  10620. },
  10621. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10622. return cli.Patch("/test", body, "text/plain", progress_callback);
  10623. },
  10624. "patch test data for upload progress");
  10625. }
  10626. // Helper function for content provider upload progress tests
  10627. template <typename SetupHandler, typename ClientCall>
  10628. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10629. ClientCall &&client_call) {
  10630. Server svr;
  10631. setup_handler(svr);
  10632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10633. auto se = detail::scope_exit([&] {
  10634. svr.stop();
  10635. t.join();
  10636. });
  10637. svr.wait_until_ready();
  10638. Client cli(HOST, PORT);
  10639. vector<uint64_t> progress_values;
  10640. auto res =
  10641. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10642. progress_values.push_back(current);
  10643. return true;
  10644. });
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. EXPECT_EQ(200, res->status);
  10647. EXPECT_FALSE(progress_values.empty());
  10648. }
  10649. TEST(UploadProgressTest, PostContentProviderProgress) {
  10650. TestContentProviderUploadProgress(
  10651. [](Server &svr) {
  10652. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10653. res.set_content("provider received", "text/plain");
  10654. });
  10655. },
  10656. [](Client &cli, UploadProgress progress_callback) {
  10657. return cli.Post(
  10658. "/test", 9,
  10659. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10660. sink.os << "test data";
  10661. return true;
  10662. },
  10663. "text/plain", progress_callback);
  10664. });
  10665. }
  10666. // Helper function for multipart upload progress tests
  10667. template <typename SetupHandler, typename ClientCall>
  10668. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10669. ClientCall &&client_call,
  10670. const string &endpoint) {
  10671. Server svr;
  10672. setup_handler(svr);
  10673. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10674. auto se = detail::scope_exit([&] {
  10675. svr.stop();
  10676. t.join();
  10677. });
  10678. svr.wait_until_ready();
  10679. Client cli(HOST, PORT);
  10680. vector<uint64_t> progress_values;
  10681. UploadFormDataItems items = {
  10682. {"field1", "value1", "", ""},
  10683. {"field2", "longer value for progress tracking test", "", ""},
  10684. {"file1", "file content data for upload progress", "test.txt",
  10685. "text/plain"}};
  10686. auto res = client_call(cli, endpoint, items,
  10687. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10688. progress_values.push_back(current);
  10689. return true;
  10690. });
  10691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10692. EXPECT_EQ(200, res->status);
  10693. EXPECT_FALSE(progress_values.empty());
  10694. }
  10695. TEST(UploadProgressTest, PostMultipartProgress) {
  10696. TestMultipartUploadProgress(
  10697. [](Server &svr) {
  10698. svr.Post("/multipart", [](const Request &req, Response &res) {
  10699. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10700. res.set_content("multipart received", "text/plain");
  10701. });
  10702. },
  10703. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10704. UploadProgress progress_callback) {
  10705. return cli.Post(endpoint, items, progress_callback);
  10706. },
  10707. "/multipart");
  10708. }
  10709. // Helper function for basic download progress tests
  10710. template <typename SetupHandler, typename ClientCall>
  10711. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10712. ClientCall &&client_call, const string &endpoint,
  10713. size_t expected_content_size) {
  10714. Server svr;
  10715. setup_handler(svr);
  10716. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10717. auto se = detail::scope_exit([&] {
  10718. svr.stop();
  10719. t.join();
  10720. });
  10721. svr.wait_until_ready();
  10722. Client cli(HOST, PORT);
  10723. vector<uint64_t> progress_values;
  10724. auto res = client_call(cli, endpoint,
  10725. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10726. progress_values.push_back(current);
  10727. return true;
  10728. });
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. EXPECT_EQ(200, res->status);
  10731. EXPECT_FALSE(progress_values.empty());
  10732. EXPECT_EQ(expected_content_size, res->body.size());
  10733. }
  10734. TEST(DownloadProgressTest, GetBasic) {
  10735. TestBasicDownloadProgress(
  10736. [](Server &svr) {
  10737. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10738. string content(1000, 'D');
  10739. res.set_content(content, "text/plain");
  10740. });
  10741. },
  10742. [](Client &cli, const string &endpoint,
  10743. DownloadProgress progress_callback) {
  10744. return cli.Get(endpoint, progress_callback);
  10745. },
  10746. "/download", 1000u);
  10747. }
  10748. // Helper function for content receiver download progress tests
  10749. template <typename SetupHandler, typename ClientCall>
  10750. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10751. ClientCall &&client_call,
  10752. const string &endpoint,
  10753. size_t expected_content_size) {
  10754. Server svr;
  10755. setup_handler(svr);
  10756. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10757. auto se = detail::scope_exit([&] {
  10758. svr.stop();
  10759. t.join();
  10760. });
  10761. svr.wait_until_ready();
  10762. Client cli(HOST, PORT);
  10763. vector<uint64_t> progress_values;
  10764. string received_body;
  10765. auto res = client_call(
  10766. cli, endpoint,
  10767. [&](const char *data, size_t data_length) -> bool {
  10768. received_body.append(data, data_length);
  10769. return true;
  10770. },
  10771. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10772. progress_values.push_back(current);
  10773. return true;
  10774. });
  10775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10776. EXPECT_EQ(200, res->status);
  10777. EXPECT_FALSE(progress_values.empty());
  10778. EXPECT_EQ(expected_content_size, received_body.size());
  10779. EXPECT_TRUE(res->body.empty());
  10780. }
  10781. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10782. TestContentReceiverDownloadProgress(
  10783. [](Server &svr) {
  10784. svr.Get("/download-receiver",
  10785. [](const Request & /*req*/, Response &res) {
  10786. string content(2000, 'R');
  10787. res.set_content(content, "text/plain");
  10788. });
  10789. },
  10790. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10791. DownloadProgress progress_callback) {
  10792. return cli.Get(endpoint, content_receiver, progress_callback);
  10793. },
  10794. "/download-receiver", 2000u);
  10795. }
  10796. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10797. // A provider reaching a pass with nothing to hand over - an empty buffer
  10798. // popped off a queue, say - must not be taken to mean the body is finished.
  10799. // It used to end the loop with the terminating chunk unwritten while the
  10800. // server still considered the response complete, so the peer waited for an
  10801. // end that never arrived.
  10802. Server svr;
  10803. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10804. auto step = std::make_shared<int>(0);
  10805. res.set_chunked_content_provider("text/plain",
  10806. [step](size_t /*offset*/, DataSink &sink) {
  10807. switch ((*step)++) {
  10808. case 0: sink.write("", 0); break;
  10809. case 1: sink.write("hello", 5); break;
  10810. default: sink.done(); break;
  10811. }
  10812. return true;
  10813. });
  10814. });
  10815. auto port = svr.bind_to_any_port(HOST);
  10816. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10817. auto listen_se = detail::scope_exit([&] {
  10818. svr.stop();
  10819. listen_thread.join();
  10820. ASSERT_FALSE(svr.is_running());
  10821. });
  10822. svr.wait_until_ready();
  10823. Client cli(HOST, port);
  10824. // Without the fix the body is never terminated, so bound the wait rather
  10825. // than letting the test hang on the default read timeout.
  10826. cli.set_read_timeout(5, 0);
  10827. auto res = cli.Get("/stream");
  10828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10829. EXPECT_EQ(StatusCode::OK_200, res->status);
  10830. EXPECT_EQ("hello", res->body);
  10831. }
  10832. TEST(StreamingTest, NoContentLengthStreaming) {
  10833. Server svr;
  10834. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10835. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10836. if (offset < 6) {
  10837. sink.os << (offset < 3 ? "a" : "b");
  10838. } else {
  10839. sink.done();
  10840. }
  10841. return true;
  10842. });
  10843. });
  10844. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10845. auto listen_se = detail::scope_exit([&] {
  10846. svr.stop();
  10847. listen_thread.join();
  10848. ASSERT_FALSE(svr.is_running());
  10849. });
  10850. svr.wait_until_ready();
  10851. Client client(HOST, PORT);
  10852. auto get_thread = std::thread([&client]() {
  10853. std::string s;
  10854. auto res =
  10855. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10856. s += std::string(data, len);
  10857. return true;
  10858. });
  10859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10860. EXPECT_EQ(StatusCode::OK_200, res->status);
  10861. EXPECT_EQ("aaabbb", s);
  10862. });
  10863. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10864. // Give GET time to get a few messages.
  10865. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10866. }
  10867. TEST(MountTest, Unmount) {
  10868. Server svr;
  10869. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10870. auto se = detail::scope_exit([&] {
  10871. svr.stop();
  10872. listen_thread.join();
  10873. ASSERT_FALSE(svr.is_running());
  10874. });
  10875. svr.wait_until_ready();
  10876. Client cli("localhost", PORT);
  10877. svr.set_mount_point("/mount2", "./www2");
  10878. auto res = cli.Get("/");
  10879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10881. res = cli.Get("/mount2/dir/test.html");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. EXPECT_EQ(StatusCode::OK_200, res->status);
  10884. svr.set_mount_point("/", "./www");
  10885. res = cli.Get("/dir/");
  10886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10887. EXPECT_EQ(StatusCode::OK_200, res->status);
  10888. svr.remove_mount_point("/");
  10889. res = cli.Get("/dir/");
  10890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10892. svr.remove_mount_point("/mount2");
  10893. res = cli.Get("/mount2/dir/test.html");
  10894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10896. }
  10897. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10898. Server svr;
  10899. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10900. svr.Get("/api/hello", [](const Request &, Response &res) {
  10901. res.set_content("api", "text/plain");
  10902. });
  10903. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10904. auto se = detail::scope_exit([&] {
  10905. svr.stop();
  10906. listen_thread.join();
  10907. ASSERT_FALSE(svr.is_running());
  10908. });
  10909. svr.wait_until_ready();
  10910. Client cli(HOST, PORT);
  10911. auto res = cli.Get("/dir/test.html");
  10912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10913. EXPECT_EQ(StatusCode::OK_200, res->status);
  10914. res = cli.Get("/api/hello");
  10915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10916. EXPECT_EQ(StatusCode::OK_200, res->status);
  10917. EXPECT_EQ("api", res->body);
  10918. }
  10919. TEST(MountTest, PathSegmentBoundary) {
  10920. Server svr;
  10921. svr.set_mount_point("/mount2", "./www2");
  10922. svr.set_mount_point("/", "./www");
  10923. auto port = svr.bind_to_any_port(HOST);
  10924. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10925. auto se = detail::scope_exit([&] {
  10926. svr.stop();
  10927. listen_thread.join();
  10928. ASSERT_FALSE(svr.is_running());
  10929. });
  10930. svr.wait_until_ready();
  10931. Client cli(HOST, port);
  10932. auto res = cli.Get("/mount2/dir/test.html");
  10933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10934. EXPECT_EQ(StatusCode::OK_200, res->status);
  10935. // "/mount2" must not match part-way through a path segment.
  10936. res = cli.Get("/mount2dir/test.html");
  10937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10938. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10939. // A mount point ending in '/' keeps matching every path below it.
  10940. res = cli.Get("/dir/test.html");
  10941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10942. EXPECT_EQ(StatusCode::OK_200, res->status);
  10943. }
  10944. TEST(MountTest, Redicect) {
  10945. Server svr;
  10946. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10947. auto se = detail::scope_exit([&] {
  10948. svr.stop();
  10949. listen_thread.join();
  10950. ASSERT_FALSE(svr.is_running());
  10951. });
  10952. svr.set_mount_point("/", "./www");
  10953. svr.wait_until_ready();
  10954. Client cli("localhost", PORT);
  10955. auto res = cli.Get("/dir/");
  10956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10957. EXPECT_EQ(StatusCode::OK_200, res->status);
  10958. res = cli.Get("/dir");
  10959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10960. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10961. res = cli.Get("/file");
  10962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10963. EXPECT_EQ(StatusCode::OK_200, res->status);
  10964. res = cli.Get("/file/");
  10965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10966. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10967. cli.set_follow_location(true);
  10968. res = cli.Get("/dir");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. EXPECT_EQ(StatusCode::OK_200, res->status);
  10971. }
  10972. TEST(MountTest, MultibytesPathName) {
  10973. Server svr;
  10974. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10975. auto se = detail::scope_exit([&] {
  10976. svr.stop();
  10977. listen_thread.join();
  10978. ASSERT_FALSE(svr.is_running());
  10979. });
  10980. svr.set_mount_point("/", "./www");
  10981. svr.wait_until_ready();
  10982. Client cli("localhost", PORT);
  10983. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10985. EXPECT_EQ(StatusCode::OK_200, res->status);
  10986. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10987. }
  10988. // A mount point serves no path with an empty segment or one ending in '.' or
  10989. // a space, so a guard in the pre-routing handler sees the path of every file
  10990. // that is served
  10991. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10992. Server svr;
  10993. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10994. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10995. if (req.path == "/dir/test.html") {
  10996. res.status = StatusCode::Unauthorized_401;
  10997. return Server::HandlerResponse::Handled;
  10998. }
  10999. return Server::HandlerResponse::Unhandled;
  11000. });
  11001. auto port = svr.bind_to_any_port(HOST);
  11002. ASSERT_LT(0, port);
  11003. thread t = thread([&] { svr.listen_after_bind(); });
  11004. auto se = detail::scope_exit([&] {
  11005. svr.stop();
  11006. t.join();
  11007. ASSERT_FALSE(svr.is_running());
  11008. });
  11009. svr.wait_until_ready();
  11010. Client cli(HOST, port);
  11011. for (auto path :
  11012. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11013. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11014. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11015. "/dir/test.html%3A%3A$DATA"}) {
  11016. SCOPED_TRACE(path);
  11017. auto res = cli.Get(path);
  11018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11020. }
  11021. }
  11022. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11023. Server svr;
  11024. svr.set_mount_point("/", "./www");
  11025. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11026. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11027. auto port = svr.bind_to_any_port(HOST);
  11028. ASSERT_GT(port, 0);
  11029. thread t = thread([&] { svr.listen_after_bind(); });
  11030. auto se = detail::scope_exit([&] {
  11031. svr.stop();
  11032. t.join();
  11033. ASSERT_FALSE(svr.is_running());
  11034. });
  11035. svr.wait_until_ready();
  11036. Client cli(HOST, port);
  11037. auto res = cli.Get("/dir/test.abcde");
  11038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11039. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11040. res = cli.Get("/dir/test.html");
  11041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11042. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11043. }
  11044. #ifdef _WIN32
  11045. // Issue #2435: mmap::open() must succeed even when another handle holds
  11046. // the file open for writing (e.g. an active log file).
  11047. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11048. const char *path = "mmap_concurrent_writer_test.txt";
  11049. const char *content = "hello";
  11050. {
  11051. std::ofstream f(path, std::ios::binary);
  11052. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11053. }
  11054. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11055. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11056. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11057. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11058. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11059. detail::mmap m(path);
  11060. ASSERT_TRUE(m.is_open());
  11061. EXPECT_EQ(strlen(content), m.size());
  11062. char buf[8];
  11063. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11064. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11065. }
  11066. #endif
  11067. #ifndef _WIN32
  11068. // A directory or a device has no size to serve.
  11069. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11070. const char *path = "./mmap_not_regular_test_dir";
  11071. ASSERT_EQ(0, ::mkdir(path, 0755));
  11072. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11073. for (auto p : {path, "/dev/null"}) {
  11074. detail::mmap m(p);
  11075. EXPECT_FALSE(m.is_open()) << p;
  11076. EXPECT_EQ(0U, m.size()) << p;
  11077. }
  11078. Server svr;
  11079. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11080. res.set_file_content("/dev/null");
  11081. });
  11082. auto port = svr.bind_to_any_port(HOST);
  11083. thread t = thread([&] { svr.listen_after_bind(); });
  11084. auto se = detail::scope_exit([&] {
  11085. svr.stop();
  11086. t.join();
  11087. });
  11088. svr.wait_until_ready();
  11089. auto res = Client(HOST, port).Get("/null");
  11090. ASSERT_TRUE(res);
  11091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11092. }
  11093. #endif
  11094. #ifdef __linux__
  11095. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11096. TEST(MmapTest, FileIsNotMapped) {
  11097. const char *path = "mmap_not_mapped_test.txt";
  11098. {
  11099. std::ofstream f(path, std::ios::binary);
  11100. f << "hello";
  11101. }
  11102. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11103. detail::mmap m(path);
  11104. ASSERT_TRUE(m.is_open());
  11105. std::ifstream maps("/proc/self/maps");
  11106. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11107. std::istreambuf_iterator<char>());
  11108. EXPECT_EQ(std::string::npos, mappings.find(path));
  11109. }
  11110. #endif
  11111. TEST(KeepAliveTest, ReadTimeout) {
  11112. Server svr;
  11113. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11114. std::this_thread::sleep_for(std::chrono::seconds(2));
  11115. res.set_content("a", "text/plain");
  11116. });
  11117. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11118. res.set_content("b", "text/plain");
  11119. });
  11120. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11121. auto se = detail::scope_exit([&] {
  11122. svr.stop();
  11123. listen_thread.join();
  11124. ASSERT_FALSE(svr.is_running());
  11125. });
  11126. svr.wait_until_ready();
  11127. Client cli("localhost", PORT);
  11128. cli.set_keep_alive(true);
  11129. cli.set_read_timeout(std::chrono::seconds(1));
  11130. auto resa = cli.Get("/a");
  11131. ASSERT_FALSE(resa);
  11132. EXPECT_EQ(Error::Read, resa.error());
  11133. auto resb = cli.Get("/b");
  11134. ASSERT_TRUE(resb);
  11135. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11136. EXPECT_EQ("b", resb->body);
  11137. }
  11138. TEST(KeepAliveTest, MaxCount) {
  11139. size_t keep_alive_max_count = 3;
  11140. Server svr;
  11141. svr.set_keep_alive_max_count(keep_alive_max_count);
  11142. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11143. res.set_content("Hello World!", "text/plain");
  11144. });
  11145. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. listen_thread.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. Client cli(HOST, PORT);
  11153. cli.set_keep_alive(true);
  11154. for (size_t i = 0; i < 5; i++) {
  11155. auto result = cli.Get("/hi");
  11156. ASSERT_TRUE(result);
  11157. EXPECT_EQ(StatusCode::OK_200, result->status);
  11158. if (i == keep_alive_max_count - 1) {
  11159. EXPECT_EQ("close", result->get_header_value("Connection"));
  11160. } else {
  11161. EXPECT_FALSE(result->has_header("Connection"));
  11162. }
  11163. }
  11164. }
  11165. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11166. // can pull the next one into the server's buffer. The server must serve it
  11167. // without waiting for the socket to become readable again. The keep-alive
  11168. // timeout outlasts the client's read timeout, so a request left waiting for it
  11169. // shows up as a missing response.
  11170. static void serve_pipelining_routes(Server &svr,
  11171. const std::function<void(int)> &client) {
  11172. svr.set_keep_alive_timeout(5);
  11173. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11174. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11175. });
  11176. svr.Post("/echo", [](const Request &req, Response &res) {
  11177. res.set_content("echo " + req.body, "text/plain");
  11178. });
  11179. auto port = svr.bind_to_any_port(HOST);
  11180. thread t = thread([&] { svr.listen_after_bind(); });
  11181. auto se = detail::scope_exit([&] {
  11182. svr.stop();
  11183. t.join();
  11184. });
  11185. svr.wait_until_ready();
  11186. client(port);
  11187. }
  11188. static std::string
  11189. send_pipelined_requests(const std::vector<std::string> &parts) {
  11190. Server svr;
  11191. std::string res;
  11192. serve_pipelining_routes(svr, [&](int port) {
  11193. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11194. });
  11195. return res;
  11196. }
  11197. static void expect_in_order(const std::string &res,
  11198. const std::vector<std::string> &bodies) {
  11199. size_t pos = 0;
  11200. for (const auto &body : bodies) {
  11201. pos = res.find(body, pos);
  11202. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11203. pos += body.size();
  11204. }
  11205. }
  11206. TEST(KeepAliveTest, PipelinedRequests) {
  11207. auto res = send_pipelined_requests(
  11208. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11209. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11210. "Content-Length: 4\r\n\r\nbody"
  11211. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11212. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11213. }
  11214. // The second request starts in the server's buffer and ends on the socket.
  11215. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11216. auto res =
  11217. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11218. "GET /hi/2 HTTP/1.1\r\nHo",
  11219. "st: localhost\r\nConnection: close\r\n\r\n"});
  11220. expect_in_order(res, {"hi 1", "hi 2"});
  11221. }
  11222. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11223. // CRLF after a body does not turn into a 400 for the next request.
  11224. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11225. auto res = send_pipelined_requests(
  11226. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11227. "Content-Length: 4\r\n\r\nbody\r\n"
  11228. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11229. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11230. expect_in_order(res, {"echo body", "hi 2"});
  11231. }
  11232. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11233. // must not be served as the next request.
  11234. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11235. auto res = send_pipelined_requests(
  11236. {"INVALID REQUEST LINE\r\n\r\n"
  11237. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11238. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11239. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11240. }
  11241. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11242. // Over TLS, the next request is held by the TLS library as already decrypted
  11243. // data rather than on the socket.
  11244. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11246. std::string res;
  11247. serve_pipelining_routes(svr, [&](int port) {
  11248. // One part, so all three requests arrive in one TLS record
  11249. EXPECT_TRUE(send_ssl_request_in_parts(
  11250. 2,
  11251. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11252. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11253. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11254. &res, port));
  11255. });
  11256. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11257. }
  11258. #endif
  11259. TEST(KeepAliveTest, Issue1041) {
  11260. Server svr;
  11261. svr.set_keep_alive_timeout(3);
  11262. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11263. res.set_content("Hello World!", "text/plain");
  11264. });
  11265. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11266. auto se = detail::scope_exit([&] {
  11267. svr.stop();
  11268. listen_thread.join();
  11269. ASSERT_FALSE(svr.is_running());
  11270. });
  11271. svr.wait_until_ready();
  11272. Client cli(HOST, PORT);
  11273. cli.set_keep_alive(true);
  11274. auto result = cli.Get("/hi");
  11275. ASSERT_TRUE(result);
  11276. EXPECT_EQ(StatusCode::OK_200, result->status);
  11277. std::this_thread::sleep_for(std::chrono::seconds(5));
  11278. result = cli.Get("/hi");
  11279. ASSERT_TRUE(result);
  11280. EXPECT_EQ(StatusCode::OK_200, result->status);
  11281. }
  11282. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11283. Server svr;
  11284. svr.set_keep_alive_max_count(0);
  11285. std::set<int> remote_ports;
  11286. svr.Get("/hi", [&](const Request &req, Response &res) {
  11287. remote_ports.insert(req.remote_port);
  11288. res.set_content("hi", "text/plain");
  11289. });
  11290. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11291. auto se = detail::scope_exit([&] {
  11292. svr.stop();
  11293. listen_thread.join();
  11294. ASSERT_FALSE(svr.is_running());
  11295. });
  11296. svr.wait_until_ready();
  11297. Client cli(HOST, PORT);
  11298. cli.set_keep_alive(true);
  11299. for (int i = 0; i < 3; i++) {
  11300. auto res = cli.Get("/hi");
  11301. ASSERT_TRUE(res);
  11302. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11303. }
  11304. // All three over one connection
  11305. EXPECT_EQ(1u, remote_ports.size());
  11306. }
  11307. TEST(KeepAliveTest, Issue1959) {
  11308. Server svr;
  11309. svr.set_keep_alive_timeout(5);
  11310. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11311. res.set_content("a", "text/plain");
  11312. });
  11313. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11314. auto se = detail::scope_exit([&] {
  11315. if (!svr.is_running()) return;
  11316. svr.stop();
  11317. listen_thread.join();
  11318. ASSERT_FALSE(svr.is_running());
  11319. });
  11320. svr.wait_until_ready();
  11321. Client cli("localhost", PORT);
  11322. cli.set_keep_alive(true);
  11323. using namespace std::chrono;
  11324. auto start = steady_clock::now();
  11325. cli.Get("/a");
  11326. svr.stop();
  11327. listen_thread.join();
  11328. auto end = steady_clock::now();
  11329. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11330. EXPECT_LT(elapsed, 5000);
  11331. }
  11332. #ifdef CPPHTTPLIB_SSL_ENABLED
  11333. TEST(KeepAliveTest, SSLClientReconnection) {
  11334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11335. ASSERT_TRUE(svr.is_valid());
  11336. svr.set_keep_alive_timeout(1);
  11337. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11338. res.set_content("Hello World!", "text/plain");
  11339. });
  11340. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. listen_thread.join();
  11344. ASSERT_FALSE(svr.is_running());
  11345. });
  11346. svr.wait_until_ready();
  11347. SSLClient cli(HOST, PORT);
  11348. cli.enable_server_certificate_verification(false);
  11349. cli.set_keep_alive(true);
  11350. auto result = cli.Get("/hi");
  11351. ASSERT_TRUE(result);
  11352. EXPECT_EQ(StatusCode::OK_200, result->status);
  11353. result = cli.Get("/hi");
  11354. ASSERT_TRUE(result);
  11355. EXPECT_EQ(StatusCode::OK_200, result->status);
  11356. std::this_thread::sleep_for(std::chrono::seconds(2));
  11357. // Recoonect
  11358. result = cli.Get("/hi");
  11359. ASSERT_TRUE(result);
  11360. EXPECT_EQ(StatusCode::OK_200, result->status);
  11361. result = cli.Get("/hi");
  11362. ASSERT_TRUE(result);
  11363. EXPECT_EQ(StatusCode::OK_200, result->status);
  11364. }
  11365. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11367. ASSERT_TRUE(svr.is_valid());
  11368. svr.set_keep_alive_timeout(1);
  11369. std::string content = "reconnect";
  11370. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11371. res.set_content("Hello World!", "text/plain");
  11372. });
  11373. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11374. auto se = detail::scope_exit([&] {
  11375. svr.stop();
  11376. listen_thread.join();
  11377. ASSERT_FALSE(svr.is_running());
  11378. });
  11379. svr.wait_until_ready();
  11380. SSLClient cli(HOST, PORT);
  11381. cli.enable_server_certificate_verification(false);
  11382. cli.set_keep_alive(true);
  11383. auto result = cli.Post(
  11384. "/hi", content.size(),
  11385. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11386. sink.write(content.c_str(), content.size());
  11387. return true;
  11388. },
  11389. "text/plain");
  11390. ASSERT_TRUE(result);
  11391. EXPECT_EQ(200, result->status);
  11392. std::this_thread::sleep_for(std::chrono::seconds(2));
  11393. // Recoonect
  11394. result = cli.Post(
  11395. "/hi", content.size(),
  11396. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11397. sink.write(content.c_str(), content.size());
  11398. return true;
  11399. },
  11400. "text/plain");
  11401. ASSERT_TRUE(result);
  11402. EXPECT_EQ(200, result->status);
  11403. result = cli.Post(
  11404. "/hi", content.size(),
  11405. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11406. sink.write(content.c_str(), content.size());
  11407. return true;
  11408. },
  11409. "text/plain");
  11410. ASSERT_TRUE(result);
  11411. EXPECT_EQ(200, result->status);
  11412. }
  11413. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11414. using namespace httplib::tls;
  11415. {
  11416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11417. ASSERT_TRUE(svr.is_valid());
  11418. svr.Get("/sni", [&](const Request &req, Response &res) {
  11419. std::string expected = req.sni();
  11420. EXPECT_EQ(expected, req.get_param_value("expected"));
  11421. res.set_content("ok", "text/plain");
  11422. });
  11423. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. listen_thread.join();
  11427. ASSERT_FALSE(svr.is_running());
  11428. });
  11429. svr.wait_until_ready();
  11430. {
  11431. SSLClient cli("localhost", PORT);
  11432. cli.enable_server_certificate_verification(false);
  11433. auto res = cli.Get("/sni?expected=localhost");
  11434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11435. }
  11436. {
  11437. SSLClient cli("::1", PORT);
  11438. cli.enable_server_certificate_verification(false);
  11439. auto res = cli.Get("/sni?expected=");
  11440. // NOTE: This may fail if the server is listening on IPv4 only
  11441. // (e.g., when localhost resolves to 127.0.0.1 only)
  11442. if (res) {
  11443. EXPECT_EQ(StatusCode::OK_200, res->status);
  11444. } else {
  11445. EXPECT_EQ(Error::Connection, res.error());
  11446. }
  11447. }
  11448. }
  11449. }
  11450. // The SNI of a failed handshake does not reach the next connection that the
  11451. // same worker thread serves
  11452. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11454. ASSERT_TRUE(svr.is_valid());
  11455. svr.new_task_queue = [] { return new ThreadPool(1); };
  11456. svr.Get("/sni", [](const Request &req, Response &res) {
  11457. res.set_content(req.sni(), "text/plain");
  11458. });
  11459. auto port = svr.bind_to_any_port("127.0.0.1");
  11460. ASSERT_LT(0, port);
  11461. thread t = thread([&] { svr.listen_after_bind(); });
  11462. auto se = detail::scope_exit([&] {
  11463. svr.stop();
  11464. t.join();
  11465. ASSERT_FALSE(svr.is_running());
  11466. });
  11467. svr.wait_until_ready();
  11468. {
  11469. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11470. SSLClient cli("localhost", port);
  11471. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11472. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11473. auto res = cli.Get("/sni");
  11474. ASSERT_FALSE(res);
  11475. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11476. }
  11477. // An IP host sends no SNI (RFC 6066)
  11478. SSLClient cli("127.0.0.1", port);
  11479. cli.enable_server_certificate_verification(false);
  11480. auto res = cli.Get("/sni");
  11481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11482. EXPECT_EQ("", res->body);
  11483. }
  11484. #endif
  11485. TEST(ClientProblemDetectionTest, ContentProvider) {
  11486. Server svr;
  11487. size_t content_length = 1024 * 1024;
  11488. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11489. res.set_content_provider(
  11490. content_length, "text/plain",
  11491. [&](size_t offset, size_t length, DataSink &sink) {
  11492. auto out_len = std::min(length, static_cast<size_t>(1024));
  11493. std::string out(out_len, '@');
  11494. sink.write(out.data(), out_len);
  11495. return offset < 4096;
  11496. },
  11497. [](bool success) { ASSERT_FALSE(success); });
  11498. });
  11499. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11500. res.set_content_provider(
  11501. 0, "text/plain",
  11502. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11503. EXPECT_TRUE(false);
  11504. return true;
  11505. },
  11506. [](bool success) { ASSERT_FALSE(success); });
  11507. });
  11508. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. listen_thread.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. Client cli("localhost", PORT);
  11516. {
  11517. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11518. size_t /*data_length*/) { return false; });
  11519. ASSERT_FALSE(res);
  11520. }
  11521. {
  11522. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11523. size_t /*data_length*/) { return false; });
  11524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11525. }
  11526. }
  11527. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11528. // A provider that reports success without writing anything and without
  11529. // calling done() used to be handed the same offset and length again on every
  11530. // pass, so it spun for as long as the peer stayed connected.
  11531. Server svr;
  11532. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11533. res.set_content("ok", "text/plain");
  11534. });
  11535. auto port = svr.bind_to_any_port(HOST);
  11536. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11537. auto se = detail::scope_exit([&] {
  11538. svr.stop();
  11539. listen_thread.join();
  11540. ASSERT_FALSE(svr.is_running());
  11541. });
  11542. svr.wait_until_ready();
  11543. std::atomic<int> call_count{0};
  11544. Client cli(HOST, port);
  11545. auto res = cli.Post(
  11546. "/", 1024,
  11547. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11548. // Give up after enough passes to show the spin, so that losing the
  11549. // check below fails this test instead of hanging it.
  11550. return ++call_count < 100;
  11551. },
  11552. "text/plain");
  11553. ASSERT_FALSE(res);
  11554. EXPECT_EQ(Error::Write, res.error());
  11555. EXPECT_EQ(1, call_count.load());
  11556. }
  11557. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11558. // A writer only has to assign `write`. The other three used to be left as
  11559. // empty std::functions, so a provider calling one threw
  11560. // std::bad_function_call out of the thread running it and took the whole
  11561. // process down.
  11562. DataSink sink;
  11563. std::string written;
  11564. sink.write = [&](const char *data, size_t data_len) {
  11565. written.append(data, data_len);
  11566. return true;
  11567. };
  11568. EXPECT_TRUE(sink.is_writable());
  11569. sink.done();
  11570. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11571. EXPECT_TRUE(written.empty());
  11572. }
  11573. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11574. // A sink that cannot carry trailers still has to finish.
  11575. DataSink sink;
  11576. auto done_count = 0;
  11577. sink.done = [&]() { done_count++; };
  11578. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11579. EXPECT_EQ(1, done_count);
  11580. }
  11581. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11582. Server svr;
  11583. const std::string body(4096, 'x');
  11584. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11585. res.set_content_provider(body.size(), "text/plain",
  11586. [&](size_t offset, size_t length, DataSink &sink) {
  11587. sink.write(body.data() + offset, length);
  11588. sink.done();
  11589. return true;
  11590. });
  11591. });
  11592. auto port = svr.bind_to_any_port(HOST);
  11593. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11594. auto se = detail::scope_exit([&] {
  11595. svr.stop();
  11596. listen_thread.join();
  11597. ASSERT_FALSE(svr.is_running());
  11598. });
  11599. svr.wait_until_ready();
  11600. Client cli(HOST, port);
  11601. auto res = cli.Get("/");
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::OK_200, res->status);
  11604. EXPECT_EQ(body, res->body);
  11605. }
  11606. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11607. Server svr;
  11608. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11609. res.set_content_provider(
  11610. 1024, "text/plain",
  11611. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11612. sink.write("hello", 5);
  11613. sink.done(); // short of the 1024 bytes the response promised
  11614. return true;
  11615. });
  11616. });
  11617. auto port = svr.bind_to_any_port(HOST);
  11618. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11619. auto se = detail::scope_exit([&] {
  11620. svr.stop();
  11621. listen_thread.join();
  11622. ASSERT_FALSE(svr.is_running());
  11623. });
  11624. svr.wait_until_ready();
  11625. Client cli(HOST, port);
  11626. cli.set_read_timeout(5, 0);
  11627. // The response is short of its Content-Length, so the client cannot read a
  11628. // complete body. What matters is that this returns at all: a no-op done()
  11629. // would leave the writer looping over a provider that never makes progress.
  11630. auto res = cli.Get("/");
  11631. EXPECT_FALSE(res);
  11632. }
  11633. // Read as the next response by a peer that sees it after a framed body.
  11634. static const std::string smuggled_response =
  11635. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11636. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11637. Server svr;
  11638. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11639. res.set_content_provider(
  11640. 5, "text/plain",
  11641. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11642. auto data = "AAAAA" + smuggled_response;
  11643. sink.write(data.data(), data.size());
  11644. return true;
  11645. });
  11646. });
  11647. thread t = thread([&] { svr.listen(HOST, PORT); });
  11648. auto se = detail::scope_exit([&] {
  11649. svr.stop();
  11650. t.join();
  11651. ASSERT_FALSE(svr.is_running());
  11652. });
  11653. svr.wait_until_ready();
  11654. std::string resp;
  11655. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11656. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11657. resp.clear();
  11658. ASSERT_TRUE(send_request(
  11659. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11660. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11661. }
  11662. TEST(NoContentTest, BodyIsNotSent) {
  11663. Server svr;
  11664. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11665. res.status = StatusCode::NoContent_204;
  11666. res.set_content(smuggled_response, "text/plain");
  11667. });
  11668. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11669. res.status = StatusCode::NotModified_304;
  11670. res.set_chunked_content_provider(
  11671. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11672. sink.write(smuggled_response.data(), smuggled_response.size());
  11673. sink.done();
  11674. return true;
  11675. });
  11676. });
  11677. thread t = thread([&] { svr.listen(HOST, PORT); });
  11678. auto se = detail::scope_exit([&] {
  11679. svr.stop();
  11680. t.join();
  11681. ASSERT_FALSE(svr.is_running());
  11682. });
  11683. svr.wait_until_ready();
  11684. for (auto path : {"/204", "/304"}) {
  11685. std::string resp;
  11686. ASSERT_TRUE(send_request(
  11687. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11688. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11689. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11690. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11691. }
  11692. }
  11693. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11694. Server svr;
  11695. std::atomic<bool> smuggled(false);
  11696. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11697. res.set_content("ok", "text/plain");
  11698. });
  11699. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11700. smuggled = true;
  11701. });
  11702. auto port = svr.bind_to_any_port(HOST);
  11703. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11704. auto se = detail::scope_exit([&] {
  11705. svr.stop();
  11706. listen_thread.join();
  11707. ASSERT_FALSE(svr.is_running());
  11708. });
  11709. svr.wait_until_ready();
  11710. // What follows the body would be read as the next request.
  11711. Client cli(HOST, port);
  11712. auto res = cli.Post(
  11713. "/", 5,
  11714. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11715. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11716. sink.write(data.data(), data.size());
  11717. return true;
  11718. },
  11719. "text/plain");
  11720. ASSERT_FALSE(res);
  11721. EXPECT_EQ(Error::Write, res.error());
  11722. EXPECT_FALSE(smuggled);
  11723. }
  11724. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11725. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11726. // The compressed path builds the whole body before connecting, so this
  11727. // fails client-side and never reaches a server.
  11728. Client cli(HOST, PORT);
  11729. cli.set_compress(true);
  11730. auto res = cli.Post(
  11731. "/", 1024,
  11732. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11733. sink.write("hello", 5);
  11734. sink.done(); // short of the 1024 bytes the request announced
  11735. return true;
  11736. },
  11737. "text/plain");
  11738. ASSERT_FALSE(res);
  11739. EXPECT_EQ(Error::Write, res.error());
  11740. }
  11741. #endif
  11742. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11743. Server svr;
  11744. svr.set_error_handler([](Request const &, Response &res) -> void {
  11745. res.set_chunked_content_provider(
  11746. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11747. sink.os << "hello";
  11748. sink.os << "world";
  11749. sink.done();
  11750. return true;
  11751. });
  11752. });
  11753. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11754. auto se = detail::scope_exit([&] {
  11755. svr.stop();
  11756. listen_thread.join();
  11757. ASSERT_FALSE(svr.is_running());
  11758. });
  11759. svr.wait_until_ready();
  11760. Client cli("localhost", PORT);
  11761. auto res = cli.Get("/");
  11762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11763. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11764. EXPECT_EQ("helloworld", res->body);
  11765. }
  11766. // A body set after a content provider must replace it, not be sent through it.
  11767. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11768. Server svr;
  11769. svr.set_mount_point("/", "./www");
  11770. svr.set_file_request_handler([](const Request &req, Response &res) {
  11771. if (req.path == "/dir/test.html") {
  11772. res.status = StatusCode::Forbidden_403;
  11773. res.set_content(std::string(5000, 'D'), "text/plain");
  11774. } else if (req.path == "/file") {
  11775. res.status = StatusCode::Forbidden_403;
  11776. res.body = "Denied";
  11777. }
  11778. });
  11779. auto port = svr.bind_to_any_port(HOST);
  11780. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11781. auto se = detail::scope_exit([&] {
  11782. svr.stop();
  11783. t.join();
  11784. ASSERT_FALSE(svr.is_running());
  11785. });
  11786. svr.wait_until_ready();
  11787. Client cli(HOST, port);
  11788. {
  11789. auto res = cli.Get("/dir/test.html");
  11790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11791. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11792. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11793. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11794. }
  11795. {
  11796. auto res = cli.Get("/file");
  11797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11798. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11799. EXPECT_EQ("Denied", res->body);
  11800. }
  11801. {
  11802. auto res = cli.Get("/dir/index.html");
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. EXPECT_EQ(StatusCode::OK_200, res->status);
  11805. EXPECT_EQ(0U, res->body.find("<html>"));
  11806. }
  11807. }
  11808. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11809. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11810. Server svr;
  11811. std::vector<bool> released;
  11812. std::mutex released_mutex;
  11813. auto releaser = [&](bool success) {
  11814. std::lock_guard<std::mutex> guard(released_mutex);
  11815. released.push_back(success);
  11816. };
  11817. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11818. return sink.write(&"hello"[offset], length);
  11819. };
  11820. svr.Get("/sized", [&](const Request &, Response &res) {
  11821. res.status = StatusCode::NotFound_404;
  11822. res.set_content_provider(5, "text/plain", provider, releaser);
  11823. });
  11824. svr.Get("/chunked", [&](const Request &, Response &res) {
  11825. res.status = StatusCode::ServiceUnavailable_503;
  11826. res.set_chunked_content_provider(
  11827. "text/plain",
  11828. [](size_t, DataSink &sink) {
  11829. sink.os << "chunk";
  11830. sink.done();
  11831. return true;
  11832. },
  11833. releaser);
  11834. });
  11835. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11836. res.set_content_provider(5, "text/plain", provider, releaser);
  11837. throw std::runtime_error("after the provider");
  11838. });
  11839. svr.set_error_handler([](const Request &req, Response &res) {
  11840. // Leave the exception handler's content to it.
  11841. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11842. res.set_content(std::string(1000, 'E'), "text/html");
  11843. return Server::HandlerResponse::Handled;
  11844. });
  11845. svr.set_exception_handler(
  11846. [](const Request &, Response &res, std::exception_ptr) {
  11847. res.status = StatusCode::InternalServerError_500;
  11848. res.set_content(std::string(1000, 'X'), "text/html");
  11849. });
  11850. auto port = svr.bind_to_any_port(HOST);
  11851. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11852. auto se = detail::scope_exit([&] {
  11853. svr.stop();
  11854. t.join();
  11855. ASSERT_FALSE(svr.is_running());
  11856. });
  11857. svr.wait_until_ready();
  11858. Client cli(HOST, port);
  11859. {
  11860. auto res = cli.Get("/sized");
  11861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11862. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11863. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11864. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11865. }
  11866. {
  11867. auto res = cli.Get("/chunked");
  11868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11869. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11870. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11871. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11872. }
  11873. {
  11874. auto res = cli.Get("/throw");
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11877. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11878. }
  11879. std::lock_guard<std::mutex> guard(released_mutex);
  11880. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11881. }
  11882. #endif
  11883. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11884. Server svr;
  11885. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11886. return sink.write(&"abc"[offset], length);
  11887. };
  11888. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11889. res.set_file_content("./www/dir/test.html");
  11890. res.set_content("body", "text/plain");
  11891. });
  11892. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11893. res.set_content(std::string(100, 'B'), "text/plain");
  11894. res.set_file_content("./www/dir/test.html");
  11895. });
  11896. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11897. res.set_content(std::string(100, 'B'), "text/plain");
  11898. res.set_content_provider(3, "text/x-provider", abc);
  11899. });
  11900. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11901. res.set_content_provider(3, "text/x-provider", abc);
  11902. res.set_content(std::string(100, 'B'), "text/plain");
  11903. });
  11904. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11905. res.set_content_provider(3, "text/x-provider", abc);
  11906. res.set_file_content("./www/dir/test.html", "text/x-file");
  11907. });
  11908. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11909. res.set_file_content("./www/dir/test.html");
  11910. res.set_header("Content-Type", "text/x-handler");
  11911. });
  11912. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11913. res.set_content_provider(3, "text/plain", abc);
  11914. res.body = "direct";
  11915. });
  11916. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11917. res.set_file_content("./www/dir/test.html");
  11918. res.body = "direct";
  11919. });
  11920. auto port = svr.bind_to_any_port(HOST);
  11921. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11922. auto se = detail::scope_exit([&] {
  11923. svr.stop();
  11924. t.join();
  11925. ASSERT_FALSE(svr.is_running());
  11926. });
  11927. svr.wait_until_ready();
  11928. Client cli(HOST, port);
  11929. auto expect_body = [&](const char *path, const std::string &body,
  11930. const std::string &type) {
  11931. // Uncompressed, so Content-Length can be compared with the body.
  11932. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11933. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11934. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11935. EXPECT_EQ(body, res->body) << path;
  11936. EXPECT_EQ(std::to_string(body.size()),
  11937. res->get_header_value("Content-Length"))
  11938. << path;
  11939. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11940. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11941. };
  11942. expect_body("/file-then-body", "body", "text/plain");
  11943. expect_body("/body-then-file", "test.html", "text/html");
  11944. expect_body("/body-then-provider", "abc", "text/x-provider");
  11945. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11946. expect_body("/provider-then-file", "test.html", "text/x-file");
  11947. expect_body("/file-then-header", "test.html", "text/x-handler");
  11948. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11949. expect_body("/file-then-direct-body", "direct", "text/plain");
  11950. // Ranges are checked against the body, not the dropped provider.
  11951. {
  11952. auto res = cli.Get("/provider-then-direct-body",
  11953. Headers{{make_range_header({{1, 2}})}});
  11954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11956. EXPECT_EQ("ir", res->body);
  11957. }
  11958. {
  11959. auto res = cli.Get("/file-then-direct-body",
  11960. Headers{{make_range_header({{7, 8}})}});
  11961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11962. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11963. }
  11964. }
  11965. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11966. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11967. const char *path = "./truncated_while_served.txt";
  11968. const size_t size = 32 * 1024 * 1024;
  11969. {
  11970. std::ofstream f(path, std::ios::binary);
  11971. f << std::string(size, 'x');
  11972. }
  11973. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11974. // Over TLS, where the bytes are encrypted in this process rather than
  11975. // copied by send().
  11976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11977. svr.Get("/file", [&](const Request &, Response &res) {
  11978. res.set_file_content(path, "text/plain");
  11979. });
  11980. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11981. auto se = detail::scope_exit([&] {
  11982. svr.stop();
  11983. thread.join();
  11984. ASSERT_FALSE(svr.is_running());
  11985. });
  11986. svr.wait_until_ready();
  11987. // The file shrinks once the first bytes are in, as a rewrite in place
  11988. // would, and reading the mapping past its new end used to raise SIGBUS.
  11989. SSLClient cli(HOST, PORT);
  11990. cli.enable_server_certificate_verification(false);
  11991. size_t received = 0;
  11992. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11993. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11994. received += len;
  11995. return true;
  11996. });
  11997. EXPECT_FALSE(res);
  11998. EXPECT_LT(received, size);
  11999. }
  12000. #endif
  12001. // Forward declaration (see the base64_encode note).
  12002. namespace httplib {
  12003. namespace detail {
  12004. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12005. const std::string &content_type,
  12006. EncodingType encoding);
  12007. } // namespace detail
  12008. } // namespace httplib
  12009. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12010. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12011. ASSERT_TRUE(mm->is_open());
  12012. Response res;
  12013. detail::set_file_content_provider(res, mm, "text/html",
  12014. detail::EncodingType::None);
  12015. std::string out;
  12016. DataSink sink;
  12017. sink.write = [&](const char *d, size_t l) {
  12018. out.append(d, l);
  12019. return true;
  12020. };
  12021. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12022. EXPECT_EQ("test.html", out);
  12023. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12024. EXPECT_EQ("test.html", out);
  12025. }
  12026. TEST(LongPollingTest, ClientCloseDetection) {
  12027. Server svr;
  12028. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12029. res.set_chunked_content_provider(
  12030. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12031. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12032. sink.os << "hello";
  12033. auto count = 10;
  12034. while (count > 0 && sink.is_writable()) {
  12035. this_thread::sleep_for(chrono::milliseconds(10));
  12036. count--;
  12037. }
  12038. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12039. return true;
  12040. });
  12041. });
  12042. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12043. auto se = detail::scope_exit([&] {
  12044. svr.stop();
  12045. listen_thread.join();
  12046. ASSERT_FALSE(svr.is_running());
  12047. });
  12048. svr.wait_until_ready();
  12049. Client cli("localhost", PORT);
  12050. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12051. EXPECT_EQ("hello", string(data, data_length));
  12052. return false; // close the socket immediately.
  12053. });
  12054. ASSERT_FALSE(res);
  12055. }
  12056. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12057. Server svr;
  12058. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12059. res.set_chunked_content_provider(
  12060. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12061. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12062. sink.os << "hello";
  12063. EXPECT_TRUE(sink.os.good());
  12064. // Wait for the client to close the connection
  12065. auto count = 10;
  12066. while (count > 0 && sink.is_writable()) {
  12067. this_thread::sleep_for(chrono::milliseconds(10));
  12068. count--;
  12069. }
  12070. // After client disconnect, write repeatedly until the socket
  12071. // write actually fails (small writes may be absorbed by the
  12072. // kernel buffer)
  12073. std::string chunk(1024, 'x');
  12074. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12075. sink.os << chunk;
  12076. }
  12077. EXPECT_TRUE(sink.os.fail());
  12078. return true;
  12079. });
  12080. });
  12081. auto port = svr.bind_to_any_port("localhost");
  12082. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12083. auto se = detail::scope_exit([&] {
  12084. svr.stop();
  12085. listen_thread.join();
  12086. ASSERT_FALSE(svr.is_running());
  12087. });
  12088. svr.wait_until_ready();
  12089. Client cli("localhost", port);
  12090. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12091. EXPECT_EQ("hello", string(data, data_length));
  12092. return false; // close the socket immediately.
  12093. });
  12094. ASSERT_FALSE(res);
  12095. }
  12096. TEST(GetWithParametersTest, GetWithParameters) {
  12097. Server svr;
  12098. svr.Get("/", [&](const Request &req, Response &) {
  12099. EXPECT_EQ("world", req.get_param_value("hello"));
  12100. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12101. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12102. });
  12103. svr.Get("/params", [&](const Request &req, Response &) {
  12104. EXPECT_EQ("world", req.get_param_value("hello"));
  12105. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12106. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12107. });
  12108. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12109. EXPECT_EQ("resource-id", req.matches[1]);
  12110. EXPECT_EQ("foo", req.get_param_value("param1"));
  12111. EXPECT_EQ("bar", req.get_param_value("param2"));
  12112. });
  12113. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12114. EXPECT_EQ("user-id", req.path_params.at("id"));
  12115. EXPECT_EQ("foo", req.get_param_value("param1"));
  12116. EXPECT_EQ("bar", req.get_param_value("param2"));
  12117. });
  12118. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12119. auto se = detail::scope_exit([&] {
  12120. svr.stop();
  12121. listen_thread.join();
  12122. ASSERT_FALSE(svr.is_running());
  12123. });
  12124. svr.wait_until_ready();
  12125. {
  12126. Client cli(HOST, PORT);
  12127. Params params;
  12128. params.emplace("hello", "world");
  12129. params.emplace("hello2", "world2");
  12130. params.emplace("hello3", "world3");
  12131. auto res = cli.Get("/", params, Headers{});
  12132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12133. EXPECT_EQ(StatusCode::OK_200, res->status);
  12134. }
  12135. {
  12136. Client cli(HOST, PORT);
  12137. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12139. EXPECT_EQ(StatusCode::OK_200, res->status);
  12140. }
  12141. {
  12142. Client cli(HOST, PORT);
  12143. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12145. EXPECT_EQ(StatusCode::OK_200, res->status);
  12146. }
  12147. {
  12148. Client cli(HOST, PORT);
  12149. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12151. EXPECT_EQ(StatusCode::OK_200, res->status);
  12152. }
  12153. }
  12154. TEST(GetWithParametersTest, GetWithParameters2) {
  12155. Server svr;
  12156. svr.Get("/", [&](const Request &req, Response &res) {
  12157. auto text = req.get_param_value("hello");
  12158. res.set_content(text, "text/plain");
  12159. });
  12160. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12161. auto se = detail::scope_exit([&] {
  12162. svr.stop();
  12163. listen_thread.join();
  12164. ASSERT_FALSE(svr.is_running());
  12165. });
  12166. svr.wait_until_ready();
  12167. Client cli("localhost", PORT);
  12168. Params params;
  12169. params.emplace("hello", "world");
  12170. std::string body;
  12171. auto res = cli.Get("/", params, Headers{},
  12172. [&](const char *data, size_t data_length) {
  12173. body.append(data, data_length);
  12174. return true;
  12175. });
  12176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12177. EXPECT_EQ(StatusCode::OK_200, res->status);
  12178. EXPECT_EQ("world", body);
  12179. }
  12180. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12181. Server svr;
  12182. svr.Get("/search", [&](const Request &req, Response &res) {
  12183. auto q = req.get_param_value("q");
  12184. res.set_content(q, "text/plain");
  12185. });
  12186. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12187. auto se = detail::scope_exit([&] {
  12188. svr.stop();
  12189. listen_thread.join();
  12190. ASSERT_FALSE(svr.is_running());
  12191. });
  12192. svr.wait_until_ready();
  12193. Client cli("localhost", PORT);
  12194. // Verify that Get(path, params) works without requiring Headers argument
  12195. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12197. EXPECT_EQ(StatusCode::OK_200, res->status);
  12198. EXPECT_EQ("cpp-httplib", res->body);
  12199. }
  12200. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12201. auto host = "httpbingo.org";
  12202. auto path = std::string{"/range/32"};
  12203. #ifdef CPPHTTPLIB_SSL_ENABLED
  12204. SSLClient cli(host);
  12205. #else
  12206. Client cli(host);
  12207. #endif
  12208. cli.set_default_headers({make_range_header({{1, 10}})});
  12209. cli.set_connection_timeout(5);
  12210. {
  12211. auto res = cli.Get(path);
  12212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12213. EXPECT_EQ("bcdefghijk", res->body);
  12214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12215. }
  12216. {
  12217. auto res = cli.Get(path);
  12218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12219. EXPECT_EQ("bcdefghijk", res->body);
  12220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12221. }
  12222. }
  12223. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12224. Server svr;
  12225. svr.set_default_headers({{"Hello", "World"}});
  12226. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12227. res.set_content("ok", "text/plain");
  12228. });
  12229. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12230. auto se = detail::scope_exit([&] {
  12231. svr.stop();
  12232. listen_thread.join();
  12233. ASSERT_FALSE(svr.is_running());
  12234. });
  12235. svr.wait_until_ready();
  12236. Client cli("localhost", PORT);
  12237. auto res = cli.Get("/");
  12238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12239. EXPECT_EQ(StatusCode::OK_200, res->status);
  12240. EXPECT_EQ("ok", res->body);
  12241. EXPECT_EQ("World", res->get_header_value("Hello"));
  12242. }
  12243. #ifdef CPPHTTPLIB_SSL_ENABLED
  12244. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12246. ASSERT_TRUE(svr.is_valid());
  12247. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12248. std::this_thread::sleep_for(std::chrono::seconds(2));
  12249. res.set_content("a", "text/plain");
  12250. });
  12251. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12252. res.set_content("b", "text/plain");
  12253. });
  12254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12255. auto se = detail::scope_exit([&] {
  12256. svr.stop();
  12257. listen_thread.join();
  12258. ASSERT_FALSE(svr.is_running());
  12259. });
  12260. svr.wait_until_ready();
  12261. SSLClient cli("localhost", PORT);
  12262. cli.enable_server_certificate_verification(false);
  12263. cli.set_keep_alive(true);
  12264. cli.set_read_timeout(std::chrono::seconds(1));
  12265. auto resa = cli.Get("/a");
  12266. ASSERT_TRUE(!resa);
  12267. EXPECT_EQ(Error::Read, resa.error());
  12268. auto resb = cli.Get("/b");
  12269. ASSERT_TRUE(resb);
  12270. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12271. EXPECT_EQ("b", resb->body);
  12272. }
  12273. // Closing an idle keep-alive connection sends close_notify and returns. The
  12274. // server must not wait for the client's close_notify: an idle client never
  12275. // sends one, so the worker would be held until the read timeout expires, and
  12276. // stop() would wait for it.
  12277. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12279. ASSERT_TRUE(svr.is_valid());
  12280. svr.set_keep_alive_timeout(1);
  12281. svr.set_read_timeout(10, 0);
  12282. svr.Get("/", [](const Request &, Response &res) {
  12283. res.set_content("ok", "text/plain");
  12284. });
  12285. auto port = svr.bind_to_any_port(HOST);
  12286. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12287. auto se = detail::scope_exit([&] {
  12288. if (listen_thread.joinable()) {
  12289. svr.stop();
  12290. listen_thread.join();
  12291. }
  12292. });
  12293. svr.wait_until_ready();
  12294. SSLClient cli(HOST, port);
  12295. cli.enable_server_certificate_verification(false);
  12296. cli.set_keep_alive(true);
  12297. auto res = cli.Get("/");
  12298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12299. EXPECT_EQ(StatusCode::OK_200, res->status);
  12300. // Stay idle past the keep-alive timeout so the server closes the connection.
  12301. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12302. auto start = std::chrono::steady_clock::now();
  12303. svr.stop();
  12304. listen_thread.join();
  12305. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12306. std::chrono::steady_clock::now() - start)
  12307. .count();
  12308. EXPECT_LT(elapsed, 3000);
  12309. }
  12310. #endif
  12311. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12312. protected:
  12313. ServerTestWithAI_PASSIVE()
  12314. : cli_(HOST, PORT)
  12315. #ifdef CPPHTTPLIB_SSL_ENABLED
  12316. ,
  12317. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12318. #endif
  12319. {
  12320. #ifdef CPPHTTPLIB_SSL_ENABLED
  12321. cli_.enable_server_certificate_verification(false);
  12322. #endif
  12323. }
  12324. virtual void SetUp() {
  12325. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12326. res.set_content("Hello World!", "text/plain");
  12327. });
  12328. t_ = thread(
  12329. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12330. svr_.wait_until_ready();
  12331. }
  12332. virtual void TearDown() {
  12333. svr_.stop();
  12334. t_.join();
  12335. }
  12336. #ifdef CPPHTTPLIB_SSL_ENABLED
  12337. SSLClient cli_;
  12338. SSLServer svr_;
  12339. #else
  12340. Client cli_;
  12341. Server svr_;
  12342. #endif
  12343. thread t_;
  12344. };
  12345. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12346. auto res = cli_.Get("/hi");
  12347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12348. EXPECT_EQ(StatusCode::OK_200, res->status);
  12349. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12350. EXPECT_EQ("Hello World!", res->body);
  12351. }
  12352. class ServerUpDownTest : public ::testing::Test {
  12353. protected:
  12354. ServerUpDownTest() : cli_(HOST, PORT) {}
  12355. virtual void SetUp() {
  12356. t_ = thread([&]() {
  12357. svr_.bind_to_any_port(HOST);
  12358. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12359. ASSERT_TRUE(svr_.listen_after_bind());
  12360. });
  12361. svr_.wait_until_ready();
  12362. }
  12363. virtual void TearDown() {
  12364. svr_.stop();
  12365. t_.join();
  12366. }
  12367. Client cli_;
  12368. Server svr_;
  12369. thread t_;
  12370. };
  12371. TEST_F(ServerUpDownTest, QuickStartStop) {
  12372. // Should not crash, especially when run with
  12373. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12374. }
  12375. class PayloadMaxLengthTest : public ::testing::Test {
  12376. protected:
  12377. PayloadMaxLengthTest()
  12378. : cli_(HOST, PORT)
  12379. #ifdef CPPHTTPLIB_SSL_ENABLED
  12380. ,
  12381. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12382. #endif
  12383. {
  12384. #ifdef CPPHTTPLIB_SSL_ENABLED
  12385. cli_.enable_server_certificate_verification(false);
  12386. #endif
  12387. }
  12388. virtual void SetUp() {
  12389. svr_.set_payload_max_length(8);
  12390. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12391. res.set_content("test", "text/plain");
  12392. });
  12393. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12394. svr_.wait_until_ready();
  12395. }
  12396. virtual void TearDown() {
  12397. svr_.stop();
  12398. t_.join();
  12399. }
  12400. #ifdef CPPHTTPLIB_SSL_ENABLED
  12401. SSLClient cli_;
  12402. SSLServer svr_;
  12403. #else
  12404. Client cli_;
  12405. Server svr_;
  12406. #endif
  12407. thread t_;
  12408. };
  12409. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12410. auto res = cli_.Post("/test", "123456789", "text/plain");
  12411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12412. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12413. res = cli_.Post("/test", "12345678", "text/plain");
  12414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12415. EXPECT_EQ(StatusCode::OK_200, res->status);
  12416. }
  12417. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12418. // Test chunked encoding with payload exceeding the 8-byte limit
  12419. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12420. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12422. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12423. }
  12424. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12425. // Test chunked encoding with payload within the 8-byte limit
  12426. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12427. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12429. EXPECT_EQ(StatusCode::OK_200, res->status);
  12430. }
  12431. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12432. // Test using send_request to send chunked data exceeding payload limit
  12433. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12434. "Host: " +
  12435. std::string(HOST) + ":" + std::to_string(PORT) +
  12436. "\r\n"
  12437. "Transfer-Encoding: chunked\r\n"
  12438. "Connection: close\r\n"
  12439. "\r\n"
  12440. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12441. "0123456789\r\n"
  12442. "0\r\n" // End chunk
  12443. "\r\n";
  12444. std::string response;
  12445. bool result = send_request(1, chunked_request, &response);
  12446. if (!result) {
  12447. // If send_request fails, it might be because the server closed the
  12448. // connection due to payload limit enforcement, which is acceptable
  12449. SUCCEED()
  12450. << "Server rejected oversized chunked request (connection closed)";
  12451. } else {
  12452. // If we got a response, check if it's an error response or connection was
  12453. // closed early Short response length indicates connection was closed due to
  12454. // payload limit
  12455. if (response.length() <= 10) {
  12456. SUCCEED() << "Server closed connection for oversized chunked request";
  12457. } else {
  12458. // Check for error status codes
  12459. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12460. response.find("Payload Too Large") != std::string::npos ||
  12461. response.find("400") != std::string::npos);
  12462. }
  12463. }
  12464. }
  12465. class LargePayloadMaxLengthTest : public ::testing::Test {
  12466. protected:
  12467. LargePayloadMaxLengthTest()
  12468. : cli_(HOST, PORT)
  12469. #ifdef CPPHTTPLIB_SSL_ENABLED
  12470. ,
  12471. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12472. #endif
  12473. {
  12474. #ifdef CPPHTTPLIB_SSL_ENABLED
  12475. cli_.enable_server_certificate_verification(false);
  12476. #endif
  12477. }
  12478. virtual void SetUp() {
  12479. // Set 10MB payload limit
  12480. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12481. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12482. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12483. res.set_content("Large payload test", "text/plain");
  12484. });
  12485. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12486. svr_.wait_until_ready();
  12487. }
  12488. virtual void TearDown() {
  12489. svr_.stop();
  12490. t_.join();
  12491. }
  12492. #ifdef CPPHTTPLIB_SSL_ENABLED
  12493. SSLClient cli_;
  12494. SSLServer svr_;
  12495. #else
  12496. Client cli_;
  12497. Server svr_;
  12498. #endif
  12499. thread t_;
  12500. };
  12501. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12502. // Test chunked encoding with payload within 10MB limit
  12503. std::string medium_payload(5 * 1024 * 1024,
  12504. 'A'); // 5MB payload, within 10MB limit
  12505. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12507. EXPECT_EQ(StatusCode::OK_200, res->status);
  12508. }
  12509. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12510. // Test chunked encoding with payload exceeding 10MB limit
  12511. std::string large_payload(12 * 1024 * 1024,
  12512. 'B'); // 12MB payload, exceeds 10MB limit
  12513. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12514. // Server may either return 413 or close the connection
  12515. if (res) {
  12516. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12517. } else {
  12518. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12519. }
  12520. }
  12521. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12522. Server svr;
  12523. svr.Get("/", [](const Request &, Response &res) {
  12524. // Claims the most the client accepts, far more than it sends, then drops
  12525. // the connection.
  12526. res.set_content_provider(std::string().max_size(), "text/plain",
  12527. [](size_t, size_t, DataSink &sink) {
  12528. sink.write("abc", 3);
  12529. return false;
  12530. });
  12531. });
  12532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12533. auto se = detail::scope_exit([&] {
  12534. svr.stop();
  12535. thread.join();
  12536. ASSERT_FALSE(svr.is_running());
  12537. });
  12538. svr.wait_until_ready();
  12539. Client cli(HOST, PORT);
  12540. cli.set_payload_max_length(0);
  12541. EXPECT_FALSE(cli.Get("/"));
  12542. }
  12543. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12544. // Stream API does, not as a plain read failure
  12545. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12546. Server svr;
  12547. svr.Get("/big", [](const Request &, Response &res) {
  12548. res.set_content(std::string(100000, 'b'), "text/plain");
  12549. });
  12550. auto port = svr.bind_to_any_port(HOST);
  12551. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12552. auto se = detail::scope_exit([&] {
  12553. svr.stop();
  12554. thread.join();
  12555. });
  12556. svr.wait_until_ready();
  12557. Client cli(HOST, port);
  12558. cli.set_payload_max_length(1000);
  12559. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12560. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12561. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12562. [](const char *, size_t) { return true; });
  12563. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12564. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12565. // Small on the wire, over the limit once decompressed
  12566. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12567. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12568. #endif
  12569. }
  12570. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12571. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12572. // path.
  12573. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12574. Server svr;
  12575. const size_t LIMIT = 64 * 1024; // 64KB
  12576. svr.set_payload_max_length(LIMIT);
  12577. size_t total = 0;
  12578. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12579. const ContentReader &content_reader) {
  12580. content_reader([&](const char * /*data*/, size_t len) {
  12581. total += len;
  12582. return true;
  12583. });
  12584. res.status = 200;
  12585. res.set_content("stream_ok", "text/plain");
  12586. });
  12587. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12588. auto se = detail::scope_exit([&] {
  12589. svr.stop();
  12590. thread.join();
  12591. ASSERT_FALSE(svr.is_running());
  12592. });
  12593. svr.wait_until_ready();
  12594. // Prepare 256KB raw data and gzip-compress it
  12595. std::string raw(256 * 1024, 'A');
  12596. std::string gz;
  12597. {
  12598. z_stream zs{};
  12599. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12600. Z_DEFAULT_STRATEGY);
  12601. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12602. zs.avail_in = static_cast<uInt>(raw.size());
  12603. char outbuf[4096];
  12604. int ret;
  12605. do {
  12606. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12607. zs.avail_out = sizeof(outbuf);
  12608. ret = deflate(&zs, Z_FINISH);
  12609. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12610. } while (ret != Z_STREAM_END);
  12611. deflateEnd(&zs);
  12612. }
  12613. Client cli(HOST, PORT);
  12614. cli.set_connection_timeout(std::chrono::seconds(5));
  12615. Headers headers = {{"Content-Encoding", "gzip"}};
  12616. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12617. "application/octet-stream");
  12618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12619. // Server must reject oversized decompressed payloads with 413.
  12620. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12621. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12622. EXPECT_LE(total, LIMIT);
  12623. }
  12624. #endif
  12625. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12626. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12627. // the payload must be passed through untouched instead of being rejected.
  12628. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12629. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12630. Server svr;
  12631. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12632. res.set_content(body, "image/jpeg");
  12633. res.set_header("Content-Encoding", "UTF-8");
  12634. });
  12635. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12636. res.set_content(body, "image/jpeg");
  12637. res.set_header("Content-Encoding", "identity");
  12638. });
  12639. svr.Post("/echo", [](const Request &req, Response &res) {
  12640. res.set_content(req.body, "image/jpeg");
  12641. });
  12642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12643. auto se = detail::scope_exit([&] {
  12644. svr.stop();
  12645. t.join();
  12646. ASSERT_FALSE(svr.is_running());
  12647. });
  12648. svr.wait_until_ready();
  12649. Client cli(HOST, PORT);
  12650. {
  12651. auto res = cli.Get("/image");
  12652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12653. EXPECT_EQ(StatusCode::OK_200, res->status);
  12654. EXPECT_EQ(body, res->body);
  12655. }
  12656. {
  12657. auto res = cli.Get("/identity");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_EQ(StatusCode::OK_200, res->status);
  12660. EXPECT_EQ(body, res->body);
  12661. }
  12662. {
  12663. // The same applies to a request body reaching the server.
  12664. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12665. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12667. EXPECT_EQ(StatusCode::OK_200, res->status);
  12668. EXPECT_EQ(body, res->body);
  12669. }
  12670. }
  12671. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12672. // gzip-encoded response even when the build has no zlib support.
  12673. static const char GZIPPED_HELLO_WORLD[] = {
  12674. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12675. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12676. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12677. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12678. // A content coding is a whole token, not something the field value merely
  12679. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12680. // as "fibre" look like Brotli, and turned a multi-coding value like
  12681. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12682. // it was never meant to see.
  12683. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12684. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12685. Server svr;
  12686. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12687. res.set_content(body, "image/jpeg");
  12688. res.set_header("Content-Encoding", "fibre");
  12689. });
  12690. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12691. res.set_content(body, "image/jpeg");
  12692. res.set_header("Content-Encoding", "gzip, br");
  12693. });
  12694. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12695. res.set_content(body, "image/jpeg");
  12696. res.set_header("Content-Encoding", "x-zstd-ish");
  12697. });
  12698. auto port = svr.bind_to_any_port(HOST);
  12699. thread t = thread([&]() { svr.listen_after_bind(); });
  12700. auto se = detail::scope_exit([&] {
  12701. svr.stop();
  12702. t.join();
  12703. ASSERT_FALSE(svr.is_running());
  12704. });
  12705. svr.wait_until_ready();
  12706. Client cli(HOST, port);
  12707. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12708. auto res = cli.Get(path);
  12709. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12710. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12711. // Not a coding we recognize, so the payload comes back untouched
  12712. EXPECT_EQ(body, res->body) << path;
  12713. }
  12714. }
  12715. // A content coding cpp-httplib recognizes but was not built with must be
  12716. // reported as such. Handing the still-compressed payload back to the caller
  12717. // would silently corrupt it.
  12718. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12719. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12720. Server svr;
  12721. // "image/jpeg" keeps the server from applying a content coding of its own,
  12722. // so the hand-crafted Content-Encoding below survives.
  12723. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12724. res.set_content(gzipped, "image/jpeg");
  12725. res.set_header("Content-Encoding", "gzip");
  12726. });
  12727. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12728. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12729. res.set_content(gzipped, "image/jpeg");
  12730. res.set_header("Content-Encoding", "GZIP");
  12731. });
  12732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12733. auto se = detail::scope_exit([&] {
  12734. svr.stop();
  12735. t.join();
  12736. ASSERT_FALSE(svr.is_running());
  12737. });
  12738. svr.wait_until_ready();
  12739. Client cli(HOST, PORT);
  12740. {
  12741. auto res = cli.Get("/gzipped");
  12742. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12744. EXPECT_EQ("Hello World!", res->body);
  12745. #else
  12746. ASSERT_FALSE(res);
  12747. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12748. #endif
  12749. }
  12750. {
  12751. // open_stream() must behave the same way.
  12752. auto handle = cli.open_stream("GET", "/gzipped");
  12753. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12754. ASSERT_TRUE(handle.is_valid());
  12755. std::string received;
  12756. char buf[256];
  12757. ssize_t n;
  12758. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12759. received.append(buf, static_cast<size_t>(n));
  12760. }
  12761. EXPECT_EQ("Hello World!", received);
  12762. #else
  12763. EXPECT_FALSE(handle.is_valid());
  12764. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12765. #endif
  12766. }
  12767. {
  12768. // A differently-cased coding must not be mistaken for an unknown one, or
  12769. // the body would be handed back still compressed.
  12770. auto res = cli.Get("/gzipped-uppercase");
  12771. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12773. EXPECT_EQ("Hello World!", res->body);
  12774. #else
  12775. ASSERT_FALSE(res);
  12776. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12777. #endif
  12778. }
  12779. }
  12780. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12781. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12782. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12783. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12784. // body a second time and appending a second Content-Encoding field line, so
  12785. // clients that decode one coding per listed value handed back raw gzip bytes.
  12786. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12787. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12788. Server svr;
  12789. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12790. // keeps the server from applying a coding of its own.
  12791. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12792. res.set_content(gzipped, "text/plain");
  12793. res.set_header("Content-Encoding", "gzip");
  12794. });
  12795. auto port = svr.bind_to_any_port(HOST);
  12796. thread t = thread([&]() { svr.listen_after_bind(); });
  12797. auto se = detail::scope_exit([&] {
  12798. svr.stop();
  12799. t.join();
  12800. ASSERT_FALSE(svr.is_running());
  12801. });
  12802. svr.wait_until_ready();
  12803. Client cli(HOST, port);
  12804. Headers headers = {{"Accept-Encoding", "gzip"}};
  12805. auto res = cli.Get("/pre-gzipped", headers);
  12806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12807. EXPECT_EQ(StatusCode::OK_200, res->status);
  12808. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12809. EXPECT_EQ("Hello World!", res->body);
  12810. }
  12811. // set_compress(false) sends every handler response as it is, buffered or
  12812. // streamed
  12813. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12814. const std::string text(1000, 'a');
  12815. Server svr;
  12816. svr.set_compress(false);
  12817. svr.Get("/buffered", [&](const Request &, Response &res) {
  12818. res.set_content(text, "text/plain");
  12819. });
  12820. svr.Get("/streamed", [&](const Request &, Response &res) {
  12821. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12822. sink.write(text.data(), text.size());
  12823. sink.done();
  12824. return true;
  12825. });
  12826. });
  12827. auto port = svr.bind_to_any_port(HOST);
  12828. ASSERT_LT(0, port);
  12829. thread t = thread([&] { svr.listen_after_bind(); });
  12830. auto se = detail::scope_exit([&] {
  12831. svr.stop();
  12832. t.join();
  12833. ASSERT_FALSE(svr.is_running());
  12834. });
  12835. svr.wait_until_ready();
  12836. Client cli(HOST, port);
  12837. cli.set_decompress(false);
  12838. for (auto path : {"/buffered", "/streamed"}) {
  12839. SCOPED_TRACE(path);
  12840. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12842. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12843. EXPECT_EQ(text, res->body);
  12844. }
  12845. }
  12846. // A chunked provider settles its coding where the headers are written and
  12847. // reuses it at write time. Both ends of that have to hold: a handler's own
  12848. // Content-Encoding suppresses the coding, and a response without one is still
  12849. // compressed as it always was.
  12850. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12851. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12852. const std::string plain = "Hello World! Hello World! Hello World!";
  12853. Server svr;
  12854. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12855. res.set_header("Content-Encoding", "gzip");
  12856. res.set_chunked_content_provider(
  12857. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12858. sink.write(gzipped.data(), gzipped.size());
  12859. sink.done();
  12860. return true;
  12861. });
  12862. });
  12863. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12864. res.set_chunked_content_provider(
  12865. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12866. sink.write(plain.data(), plain.size());
  12867. sink.done();
  12868. return true;
  12869. });
  12870. });
  12871. auto port = svr.bind_to_any_port(HOST);
  12872. thread t = thread([&]() { svr.listen_after_bind(); });
  12873. auto se = detail::scope_exit([&] {
  12874. svr.stop();
  12875. t.join();
  12876. ASSERT_FALSE(svr.is_running());
  12877. });
  12878. svr.wait_until_ready();
  12879. Client cli(HOST, port);
  12880. Headers headers = {{"Accept-Encoding", "gzip"}};
  12881. {
  12882. auto res = cli.Get("/pre-gzipped", headers);
  12883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12884. EXPECT_EQ(StatusCode::OK_200, res->status);
  12885. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12886. EXPECT_EQ("Hello World!", res->body);
  12887. }
  12888. {
  12889. auto res = cli.Get("/negotiated", headers);
  12890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12891. EXPECT_EQ(StatusCode::OK_200, res->status);
  12892. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12893. EXPECT_EQ(plain, res->body);
  12894. }
  12895. }
  12896. #endif
  12897. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12898. // the same message as the comma-joined one, so both have to be read the same
  12899. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12900. // single gzip coding, and a body the sender says was encoded twice was handed
  12901. // back after one pass, still compressed but presented as decoded.
  12902. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12903. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12904. Server svr;
  12905. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12906. res.set_content(body, "image/jpeg");
  12907. res.headers.emplace("Content-Encoding", "gzip");
  12908. res.headers.emplace("Content-Encoding", "gzip");
  12909. });
  12910. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12911. res.set_content(body, "image/jpeg");
  12912. res.set_header("Content-Encoding", "gzip, gzip");
  12913. });
  12914. auto port = svr.bind_to_any_port(HOST);
  12915. thread t = thread([&]() { svr.listen_after_bind(); });
  12916. auto se = detail::scope_exit([&] {
  12917. svr.stop();
  12918. t.join();
  12919. ASSERT_FALSE(svr.is_running());
  12920. });
  12921. svr.wait_until_ready();
  12922. Client cli(HOST, port);
  12923. // Two codings is not something cpp-httplib decodes, so both representations
  12924. // take the pass-through path rather than one of them being gunzipped once.
  12925. for (const char *path : {"/split", "/joined"}) {
  12926. auto res = cli.Get(path);
  12927. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12928. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12929. EXPECT_EQ(body, res->body) << path;
  12930. }
  12931. }
  12932. // Regression test for DoS vulnerability: a malicious server sending a response
  12933. // without Content-Length header must not cause unbounded memory consumption on
  12934. // the client side. The client should stop reading after a reasonable limit,
  12935. // similar to the server-side set_payload_max_length protection.
  12936. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12937. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12938. #ifndef _WIN32
  12939. signal(SIGPIPE, SIG_IGN);
  12940. #endif
  12941. auto server_thread = std::thread([] {
  12942. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12943. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12944. default_socket_options(srv);
  12945. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12946. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12947. sockaddr_in addr{};
  12948. addr.sin_family = AF_INET;
  12949. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12950. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12951. int opt = 1;
  12952. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12953. #ifdef _WIN32
  12954. reinterpret_cast<const char *>(&opt),
  12955. #else
  12956. &opt,
  12957. #endif
  12958. sizeof(opt));
  12959. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12960. ::listen(srv, 1);
  12961. sockaddr_in cli_addr{};
  12962. socklen_t cli_len = sizeof(cli_addr);
  12963. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12964. if (cli != INVALID_SOCKET) {
  12965. char buf[4096];
  12966. ::recv(cli, buf, sizeof(buf), 0);
  12967. // Malicious response: no Content-Length, no chunked encoding
  12968. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12969. "Connection: close\r\n"
  12970. "\r\n";
  12971. ::send(cli,
  12972. #ifdef _WIN32
  12973. static_cast<const char *>(response_header.c_str()),
  12974. static_cast<int>(response_header.size()),
  12975. #else
  12976. response_header.c_str(), response_header.size(),
  12977. #endif
  12978. 0);
  12979. // Send 10MB of data
  12980. std::string chunk(64 * 1024, 'A');
  12981. size_t total_sent = 0;
  12982. while (total_sent < MALICIOUS_DATA_SIZE) {
  12983. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12984. auto sent = ::send(cli,
  12985. #ifdef _WIN32
  12986. static_cast<const char *>(chunk.c_str()),
  12987. static_cast<int>(to_send),
  12988. #else
  12989. chunk.c_str(), to_send,
  12990. #endif
  12991. 0);
  12992. if (sent <= 0) break;
  12993. total_sent += static_cast<size_t>(sent);
  12994. }
  12995. detail::close_socket(cli);
  12996. }
  12997. detail::close_socket(srv);
  12998. });
  12999. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13000. size_t total_read = 0;
  13001. {
  13002. Client cli("127.0.0.1", PORT + 2);
  13003. cli.set_read_timeout(5, 0);
  13004. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13005. auto stream = cli.open_stream("GET", "/malicious");
  13006. ASSERT_TRUE(stream.is_valid());
  13007. char buffer[64 * 1024];
  13008. ssize_t n;
  13009. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13010. total_read += static_cast<size_t>(n);
  13011. }
  13012. } // StreamHandle and Client destroyed here, closing the socket
  13013. server_thread.join();
  13014. // With set_payload_max_length, the client must stop reading before consuming
  13015. // all 10MB. The read loop should be cut off at or near the configured limit.
  13016. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13017. << "Client read " << total_read << " bytes, exceeding the configured "
  13018. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13019. }
  13020. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13021. // the entire response body without truncation.
  13022. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13023. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13024. #ifndef _WIN32
  13025. signal(SIGPIPE, SIG_IGN);
  13026. #endif
  13027. auto server_thread = std::thread([] {
  13028. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13029. default_socket_options(srv);
  13030. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13031. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13032. sockaddr_in addr{};
  13033. addr.sin_family = AF_INET;
  13034. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13035. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13036. int opt = 1;
  13037. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13038. #ifdef _WIN32
  13039. reinterpret_cast<const char *>(&opt),
  13040. #else
  13041. &opt,
  13042. #endif
  13043. sizeof(opt));
  13044. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13045. ::listen(srv, 1);
  13046. sockaddr_in cli_addr{};
  13047. socklen_t cli_len = sizeof(cli_addr);
  13048. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13049. if (cli != INVALID_SOCKET) {
  13050. char buf[4096];
  13051. ::recv(cli, buf, sizeof(buf), 0);
  13052. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13053. "Connection: close\r\n"
  13054. "\r\n";
  13055. ::send(cli,
  13056. #ifdef _WIN32
  13057. static_cast<const char *>(response_header.c_str()),
  13058. static_cast<int>(response_header.size()),
  13059. #else
  13060. response_header.c_str(), response_header.size(),
  13061. #endif
  13062. 0);
  13063. std::string chunk(64 * 1024, 'A');
  13064. size_t total_sent = 0;
  13065. while (total_sent < DATA_SIZE) {
  13066. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13067. auto sent = ::send(cli,
  13068. #ifdef _WIN32
  13069. static_cast<const char *>(chunk.c_str()),
  13070. static_cast<int>(to_send),
  13071. #else
  13072. chunk.c_str(), to_send,
  13073. #endif
  13074. 0);
  13075. if (sent <= 0) break;
  13076. total_sent += static_cast<size_t>(sent);
  13077. }
  13078. #ifdef _WIN32
  13079. ::shutdown(cli, SD_SEND);
  13080. #else
  13081. ::shutdown(cli, SHUT_WR);
  13082. #endif
  13083. // Drain until the client closes its end, ensuring all data is delivered
  13084. char drain[1024];
  13085. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13086. detail::close_socket(cli);
  13087. }
  13088. detail::close_socket(srv);
  13089. });
  13090. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13091. size_t total_read = 0;
  13092. {
  13093. Client cli("127.0.0.1", PORT + 2);
  13094. cli.set_read_timeout(5, 0);
  13095. cli.set_payload_max_length(0); // 0 means no limit
  13096. auto stream = cli.open_stream("GET", "/data");
  13097. ASSERT_TRUE(stream.is_valid());
  13098. char buffer[64 * 1024];
  13099. ssize_t n;
  13100. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13101. total_read += static_cast<size_t>(n);
  13102. }
  13103. }
  13104. server_thread.join();
  13105. EXPECT_EQ(total_read, DATA_SIZE)
  13106. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13107. << " bytes without truncation, but only read " << total_read << " bytes.";
  13108. }
  13109. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13110. // enormous Content-Length must not cause the client to pre-allocate a huge
  13111. // response body buffer. The reservation is capped at payload_max_length_, and
  13112. // the read itself fails when the body exceeds the limit.
  13113. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13114. #ifndef _WIN32
  13115. signal(SIGPIPE, SIG_IGN);
  13116. #endif
  13117. auto server_thread = std::thread([] {
  13118. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13119. default_socket_options(srv);
  13120. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13121. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13122. sockaddr_in addr{};
  13123. addr.sin_family = AF_INET;
  13124. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13125. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13126. int opt = 1;
  13127. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13128. #ifdef _WIN32
  13129. reinterpret_cast<const char *>(&opt),
  13130. #else
  13131. &opt,
  13132. #endif
  13133. sizeof(opt));
  13134. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13135. ::listen(srv, 1);
  13136. sockaddr_in cli_addr{};
  13137. socklen_t cli_len = sizeof(cli_addr);
  13138. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13139. if (cli != INVALID_SOCKET) {
  13140. char buf[4096];
  13141. ::recv(cli, buf, sizeof(buf), 0);
  13142. // Malicious response: claim a 20GB body but send only a tiny payload.
  13143. std::string response = "HTTP/1.1 200 OK\r\n"
  13144. "Content-Length: 20000000000\r\n"
  13145. "\r\n"
  13146. "abc";
  13147. ::send(cli,
  13148. #ifdef _WIN32
  13149. static_cast<const char *>(response.c_str()),
  13150. static_cast<int>(response.size()),
  13151. #else
  13152. response.c_str(), response.size(),
  13153. #endif
  13154. 0);
  13155. detail::close_socket(cli);
  13156. }
  13157. detail::close_socket(srv);
  13158. });
  13159. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13160. {
  13161. Client cli("127.0.0.1", PORT + 2);
  13162. cli.set_read_timeout(5, 0);
  13163. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13164. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13165. // (server claims more bytes than payload_max_length permits), but it must
  13166. // not exhaust memory before getting there.
  13167. auto res = cli.Get("/malicious");
  13168. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13169. }
  13170. server_thread.join();
  13171. }
  13172. // Verify that content_receiver bypasses the default payload_max_length,
  13173. // allowing streaming downloads larger than 100MB without requiring an explicit
  13174. // set_payload_max_length call.
  13175. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13176. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13177. #ifndef _WIN32
  13178. signal(SIGPIPE, SIG_IGN);
  13179. #endif
  13180. auto server_thread = std::thread([] {
  13181. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13182. default_socket_options(srv);
  13183. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13184. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13185. sockaddr_in addr{};
  13186. addr.sin_family = AF_INET;
  13187. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13188. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13189. int opt = 1;
  13190. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13191. #ifdef _WIN32
  13192. reinterpret_cast<const char *>(&opt),
  13193. #else
  13194. &opt,
  13195. #endif
  13196. sizeof(opt));
  13197. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13198. ::listen(srv, 1);
  13199. sockaddr_in cli_addr{};
  13200. socklen_t cli_len = sizeof(cli_addr);
  13201. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13202. if (cli != INVALID_SOCKET) {
  13203. char buf[4096];
  13204. ::recv(cli, buf, sizeof(buf), 0);
  13205. // Response with Content-Length larger than default 100MB limit
  13206. auto content_length = std::to_string(DATA_SIZE);
  13207. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13208. "Content-Length: " +
  13209. content_length +
  13210. "\r\n"
  13211. "Connection: close\r\n"
  13212. "\r\n";
  13213. ::send(cli,
  13214. #ifdef _WIN32
  13215. static_cast<const char *>(response_header.c_str()),
  13216. static_cast<int>(response_header.size()),
  13217. #else
  13218. response_header.c_str(), response_header.size(),
  13219. #endif
  13220. 0);
  13221. std::string chunk(64 * 1024, 'A');
  13222. size_t total_sent = 0;
  13223. while (total_sent < DATA_SIZE) {
  13224. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13225. auto sent = ::send(cli,
  13226. #ifdef _WIN32
  13227. static_cast<const char *>(chunk.c_str()),
  13228. static_cast<int>(to_send),
  13229. #else
  13230. chunk.c_str(), to_send,
  13231. #endif
  13232. 0);
  13233. if (sent <= 0) break;
  13234. total_sent += static_cast<size_t>(sent);
  13235. }
  13236. detail::close_socket(cli);
  13237. }
  13238. detail::close_socket(srv);
  13239. });
  13240. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13241. size_t total_received = 0;
  13242. {
  13243. Client cli("127.0.0.1", PORT + 2);
  13244. cli.set_read_timeout(10, 0);
  13245. // Do NOT call set_payload_max_length — use the default 100MB limit
  13246. auto res =
  13247. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13248. total_received += data_length;
  13249. return true;
  13250. });
  13251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13252. EXPECT_EQ(StatusCode::OK_200, res->status);
  13253. }
  13254. server_thread.join();
  13255. EXPECT_EQ(total_received, DATA_SIZE)
  13256. << "With content_receiver, the client should read all " << DATA_SIZE
  13257. << " bytes despite the default 100MB payload_max_length, but only read "
  13258. << total_received << " bytes.";
  13259. }
  13260. // Verify that an explicit set_payload_max_length smaller than the response is
  13261. // enforced even when a content_receiver is used.
  13262. TEST(ClientVulnerabilityTest,
  13263. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13264. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13265. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13266. #ifndef _WIN32
  13267. signal(SIGPIPE, SIG_IGN);
  13268. #endif
  13269. auto server_thread = std::thread([] {
  13270. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13271. default_socket_options(srv);
  13272. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13273. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13274. sockaddr_in addr{};
  13275. addr.sin_family = AF_INET;
  13276. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13277. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13278. int opt = 1;
  13279. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13280. #ifdef _WIN32
  13281. reinterpret_cast<const char *>(&opt),
  13282. #else
  13283. &opt,
  13284. #endif
  13285. sizeof(opt));
  13286. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13287. ::listen(srv, 1);
  13288. sockaddr_in cli_addr{};
  13289. socklen_t cli_len = sizeof(cli_addr);
  13290. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13291. if (cli != INVALID_SOCKET) {
  13292. char buf[4096];
  13293. ::recv(cli, buf, sizeof(buf), 0);
  13294. auto content_length = std::to_string(DATA_SIZE);
  13295. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13296. "Content-Length: " +
  13297. content_length +
  13298. "\r\n"
  13299. "Connection: close\r\n"
  13300. "\r\n";
  13301. ::send(cli,
  13302. #ifdef _WIN32
  13303. static_cast<const char *>(response_header.c_str()),
  13304. static_cast<int>(response_header.size()),
  13305. #else
  13306. response_header.c_str(), response_header.size(),
  13307. #endif
  13308. 0);
  13309. std::string chunk(64 * 1024, 'A');
  13310. size_t total_sent = 0;
  13311. while (total_sent < DATA_SIZE) {
  13312. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13313. auto sent = ::send(cli,
  13314. #ifdef _WIN32
  13315. static_cast<const char *>(chunk.c_str()),
  13316. static_cast<int>(to_send),
  13317. #else
  13318. chunk.c_str(), to_send,
  13319. #endif
  13320. 0);
  13321. if (sent <= 0) break;
  13322. total_sent += static_cast<size_t>(sent);
  13323. }
  13324. detail::close_socket(cli);
  13325. }
  13326. detail::close_socket(srv);
  13327. });
  13328. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13329. size_t total_received = 0;
  13330. {
  13331. Client cli("127.0.0.1", PORT + 2);
  13332. cli.set_read_timeout(10, 0);
  13333. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13334. auto res =
  13335. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13336. total_received += data_length;
  13337. return true;
  13338. });
  13339. // Should fail because 200MB exceeds the explicit 150MB limit
  13340. EXPECT_FALSE(res);
  13341. }
  13342. server_thread.join();
  13343. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13344. << "Client with content_receiver should respect the explicit "
  13345. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13346. << total_received << " bytes.";
  13347. }
  13348. // Verify that an explicit set_payload_max_length larger than the response
  13349. // allows the content_receiver to read all data successfully.
  13350. TEST(ClientVulnerabilityTest,
  13351. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13352. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13353. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13354. #ifndef _WIN32
  13355. signal(SIGPIPE, SIG_IGN);
  13356. #endif
  13357. auto server_thread = std::thread([] {
  13358. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13359. default_socket_options(srv);
  13360. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13361. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13362. sockaddr_in addr{};
  13363. addr.sin_family = AF_INET;
  13364. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13365. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13366. int opt = 1;
  13367. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13368. #ifdef _WIN32
  13369. reinterpret_cast<const char *>(&opt),
  13370. #else
  13371. &opt,
  13372. #endif
  13373. sizeof(opt));
  13374. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13375. ::listen(srv, 1);
  13376. sockaddr_in cli_addr{};
  13377. socklen_t cli_len = sizeof(cli_addr);
  13378. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13379. if (cli != INVALID_SOCKET) {
  13380. char buf[4096];
  13381. ::recv(cli, buf, sizeof(buf), 0);
  13382. auto content_length = std::to_string(DATA_SIZE);
  13383. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13384. "Content-Length: " +
  13385. content_length +
  13386. "\r\n"
  13387. "Connection: close\r\n"
  13388. "\r\n";
  13389. ::send(cli,
  13390. #ifdef _WIN32
  13391. static_cast<const char *>(response_header.c_str()),
  13392. static_cast<int>(response_header.size()),
  13393. #else
  13394. response_header.c_str(), response_header.size(),
  13395. #endif
  13396. 0);
  13397. std::string chunk(64 * 1024, 'A');
  13398. size_t total_sent = 0;
  13399. while (total_sent < DATA_SIZE) {
  13400. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13401. auto sent = ::send(cli,
  13402. #ifdef _WIN32
  13403. static_cast<const char *>(chunk.c_str()),
  13404. static_cast<int>(to_send),
  13405. #else
  13406. chunk.c_str(), to_send,
  13407. #endif
  13408. 0);
  13409. if (sent <= 0) break;
  13410. total_sent += static_cast<size_t>(sent);
  13411. }
  13412. #ifdef _WIN32
  13413. ::shutdown(cli, SD_SEND);
  13414. #else
  13415. ::shutdown(cli, SHUT_WR);
  13416. #endif
  13417. char drain[1024];
  13418. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13419. detail::close_socket(cli);
  13420. }
  13421. detail::close_socket(srv);
  13422. });
  13423. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13424. size_t total_received = 0;
  13425. {
  13426. Client cli("127.0.0.1", PORT + 2);
  13427. cli.set_read_timeout(10, 0);
  13428. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13429. auto res =
  13430. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13431. total_received += data_length;
  13432. return true;
  13433. });
  13434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13435. EXPECT_EQ(StatusCode::OK_200, res->status);
  13436. }
  13437. server_thread.join();
  13438. EXPECT_EQ(total_received, DATA_SIZE)
  13439. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13440. << " bytes (larger than " << DATA_SIZE
  13441. << " bytes response), content_receiver should read all data, but only "
  13442. "read "
  13443. << total_received << " bytes.";
  13444. }
  13445. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13446. // Regression test for "zip bomb" attack on the client side: a malicious server
  13447. // sends a small gzip-compressed response that decompresses to a huge payload.
  13448. // The client must enforce payload_max_length on the decompressed size.
  13449. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13450. constexpr size_t DECOMPRESSED_SIZE =
  13451. 10 * 1024 * 1024; // 10MB after decompression
  13452. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13453. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13454. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13455. std::string compressed;
  13456. {
  13457. httplib::detail::gzip_compressor compressor;
  13458. bool ok =
  13459. compressor.compress(uncompressed.data(), uncompressed.size(),
  13460. /*last=*/true, [&](const char *buf, size_t len) {
  13461. compressed.append(buf, len);
  13462. return true;
  13463. });
  13464. ASSERT_TRUE(ok);
  13465. }
  13466. // Sanity: compressed data should be much smaller than the decompressed size
  13467. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13468. #ifndef _WIN32
  13469. signal(SIGPIPE, SIG_IGN);
  13470. #endif
  13471. // Set up the listening socket in the main thread so the server is guaranteed
  13472. // to be ready before the client connects (eliminates race condition).
  13473. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13474. default_socket_options(srv);
  13475. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13476. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13477. sockaddr_in addr{};
  13478. addr.sin_family = AF_INET;
  13479. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13480. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13481. int opt = 1;
  13482. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13483. #ifdef _WIN32
  13484. reinterpret_cast<const char *>(&opt),
  13485. #else
  13486. &opt,
  13487. #endif
  13488. sizeof(opt));
  13489. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13490. ASSERT_EQ(0, ::listen(srv, 1));
  13491. auto server_thread = std::thread([&compressed, srv] {
  13492. sockaddr_in cli_addr{};
  13493. socklen_t cli_len = sizeof(cli_addr);
  13494. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13495. if (cli != INVALID_SOCKET) {
  13496. // Read the full HTTP request (until \r\n\r\n)
  13497. char buf[4096];
  13498. size_t total = 0;
  13499. while (total < sizeof(buf)) {
  13500. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13501. if (n <= 0) break;
  13502. total += static_cast<size_t>(n);
  13503. // Check for end of headers
  13504. if (total >= 4) {
  13505. std::string req(buf, total);
  13506. if (req.find("\r\n\r\n") != std::string::npos) break;
  13507. }
  13508. }
  13509. // Malicious response: gzip-compressed body, no Content-Length
  13510. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13511. "Content-Encoding: gzip\r\n"
  13512. "Connection: close\r\n"
  13513. "\r\n";
  13514. ::send(cli,
  13515. #ifdef _WIN32
  13516. static_cast<const char *>(response_header.c_str()),
  13517. static_cast<int>(response_header.size()),
  13518. #else
  13519. response_header.c_str(), response_header.size(),
  13520. #endif
  13521. 0);
  13522. // Send the compressed payload (small on the wire, huge when decompressed)
  13523. size_t total_sent = 0;
  13524. while (total_sent < compressed.size()) {
  13525. auto to_send = std::min(compressed.size() - total_sent,
  13526. static_cast<size_t>(64 * 1024));
  13527. auto sent =
  13528. ::send(cli,
  13529. #ifdef _WIN32
  13530. static_cast<const char *>(compressed.c_str() + total_sent),
  13531. static_cast<int>(to_send),
  13532. #else
  13533. compressed.c_str() + total_sent, to_send,
  13534. #endif
  13535. 0);
  13536. if (sent <= 0) break;
  13537. total_sent += static_cast<size_t>(sent);
  13538. }
  13539. detail::close_socket(cli);
  13540. }
  13541. });
  13542. auto se = detail::scope_exit([&] {
  13543. detail::close_socket(srv);
  13544. server_thread.join();
  13545. });
  13546. size_t total_decompressed = 0;
  13547. {
  13548. Client cli("127.0.0.1", PORT + 3);
  13549. cli.set_read_timeout(5, 0);
  13550. cli.set_decompress(true);
  13551. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13552. auto stream = cli.open_stream("GET", "/zipbomb");
  13553. ASSERT_TRUE(stream.is_valid());
  13554. char buffer[64 * 1024];
  13555. ssize_t n;
  13556. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13557. total_decompressed += static_cast<size_t>(n);
  13558. }
  13559. }
  13560. // The decompressed size must be capped by payload_max_length. Without
  13561. // protection, the client would decompress the full 10MB from a tiny
  13562. // compressed payload, enabling a zip bomb DoS attack.
  13563. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13564. << "Client decompressed " << total_decompressed
  13565. << " bytes from a gzip response. The decompressed size should be "
  13566. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13567. }
  13568. #endif
  13569. TEST(HostAndPortPropertiesTest, NoSSL) {
  13570. httplib::Client cli("www.google.com", 1234);
  13571. ASSERT_EQ("www.google.com", cli.host());
  13572. ASSERT_EQ(1234, cli.port());
  13573. }
  13574. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13575. httplib::Client cli("www.google.com:1234");
  13576. ASSERT_EQ("www.google.com", cli.host());
  13577. ASSERT_EQ(1234, cli.port());
  13578. }
  13579. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13580. // Port number that overflows int — should not crash, client becomes invalid
  13581. httplib::Client cli("http://www.google.com:99999999999999999999");
  13582. ASSERT_FALSE(cli.is_valid());
  13583. }
  13584. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13585. // Port 99999 exceeds valid range (1-65535) — should not crash
  13586. httplib::Client cli("http://www.google.com:99999");
  13587. ASSERT_FALSE(cli.is_valid());
  13588. auto res = cli.Get("/");
  13589. EXPECT_FALSE(res);
  13590. EXPECT_EQ(Error::Connection, res.error());
  13591. }
  13592. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13593. httplib::Client cli("http://user:pass@localhost:1234");
  13594. ASSERT_FALSE(cli.is_valid());
  13595. EXPECT_FALSE(cli.Get("/"));
  13596. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13597. }
  13598. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13599. httplib::Client cli("http://www.google.com:80abc");
  13600. ASSERT_FALSE(cli.is_valid());
  13601. }
  13602. #ifdef CPPHTTPLIB_SSL_ENABLED
  13603. TEST(HostAndPortPropertiesTest, SSL) {
  13604. httplib::SSLClient cli("www.google.com");
  13605. ASSERT_EQ("www.google.com", cli.host());
  13606. ASSERT_EQ(443, cli.port());
  13607. }
  13608. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13609. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13610. std::string cert;
  13611. read_file(CA_CERT_FILE, cert);
  13612. httplib::SSLClient httplib_client("www.google.com");
  13613. // Load CA store first time
  13614. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13615. // Load CA store second time (update)
  13616. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13617. // Verify client is still valid and can make connections
  13618. httplib_client.enable_server_certificate_verification(true);
  13619. auto res = httplib_client.Get("/");
  13620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13621. // Google may return 200 or 301 depending on various factors
  13622. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13623. res->status == StatusCode::MovedPermanently_301);
  13624. }
  13625. TEST(SSLClientTest, ServerNameIndication_Online) {
  13626. auto host = "httpbingo.org";
  13627. auto path = std::string{"/get"};
  13628. SSLClient cli(host, 443);
  13629. auto res = cli.Get(path);
  13630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13631. ASSERT_EQ(StatusCode::OK_200, res->status);
  13632. }
  13633. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13634. // Use a site that will cause SSL verification failure due to self-signed cert
  13635. SSLClient cli("self-signed.badssl.com", 443);
  13636. cli.enable_server_certificate_verification(true);
  13637. auto res = cli.Get("/");
  13638. ASSERT_TRUE(!res);
  13639. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13640. // Verify backend error is captured for SSLServerVerification
  13641. // This occurs when certificate verification fails
  13642. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13643. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13644. EXPECT_NE(0UL, res.ssl_backend_error());
  13645. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13646. res.ssl_error());
  13647. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13648. #if !defined(_WIN32) || \
  13649. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13650. // On non-Windows or when Windows Schannel is disabled, the error comes
  13651. // from OpenSSL's verification
  13652. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13653. res.ssl_backend_error());
  13654. #endif
  13655. #endif
  13656. }
  13657. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13658. // Use a site where hostname doesn't match the certificate
  13659. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13660. SSLClient cli("wrong.host.badssl.com", 443);
  13661. cli.enable_server_certificate_verification(true);
  13662. cli.enable_server_hostname_verification(true);
  13663. auto res = cli.Get("/");
  13664. ASSERT_TRUE(!res);
  13665. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13666. // Verify backend error is captured for hostname verification failure
  13667. EXPECT_NE(0UL, res.ssl_backend_error());
  13668. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13669. res.ssl_error());
  13670. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13671. #if !defined(_WIN32) || \
  13672. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13673. // On non-Windows or when Windows Schannel is disabled, the error comes
  13674. // from OpenSSL's hostname verification
  13675. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13676. res.ssl_backend_error());
  13677. #endif
  13678. #endif
  13679. }
  13680. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13681. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13682. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13683. SSLClient cli("www.google.com", 443);
  13684. cli.enable_server_certificate_verification(true);
  13685. auto res = cli.Get("/");
  13686. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13687. }
  13688. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13689. SSLClient cli("www.google.com", 443);
  13690. cli.enable_server_certificate_verification(true);
  13691. cli.enable_windows_certificate_verification(false);
  13692. auto res = cli.Get("/");
  13693. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13694. }
  13695. // The server sends an intermediate cross-signed by a root Windows trusts,
  13696. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13697. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13698. SSLClient cli("accounts.spotify.com", 443);
  13699. auto res = cli.Get("/");
  13700. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13701. << " ssl_backend_error=" << res.ssl_backend_error();
  13702. }
  13703. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13704. // policy status, which no backend reports for a self-signed certificate.
  13705. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13706. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13707. ASSERT_TRUE(svr.is_valid());
  13708. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13709. auto se = detail::scope_exit([&] {
  13710. svr.stop();
  13711. t.join();
  13712. ASSERT_FALSE(svr.is_running());
  13713. });
  13714. svr.wait_until_ready();
  13715. SSLClient cli("127.0.0.1", PORT);
  13716. cli.set_connection_timeout(30);
  13717. auto res = cli.Get("/");
  13718. ASSERT_FALSE(res);
  13719. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13720. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13721. }
  13722. #endif
  13723. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13724. Client cli("https://google.com");
  13725. auto res = cli.Get("/");
  13726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13727. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13728. }
  13729. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13730. SSLClient cli("google.com");
  13731. cli.set_ca_cert_path(CA_CERT_FILE);
  13732. auto res = cli.Get("/");
  13733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13734. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13735. }
  13736. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13737. SSLClient cli("google.com");
  13738. cli.enable_server_certificate_verification(true);
  13739. cli.set_ca_cert_path("hello");
  13740. auto res = cli.Get("/");
  13741. ASSERT_TRUE(!res);
  13742. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13743. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13744. // should be set
  13745. EXPECT_EQ(0, res.ssl_error());
  13746. // Verify backend error is captured for SSLLoadingCerts
  13747. // This error occurs when loading CA certificates fails
  13748. EXPECT_NE(0UL, res.ssl_backend_error());
  13749. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13750. // OpenSSL specific error codes:
  13751. // > openssl errstr 0x80000002
  13752. // error:80000002:system library::No such file or directory
  13753. // > openssl errstr 0xA000126
  13754. // error:0A000126:SSL routines::unexpected eof while reading
  13755. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13756. res.ssl_backend_error() == 0xA000126);
  13757. #endif
  13758. }
  13759. TEST(SSLClientTest, ServerCertificateVerification4) {
  13760. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13761. ASSERT_TRUE(svr.is_valid());
  13762. svr.Get("/test", [&](const Request &, Response &res) {
  13763. res.set_content("test", "text/plain");
  13764. svr.stop();
  13765. ASSERT_TRUE(true);
  13766. });
  13767. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13768. auto se = detail::scope_exit([&] {
  13769. t.join();
  13770. ASSERT_FALSE(svr.is_running());
  13771. });
  13772. svr.wait_until_ready();
  13773. SSLClient cli("127.0.0.1", PORT);
  13774. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13775. cli.enable_server_certificate_verification(true);
  13776. cli.set_connection_timeout(30);
  13777. auto res = cli.Get("/test");
  13778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13779. ASSERT_EQ(StatusCode::OK_200, res->status);
  13780. }
  13781. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13782. std::string cert;
  13783. read_file(CA_CERT_FILE, cert);
  13784. SSLClient cli("google.com");
  13785. cli.load_ca_cert_store(cert.data(), cert.size());
  13786. const auto res = cli.Get("/");
  13787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13788. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13789. }
  13790. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13791. // clang-format off
  13792. static constexpr char cert[] =
  13793. "GlobalSign Root CA\n"
  13794. "==================\n"
  13795. "-----BEGIN CERTIFICATE-----\n"
  13796. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13797. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13798. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13799. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13800. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13801. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13802. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13803. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13804. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13805. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13806. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13807. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13808. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13809. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13810. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13811. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13812. "-----END CERTIFICATE-----\n";
  13813. // clang-format on
  13814. SSLClient cli("google.com");
  13815. cli.load_ca_cert_store(cert, sizeof(cert));
  13816. const auto res = cli.Get("/");
  13817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13818. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13819. }
  13820. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13821. SSLClient cli("www.youtube.com");
  13822. cli.set_ca_cert_path(CA_CERT_FILE);
  13823. cli.enable_server_certificate_verification(true);
  13824. cli.set_follow_location(true);
  13825. auto res = cli.Get("/");
  13826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13827. ASSERT_EQ(StatusCode::OK_200, res->status);
  13828. }
  13829. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13830. SSLClient cli("wWw.YouTube.Com");
  13831. cli.set_ca_cert_path(CA_CERT_FILE);
  13832. cli.enable_server_certificate_verification(true);
  13833. cli.enable_server_hostname_verification(true);
  13834. cli.set_follow_location(true);
  13835. auto res = cli.Get("/");
  13836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13837. ASSERT_EQ(StatusCode::OK_200, res->status);
  13838. }
  13839. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13840. SSLClient cli("gOoGlE.COm");
  13841. cli.enable_server_certificate_verification(true);
  13842. cli.enable_server_hostname_verification(true);
  13843. cli.set_follow_location(true);
  13844. auto res = cli.Get("/");
  13845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13846. ASSERT_EQ(StatusCode::OK_200, res->status);
  13847. }
  13848. TEST(SSLClientTest, Issue2004_Online) {
  13849. Client client("https://google.com");
  13850. client.set_follow_location(true);
  13851. auto res = client.Get("/");
  13852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13853. ASSERT_EQ(StatusCode::OK_200, res->status);
  13854. auto body = res->body;
  13855. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13856. }
  13857. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13858. // Create SSLClient with invalid cert/key to make is_valid() return false
  13859. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13860. "nonexistent_key.pem");
  13861. // is_valid() should be false due to cert loading failure
  13862. ASSERT_FALSE(cli.is_valid());
  13863. auto res = cli.Get("/");
  13864. ASSERT_FALSE(res);
  13865. EXPECT_EQ(Error::SSLConnection, res.error());
  13866. }
  13867. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13868. // Test for Issue #2251: SSL error not properly reported when client cert
  13869. // and key paths are swapped or mismatched
  13870. // This simulates the scenario where user accidentally swaps the cert and key
  13871. // files
  13872. // Using client cert file as private key and vice versa (completely wrong)
  13873. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13874. // Should fail validation due to cert/key mismatch
  13875. ASSERT_FALSE(cli.is_valid());
  13876. // Attempt to make a request should fail with proper error
  13877. auto res = cli.Get("/");
  13878. ASSERT_FALSE(res);
  13879. EXPECT_EQ(Error::SSLConnection, res.error());
  13880. // SSL error should be recorded in the Result object (this is the key fix for
  13881. // Issue #2251)
  13882. auto backend_error = res.ssl_backend_error();
  13883. EXPECT_NE(0u, backend_error);
  13884. }
  13885. // Tests cert/key mismatch detection at the TLS context level
  13886. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13887. // Test that using mismatched cert/key causes connection failure.
  13888. // We verify this at the SSLClient level rather than through internal
  13889. // TLS API functions.
  13890. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13891. cli.enable_server_certificate_verification(false);
  13892. cli.set_connection_timeout(2);
  13893. // The mismatch should cause a connection or handshake error
  13894. auto res = cli.Get("/test");
  13895. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13896. // Either way, the request should fail
  13897. EXPECT_FALSE(res);
  13898. }
  13899. #endif
  13900. #if 0
  13901. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13902. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13903. ASSERT_TRUE(cli != nullptr);
  13904. cli->set_address_family(AF_INET6);
  13905. cli->set_interface("en0");
  13906. auto res = cli->Get("/get");
  13907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13908. ASSERT_EQ(StatusCode::OK_200, res->status);
  13909. }
  13910. #endif
  13911. // Client certificate tests - work with all TLS backends
  13912. #ifdef CPPHTTPLIB_SSL_ENABLED
  13913. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13914. void ClientCertPresent(
  13915. const std::string &client_cert_file,
  13916. const std::string &client_private_key_file,
  13917. const std::string &client_encrypted_private_key_pass = std::string(),
  13918. const ClientCertServerSetup &setup = nullptr) {
  13919. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13920. ASSERT_TRUE(svr.is_valid());
  13921. if (setup) { setup(svr); }
  13922. svr.Get("/test", [&](const Request &req, Response &res) {
  13923. res.set_content("test", "text/plain");
  13924. auto cert = req.peer_cert();
  13925. ASSERT_TRUE(static_cast<bool>(cert));
  13926. std::string common_name = cert.subject_cn();
  13927. EXPECT_EQ("Common Name", common_name);
  13928. });
  13929. auto port = svr.bind_to_any_port(HOST);
  13930. ASSERT_LT(0, port);
  13931. thread t = thread([&]() { svr.listen_after_bind(); });
  13932. auto se = detail::scope_exit([&] {
  13933. svr.stop();
  13934. t.join();
  13935. ASSERT_FALSE(svr.is_running());
  13936. });
  13937. svr.wait_until_ready();
  13938. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13939. client_encrypted_private_key_pass);
  13940. cli.enable_server_certificate_verification(false);
  13941. cli.set_connection_timeout(30);
  13942. auto res = cli.Get("/test");
  13943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13944. ASSERT_EQ(StatusCode::OK_200, res->status);
  13945. }
  13946. TEST(SSLClientServerTest, ClientCertPresent) {
  13947. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13948. }
  13949. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13950. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13951. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13952. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13953. }
  13954. // Expects svr, which must require client certificates, to reject a client
  13955. // that has none
  13956. void RejectsClientWithoutCert(SSLServer &svr) {
  13957. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13958. auto port = svr.bind_to_any_port(HOST);
  13959. ASSERT_LT(0, port);
  13960. thread t = thread([&]() { svr.listen_after_bind(); });
  13961. auto se = detail::scope_exit([&] {
  13962. svr.stop();
  13963. t.join();
  13964. ASSERT_FALSE(svr.is_running());
  13965. });
  13966. svr.wait_until_ready();
  13967. SSLClient cli(HOST, port);
  13968. cli.set_connection_timeout(30);
  13969. // Skip the server certificate check, so that the request fails because the
  13970. // client certificate is missing rather than because cert.pem is not trusted
  13971. cli.enable_server_certificate_verification(false);
  13972. auto res = cli.Get("/test");
  13973. ASSERT_FALSE(res);
  13974. // The server rejects the client during the handshake, or on TLS 1.3 right
  13975. // after it, which the client notices on its first write or read
  13976. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13977. res.error() == Error::Write || res.error() == Error::Read)
  13978. << to_string(res.error());
  13979. if (res.error() == Error::SSLConnection) {
  13980. EXPECT_NE(0UL, res.ssl_backend_error());
  13981. }
  13982. // A rejection noticed on the write keeps the TLS error the write hit
  13983. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13984. }
  13985. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13987. ASSERT_TRUE(svr.is_valid());
  13988. if (setup) { setup(svr); }
  13989. RejectsClientWithoutCert(svr);
  13990. }
  13991. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13992. // A server that requires client certificates must keep requiring them after
  13993. // setup changes it, and keep accepting a client that has one
  13994. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13995. ClientCertMissing(setup);
  13996. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13997. setup);
  13998. }
  13999. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14000. ClientCertStillRequired([](SSLServer &svr) {
  14001. ASSERT_TRUE(tls::set_verify_callback(
  14002. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14003. });
  14004. }
  14005. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14006. ClientCertStillRequired([](SSLServer &svr) {
  14007. ASSERT_TRUE(tls::set_verify_callback(
  14008. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14009. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14010. });
  14011. }
  14012. // The client verifies the server certificate during the handshake, so a
  14013. // server that fails the check never gets the client certificate, even when a
  14014. // verifier of the client's own accepts it
  14015. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14016. struct Case {
  14017. const char *trusted_ca;
  14018. const char *host;
  14019. Error error;
  14020. };
  14021. // cert2.pem names localhost: the first client does not trust it, and the
  14022. // second trusts it but asks for another name
  14023. for (const auto &c :
  14024. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14025. Case{SERVER_CERT2_FILE, "example.com",
  14026. Error::SSLServerHostnameVerification}}) {
  14027. for (auto with_verifier : {false, true}) {
  14028. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14029. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14030. CLIENT_CA_CERT_FILE);
  14031. ASSERT_TRUE(svr.is_valid());
  14032. std::atomic<bool> got_client_cert{false};
  14033. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14034. [&](const tls::VerifyContext &) {
  14035. got_client_cert = true;
  14036. return true;
  14037. }));
  14038. auto port = svr.bind_to_any_port("127.0.0.1");
  14039. ASSERT_LT(0, port);
  14040. thread t = thread([&] { svr.listen_after_bind(); });
  14041. svr.wait_until_ready();
  14042. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14043. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14044. cli.set_ca_cert_path(c.trusted_ca);
  14045. if (with_verifier) {
  14046. cli.set_server_certificate_verifier(
  14047. [](const tls::VerifyContext &) { return true; });
  14048. }
  14049. auto res = cli.Get("/");
  14050. EXPECT_FALSE(res);
  14051. EXPECT_EQ(c.error, res.error());
  14052. svr.stop();
  14053. t.join();
  14054. EXPECT_FALSE(got_client_cert);
  14055. }
  14056. }
  14057. }
  14058. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14059. std::string cert_pem, key_pem, ca_pem;
  14060. read_file(SERVER_CERT_FILE, cert_pem);
  14061. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14062. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14063. ASSERT_TRUE(
  14064. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14065. }
  14066. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14067. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14068. ASSERT_TRUE(svr.is_valid());
  14069. UpdateCertsPemWithClientCA(svr);
  14070. RejectsClientWithoutCert(svr);
  14071. }
  14072. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14073. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14074. }
  14075. // A TLS error from one request must not show up in a later request's Result
  14076. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14078. ASSERT_TRUE(svr.is_valid());
  14079. svr.Get("/test", [](const Request &, Response &res) {
  14080. res.set_content("test", "text/plain");
  14081. });
  14082. auto port = svr.bind_to_any_port(HOST);
  14083. ASSERT_LT(0, port);
  14084. thread t = thread([&]() { svr.listen_after_bind(); });
  14085. auto se = detail::scope_exit([&] {
  14086. svr.stop();
  14087. t.join();
  14088. ASSERT_FALSE(svr.is_running());
  14089. });
  14090. svr.wait_until_ready();
  14091. SSLClient cli(HOST, port);
  14092. cli.set_connection_timeout(30);
  14093. cli.enable_server_hostname_verification(false);
  14094. // cert.pem is not trusted, so the handshake fails
  14095. ASSERT_FALSE(cli.Get("/test"));
  14096. cli.enable_server_certificate_verification(false);
  14097. auto res = cli.Get("/test");
  14098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14099. EXPECT_EQ(0, res.ssl_error());
  14100. EXPECT_EQ(0UL, res.ssl_backend_error());
  14101. }
  14102. // PEM memory-based constructor tests (works with all TLS backends).
  14103. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14104. // terminator after it.
  14105. void PemMemoryClientCertPresent(
  14106. const std::string &client_cert_file,
  14107. const std::string &client_private_key_file,
  14108. const std::string &client_encrypted_private_key_pass = std::string(),
  14109. bool exact_size = false) {
  14110. // Read PEM files into memory
  14111. std::string server_cert_pem, server_key_pem;
  14112. std::string client_ca_pem;
  14113. std::string client_cert_pem, client_key_pem;
  14114. read_file(SERVER_CERT_FILE, server_cert_pem);
  14115. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14116. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14117. read_file(client_cert_file, client_cert_pem);
  14118. read_file(client_private_key_file, client_key_pem);
  14119. std::list<std::vector<char>> exact_copies;
  14120. auto data = [&](const std::string &pem) -> const char * {
  14121. if (!exact_size) { return pem.c_str(); }
  14122. exact_copies.emplace_back(pem.begin(), pem.end());
  14123. return exact_copies.back().data();
  14124. };
  14125. // Create server with PEM memory
  14126. SSLServer::PemMemory server_pem = {
  14127. data(server_cert_pem),
  14128. server_cert_pem.size(),
  14129. data(server_key_pem),
  14130. server_key_pem.size(),
  14131. data(client_ca_pem),
  14132. client_ca_pem.size(),
  14133. nullptr // no password for server key
  14134. };
  14135. SSLServer svr(server_pem);
  14136. ASSERT_TRUE(svr.is_valid());
  14137. svr.Get("/test", [&](const Request &req, Response &res) {
  14138. res.set_content("test", "text/plain");
  14139. auto cert = req.peer_cert();
  14140. ASSERT_TRUE(static_cast<bool>(cert));
  14141. EXPECT_EQ("Common Name", cert.subject_cn());
  14142. });
  14143. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14144. auto se = detail::scope_exit([&] {
  14145. svr.stop();
  14146. t.join();
  14147. ASSERT_FALSE(svr.is_running());
  14148. });
  14149. svr.wait_until_ready();
  14150. // Create client with PEM memory
  14151. const char *password = client_encrypted_private_key_pass.empty()
  14152. ? nullptr
  14153. : client_encrypted_private_key_pass.c_str();
  14154. SSLClient::PemMemory client_pem = {
  14155. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14156. client_key_pem.size(), password};
  14157. SSLClient cli(HOST, PORT, client_pem);
  14158. cli.enable_server_certificate_verification(false);
  14159. cli.set_connection_timeout(30);
  14160. auto res = cli.Get("/test");
  14161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14162. ASSERT_EQ(StatusCode::OK_200, res->status);
  14163. }
  14164. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14165. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14166. }
  14167. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14168. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14169. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14170. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14171. }
  14172. // A server built from PEM memory with a client CA requires client certificates,
  14173. // also when the CA is a NUL-terminated string passed with a length of 0
  14174. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14175. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14176. read_file(SERVER_CERT_FILE, server_cert_pem);
  14177. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14178. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14179. SSLServer::PemMemory server_pem = {
  14180. server_cert_pem.c_str(),
  14181. server_cert_pem.size(),
  14182. server_key_pem.c_str(),
  14183. server_key_pem.size(),
  14184. client_ca_pem.c_str(),
  14185. client_ca_pem.size(),
  14186. nullptr // no password for server key
  14187. };
  14188. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14189. SCOPED_TRACE(client_ca_pem_len);
  14190. server_pem.client_ca_pem_len = client_ca_pem_len;
  14191. SSLServer svr(server_pem);
  14192. ASSERT_TRUE(svr.is_valid());
  14193. RejectsClientWithoutCert(svr);
  14194. }
  14195. // An empty CA fails to load instead of turning the check off
  14196. server_pem.client_ca_pem = "";
  14197. server_pem.client_ca_pem_len = 0;
  14198. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14199. }
  14200. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14201. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14202. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14203. true);
  14204. }
  14205. // A length shorter than the PEM cuts it short, so it no longer loads
  14206. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14207. std::string cert, key;
  14208. read_file(SERVER_CERT_FILE, cert);
  14209. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14210. for (auto cut_cert : {true, false}) {
  14211. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14212. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14213. SSLServer::PemMemory server_pem = {
  14214. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14215. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14216. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14217. key_len, nullptr};
  14218. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14219. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14220. key.c_str(), key_len, nullptr};
  14221. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14222. }
  14223. }
  14224. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14225. class NoListenSSLServer : public SSLServer {
  14226. public:
  14227. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14228. const char *client_ca_cert_file_path,
  14229. const char *client_ca_cert_dir_path = nullptr)
  14230. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14231. client_ca_cert_dir_path),
  14232. stop_(false) {}
  14233. std::atomic_bool stop_;
  14234. private:
  14235. bool process_and_close_socket(socket_t /*sock*/) override {
  14236. // Don't create SSL context
  14237. while (!stop_.load()) {
  14238. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14239. }
  14240. return true;
  14241. }
  14242. };
  14243. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14244. CLIENT_CA_CERT_FILE);
  14245. ASSERT_TRUE(svr.is_valid());
  14246. svr.Get("/test", [&](const Request &, Response &res) {
  14247. res.set_content("test", "text/plain");
  14248. });
  14249. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop_ = true;
  14252. svr.stop();
  14253. t.join();
  14254. ASSERT_FALSE(svr.is_running());
  14255. });
  14256. svr.wait_until_ready();
  14257. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14258. cli.enable_server_certificate_verification(false);
  14259. cli.set_connection_timeout(1);
  14260. auto res = cli.Get("/test");
  14261. ASSERT_TRUE(!res);
  14262. EXPECT_EQ(Error::SSLConnection, res.error());
  14263. // Timeout results in WantRead error code (maps to backend-specific value)
  14264. EXPECT_NE(0, res.ssl_error());
  14265. }
  14266. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14267. // Test SSLServer with client certificate verification using the standard
  14268. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14269. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14270. CLIENT_CA_CERT_DIR);
  14271. ASSERT_TRUE(svr.is_valid());
  14272. svr.Get("/test", [&](const Request &req, Response &res) {
  14273. res.set_content("test", "text/plain");
  14274. auto cert = req.peer_cert();
  14275. ASSERT_TRUE(static_cast<bool>(cert));
  14276. auto common_name = cert.subject_cn();
  14277. EXPECT_EQ("Common Name", common_name);
  14278. });
  14279. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14280. auto se = detail::scope_exit([&] {
  14281. svr.stop();
  14282. t.join();
  14283. ASSERT_FALSE(svr.is_running());
  14284. });
  14285. svr.wait_until_ready();
  14286. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14287. cli.enable_server_certificate_verification(false);
  14288. cli.set_connection_timeout(30);
  14289. auto res = cli.Get("/test");
  14290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14291. ASSERT_EQ(StatusCode::OK_200, res->status);
  14292. }
  14293. // Test verify_hostname on every backend: a host is named by a SAN only
  14294. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14295. using namespace httplib::tls;
  14296. // We need a running server to test against
  14297. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14298. ASSERT_TRUE(svr.is_valid());
  14299. svr.Get("/test", [](const Request &, Response &res) {
  14300. res.set_content("ok", "text/plain");
  14301. });
  14302. thread t([&]() { svr.listen(HOST, PORT); });
  14303. auto se = detail::scope_exit([&] {
  14304. svr.stop();
  14305. t.join();
  14306. });
  14307. svr.wait_until_ready();
  14308. bool verify_callback_called = false;
  14309. bool verify_result_wrong = false;
  14310. SSLClient cli(HOST, PORT);
  14311. cli.enable_server_certificate_verification(true);
  14312. cli.set_ca_cert_path(CA_CERT_FILE);
  14313. cli.set_connection_timeout(5);
  14314. // Note: Test certificate has CN="Common Name", not "localhost"
  14315. bool verify_result_cn = false;
  14316. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14317. verify_callback_called = true;
  14318. if (!ctx.cert) return false;
  14319. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14320. verify_result_cn = ctx.check_hostname("Common Name");
  14321. // Test 2: wrong hostname should not match
  14322. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14323. return true; // Accept for the purpose of this test
  14324. });
  14325. auto res = cli.Get("/test");
  14326. // The request may succeed or fail depending on cert configuration
  14327. // but the callback should have been called
  14328. ASSERT_TRUE(verify_callback_called)
  14329. << "Verify callback should have been called";
  14330. EXPECT_FALSE(verify_result_cn)
  14331. << "verify_hostname must not match the certificate CN (no SAN)";
  14332. // Wrong hostname should not match
  14333. EXPECT_FALSE(verify_result_wrong)
  14334. << "verify_hostname should not match 'wronghost.example.com'";
  14335. }
  14336. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14337. // backend verifies it.
  14338. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14339. // Certificate CN is "localhost" and it carries no SAN.
  14340. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14341. ASSERT_TRUE(svr.is_valid());
  14342. svr.Get("/test", [](const Request &, Response &res) {
  14343. res.set_content("ok", "text/plain");
  14344. });
  14345. auto port = svr.bind_to_any_port(HOST);
  14346. thread t([&]() { svr.listen_after_bind(); });
  14347. auto se = detail::scope_exit([&] {
  14348. svr.stop();
  14349. t.join();
  14350. });
  14351. svr.wait_until_ready();
  14352. SSLClient cli("localhost", port);
  14353. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14354. cli.enable_server_certificate_verification(true);
  14355. cli.set_connection_timeout(5);
  14356. auto res = cli.Get("/test");
  14357. ASSERT_FALSE(res);
  14358. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14359. // The same certificate is accepted once host name verification is off, so the
  14360. // failure above is the host name and not the chain.
  14361. cli.enable_server_hostname_verification(false);
  14362. res = cli.Get("/test");
  14363. ASSERT_TRUE(res) << to_string(res.error());
  14364. EXPECT_EQ(StatusCode::OK_200, res->status);
  14365. }
  14366. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14367. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14368. // X509_check_ip behavior and must hold for every backend.
  14369. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14370. using namespace httplib::tls;
  14371. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14372. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14373. ASSERT_TRUE(svr.is_valid());
  14374. svr.Get("/test", [](const Request &, Response &res) {
  14375. res.set_content("ok", "text/plain");
  14376. });
  14377. thread t([&]() { svr.listen(HOST, PORT); });
  14378. auto se = detail::scope_exit([&] {
  14379. svr.stop();
  14380. t.join();
  14381. });
  14382. svr.wait_until_ready();
  14383. bool verify_callback_called = false;
  14384. bool ip_matched_via_cn = true;
  14385. SSLClient cli(HOST, PORT);
  14386. cli.enable_server_certificate_verification(true);
  14387. cli.set_ca_cert_path(CA_CERT_FILE);
  14388. cli.set_connection_timeout(5);
  14389. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14390. verify_callback_called = true;
  14391. if (!ctx.cert) return false;
  14392. // The IP appears only in the CN, so it must NOT be accepted.
  14393. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14394. return true; // Accept for the purpose of this test
  14395. });
  14396. cli.Get("/test");
  14397. ASSERT_TRUE(verify_callback_called)
  14398. << "Verify callback should have been called";
  14399. EXPECT_FALSE(ip_matched_via_cn)
  14400. << "An IP host must not be authenticated via the certificate CN";
  14401. }
  14402. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14403. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14404. using namespace httplib::tls;
  14405. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14406. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14407. ASSERT_TRUE(svr.is_valid());
  14408. svr.Get("/test", [](const Request &, Response &res) {
  14409. res.set_content("ok", "text/plain");
  14410. });
  14411. thread t([&]() { svr.listen(HOST, PORT); });
  14412. auto se = detail::scope_exit([&] {
  14413. svr.stop();
  14414. t.join();
  14415. });
  14416. svr.wait_until_ready();
  14417. bool verify_callback_called = false;
  14418. bool san_matched = false;
  14419. bool wrong_ipv6_matched = true;
  14420. bool cn_ipv6_matched = true;
  14421. SSLClient cli(HOST, PORT);
  14422. cli.enable_server_certificate_verification(true);
  14423. cli.set_ca_cert_path(CA_CERT_FILE);
  14424. cli.set_connection_timeout(5);
  14425. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14426. verify_callback_called = true;
  14427. if (!ctx.cert) return false;
  14428. // Matches the IPv6 iPAddress SAN.
  14429. san_matched = ctx.check_hostname("2001:db8::1");
  14430. // A different IPv6 address must not match.
  14431. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14432. // "::1" lives only in the CN, so it must not be accepted.
  14433. cn_ipv6_matched = ctx.check_hostname("::1");
  14434. return true; // Accept for the purpose of this test
  14435. });
  14436. cli.Get("/test");
  14437. ASSERT_TRUE(verify_callback_called)
  14438. << "Verify callback should have been called";
  14439. EXPECT_TRUE(san_matched)
  14440. << "verify_hostname should match an IPv6 iPAddress SAN";
  14441. EXPECT_FALSE(wrong_ipv6_matched)
  14442. << "verify_hostname should not match a non-matching IPv6 address";
  14443. EXPECT_FALSE(cn_ipv6_matched)
  14444. << "An IPv6 host must not be authenticated via the certificate CN";
  14445. }
  14446. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14447. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14448. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14449. using namespace httplib::tls;
  14450. // SANs: DNS:a.zz, IP:42.46.122.122
  14451. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14452. ASSERT_TRUE(svr.is_valid());
  14453. svr.Get("/test", [](const Request &, Response &res) {
  14454. res.set_content("ok", "text/plain");
  14455. });
  14456. auto port = svr.bind_to_any_port(HOST);
  14457. thread t([&]() { svr.listen_after_bind(); });
  14458. auto se = detail::scope_exit([&] {
  14459. svr.stop();
  14460. t.join();
  14461. });
  14462. svr.wait_until_ready();
  14463. bool verify_callback_called = false;
  14464. bool dns_san_matched = false;
  14465. bool ip_san_matched = false;
  14466. bool ip_matched_via_dns_san = true;
  14467. bool dns_matched_via_ip_san = true;
  14468. bool cn_matched_next_to_dns_san = true;
  14469. SSLClient cli(HOST, port);
  14470. cli.enable_server_certificate_verification(true);
  14471. cli.set_ca_cert_path(CA_CERT_FILE);
  14472. cli.set_connection_timeout(5);
  14473. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14474. verify_callback_called = true;
  14475. if (!ctx.cert) return false;
  14476. dns_san_matched = ctx.check_hostname("a.zz");
  14477. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14478. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14479. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14480. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14481. return true; // Accept for the purpose of this test
  14482. });
  14483. cli.Get("/test");
  14484. ASSERT_TRUE(verify_callback_called)
  14485. << "Verify callback should have been called";
  14486. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14487. EXPECT_TRUE(ip_san_matched)
  14488. << "verify_hostname should match an iPAddress SAN";
  14489. EXPECT_FALSE(ip_matched_via_dns_san)
  14490. << "An IP host must not be authenticated via a dNSName SAN";
  14491. EXPECT_FALSE(dns_matched_via_ip_san)
  14492. << "A DNS host must not be authenticated via an iPAddress SAN";
  14493. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14494. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14495. }
  14496. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14497. // "www.*.example.test" names one host and not every host under example.test.
  14498. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14499. using namespace httplib::tls;
  14500. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14501. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14502. ASSERT_TRUE(svr.is_valid());
  14503. svr.Get("/test", [](const Request &, Response &res) {
  14504. res.set_content("ok", "text/plain");
  14505. });
  14506. auto port = svr.bind_to_any_port(HOST);
  14507. thread t([&]() { svr.listen_after_bind(); });
  14508. auto se = detail::scope_exit([&] {
  14509. svr.stop();
  14510. t.join();
  14511. });
  14512. svr.wait_until_ready();
  14513. bool verify_callback_called = false;
  14514. bool leftmost_wildcard_matched = false;
  14515. bool wildcard_spanned_labels = true;
  14516. bool inner_wildcard_matched = true;
  14517. SSLClient cli(HOST, port);
  14518. cli.enable_server_certificate_verification(true);
  14519. cli.set_ca_cert_path(CA_CERT_FILE);
  14520. cli.set_connection_timeout(5);
  14521. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14522. verify_callback_called = true;
  14523. if (!ctx.cert) return false;
  14524. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14525. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14526. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14527. return true; // Accept for the purpose of this test
  14528. });
  14529. cli.Get("/test");
  14530. ASSERT_TRUE(verify_callback_called)
  14531. << "Verify callback should have been called";
  14532. EXPECT_TRUE(leftmost_wildcard_matched)
  14533. << "A leftmost wildcard should match a single label";
  14534. EXPECT_FALSE(wildcard_spanned_labels)
  14535. << "A wildcard label must not match more than one label";
  14536. EXPECT_FALSE(inner_wildcard_matched)
  14537. << "A wildcard outside the leftmost label must not be honoured";
  14538. }
  14539. // sans() must report each SAN entry under its own type.
  14540. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14541. using namespace httplib::tls;
  14542. // SANs: DNS:a.zz, IP:42.46.122.122
  14543. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14544. ASSERT_TRUE(svr.is_valid());
  14545. svr.Get("/test", [](const Request &, Response &res) {
  14546. res.set_content("ok", "text/plain");
  14547. });
  14548. auto port = svr.bind_to_any_port(HOST);
  14549. thread t([&]() { svr.listen_after_bind(); });
  14550. auto se = detail::scope_exit([&] {
  14551. svr.stop();
  14552. t.join();
  14553. });
  14554. svr.wait_until_ready();
  14555. bool verify_callback_called = false;
  14556. std::vector<SanEntry> sans;
  14557. SSLClient cli(HOST, port);
  14558. cli.enable_server_certificate_verification(true);
  14559. cli.set_ca_cert_path(CA_CERT_FILE);
  14560. cli.set_connection_timeout(5);
  14561. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14562. verify_callback_called = true;
  14563. if (!ctx.cert) return false;
  14564. sans = ctx.sans();
  14565. return true; // Accept for the purpose of this test
  14566. });
  14567. cli.Get("/test");
  14568. ASSERT_TRUE(verify_callback_called)
  14569. << "Verify callback should have been called";
  14570. auto has_san = [&](SanType type, const std::string &value) {
  14571. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14572. return san.type == type && san.value == value;
  14573. });
  14574. };
  14575. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14576. << "sans() should report the dNSName SAN";
  14577. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14578. << "sans() should report the iPAddress SAN";
  14579. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14580. << "sans() must not report the dNSName SAN as an address";
  14581. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14582. << "sans() must not report the iPAddress SAN as a DNS name";
  14583. }
  14584. #endif
  14585. // mbedTLS-specific callback constructor test
  14586. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14587. #ifdef CPPHTTPLIB_SSL_ENABLED
  14588. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14590. ASSERT_TRUE(svr.is_valid());
  14591. // Set up a handler to verify client certificate is present
  14592. bool client_cert_verified = false;
  14593. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14594. // Verify that client certificate was provided
  14595. client_cert_verified = true;
  14596. res.set_content("success", "text/plain");
  14597. });
  14598. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14599. auto se = detail::scope_exit([&] {
  14600. svr.stop();
  14601. t.join();
  14602. ASSERT_FALSE(svr.is_running());
  14603. });
  14604. svr.wait_until_ready();
  14605. // Client with certificate
  14606. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14607. cli.enable_server_certificate_verification(false);
  14608. cli.set_connection_timeout(30);
  14609. auto res = cli.Get("/test");
  14610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14611. ASSERT_EQ(StatusCode::OK_200, res->status);
  14612. ASSERT_TRUE(client_cert_verified);
  14613. EXPECT_EQ("success", res->body);
  14614. }
  14615. #endif
  14616. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14617. // backends
  14618. #ifdef CPPHTTPLIB_SSL_ENABLED
  14619. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14620. using namespace httplib::tls;
  14621. // Test that when client CA cert file is provided,
  14622. // the server properly requests and validates client certificates
  14623. // Create a server with client authentication
  14624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14625. ASSERT_TRUE(svr.is_valid());
  14626. bool handler_called = false;
  14627. svr.Get("/test", [&](const Request &req, Response &res) {
  14628. handler_called = true;
  14629. // Verify that a client certificate was provided
  14630. auto cert = req.peer_cert();
  14631. ASSERT_TRUE(static_cast<bool>(cert));
  14632. // Get the issuer name
  14633. std::string issuer_str = cert.issuer_name();
  14634. ASSERT_FALSE(issuer_str.empty());
  14635. // The client certificate should be issued by our test CA
  14636. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14637. res.set_content("authenticated", "text/plain");
  14638. });
  14639. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14640. auto se = detail::scope_exit([&] {
  14641. svr.stop();
  14642. t.join();
  14643. ASSERT_FALSE(svr.is_running());
  14644. });
  14645. svr.wait_until_ready();
  14646. // Connect with a client certificate issued by the CA
  14647. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14648. cli.enable_server_certificate_verification(false);
  14649. cli.set_connection_timeout(30);
  14650. auto res = cli.Get("/test");
  14651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14652. ASSERT_EQ(StatusCode::OK_200, res->status);
  14653. ASSERT_TRUE(handler_called);
  14654. EXPECT_EQ("authenticated", res->body);
  14655. }
  14656. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14657. using namespace httplib::tls;
  14658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14659. ASSERT_TRUE(svr.is_valid());
  14660. svr.Get("/test", [](const Request &, Response &res) {
  14661. res.set_content("ok", "text/plain");
  14662. });
  14663. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14664. auto se = detail::scope_exit([&] {
  14665. svr.stop();
  14666. t.join();
  14667. });
  14668. svr.wait_until_ready();
  14669. SSLClient cli(HOST, PORT);
  14670. cli.enable_server_certificate_verification(false);
  14671. cli.set_connection_timeout(30);
  14672. bool cert_checked = false;
  14673. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14674. if (ctx.cert) {
  14675. auto sans = ctx.sans();
  14676. // Test certificate may or may not have SANs - just verify the API
  14677. // works If SANs exist, verify the types are valid
  14678. for (const auto &san : sans) {
  14679. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14680. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14681. san.type == SanType::OTHER);
  14682. EXPECT_FALSE(san.value.empty());
  14683. }
  14684. cert_checked = true;
  14685. }
  14686. return true;
  14687. });
  14688. auto res = cli.Get("/test");
  14689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14690. EXPECT_TRUE(cert_checked);
  14691. }
  14692. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14693. using namespace httplib::tls;
  14694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14695. ASSERT_TRUE(svr.is_valid());
  14696. svr.Get("/test", [](const Request &, Response &res) {
  14697. res.set_content("ok", "text/plain");
  14698. });
  14699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14700. auto se = detail::scope_exit([&] {
  14701. svr.stop();
  14702. t.join();
  14703. });
  14704. svr.wait_until_ready();
  14705. SSLClient cli(HOST, PORT);
  14706. cli.enable_server_certificate_verification(false);
  14707. cli.set_connection_timeout(30);
  14708. bool validity_checked = false;
  14709. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14710. if (ctx.cert) {
  14711. time_t not_before = 0, not_after = 0;
  14712. bool result = ctx.validity(not_before, not_after);
  14713. EXPECT_TRUE(result);
  14714. // Verify that not_before < now < not_after for a valid cert
  14715. time_t now = time(nullptr);
  14716. EXPECT_LT(not_before, now);
  14717. EXPECT_GT(not_after, now);
  14718. validity_checked = true;
  14719. }
  14720. return true;
  14721. });
  14722. auto res = cli.Get("/test");
  14723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14724. EXPECT_TRUE(validity_checked);
  14725. }
  14726. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14727. using namespace httplib::tls;
  14728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14729. ASSERT_TRUE(svr.is_valid());
  14730. svr.Get("/test", [](const Request &, Response &res) {
  14731. res.set_content("ok", "text/plain");
  14732. });
  14733. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14734. auto se = detail::scope_exit([&] {
  14735. svr.stop();
  14736. t.join();
  14737. });
  14738. svr.wait_until_ready();
  14739. SSLClient cli(HOST, PORT);
  14740. cli.enable_server_certificate_verification(false);
  14741. cli.set_connection_timeout(30);
  14742. bool serial_checked = false;
  14743. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14744. if (ctx.cert) {
  14745. std::string serial = ctx.serial();
  14746. EXPECT_FALSE(serial.empty());
  14747. // Serial should be a hex string
  14748. for (char c : serial) {
  14749. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14750. (c >= 'a' && c <= 'f'));
  14751. }
  14752. serial_checked = true;
  14753. }
  14754. return true;
  14755. });
  14756. auto res = cli.Get("/test");
  14757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14758. EXPECT_TRUE(serial_checked);
  14759. }
  14760. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14761. // Test 1: Valid CA file - no error should be recorded
  14762. {
  14763. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14764. CLIENT_CA_CERT_FILE);
  14765. ASSERT_TRUE(svr.is_valid());
  14766. // With valid setup, last_ssl_error should be 0
  14767. EXPECT_EQ(0, svr.ssl_last_error());
  14768. }
  14769. // Test 2: Invalid CA file content
  14770. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14771. {
  14772. // Create a temporary file with completely invalid content
  14773. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14774. {
  14775. std::ofstream ofs(temp_invalid_ca);
  14776. ofs << "This is not a certificate file at all\n";
  14777. ofs << "Just plain text content\n";
  14778. }
  14779. // Create server with invalid CA file
  14780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14781. // Clean up temporary file
  14782. std::remove(temp_invalid_ca);
  14783. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14784. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14785. // Note: SSL_CTX_load_verify_locations typically fails first,
  14786. // but our error handling code path is still exercised
  14787. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14788. }
  14789. }
  14790. TEST(VerifyCallbackTest, VerifyContextFields) {
  14791. using namespace httplib::tls;
  14792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14793. ASSERT_TRUE(svr.is_valid());
  14794. svr.Get("/test", [](const Request &, Response &res) {
  14795. res.set_content("ok", "text/plain");
  14796. });
  14797. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14798. auto se = detail::scope_exit([&] {
  14799. svr.stop();
  14800. t.join();
  14801. });
  14802. svr.wait_until_ready();
  14803. SSLClient cli(HOST, PORT);
  14804. cli.enable_server_certificate_verification(false);
  14805. cli.set_connection_timeout(30);
  14806. int callback_count = 0;
  14807. bool saw_leaf_cert = false;
  14808. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14809. if (ctx.cert) {
  14810. callback_count++;
  14811. // We should see at least one certificate (the leaf)
  14812. std::string cn = ctx.subject_cn();
  14813. if (!cn.empty()) { saw_leaf_cert = true; }
  14814. // Verify context fields are populated
  14815. EXPECT_NE(ctx.session, nullptr);
  14816. EXPECT_GE(ctx.depth, 0);
  14817. }
  14818. return true;
  14819. });
  14820. auto res = cli.Get("/test");
  14821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14822. EXPECT_GT(callback_count, 0);
  14823. EXPECT_TRUE(saw_leaf_cert);
  14824. }
  14825. // A verifier that accepts runs alongside the built-in verification, and is the
  14826. // only check once that is turned off.
  14827. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14828. using namespace httplib::tls;
  14829. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14830. ASSERT_TRUE(svr.is_valid());
  14831. svr.Get("/test", [](const Request &, Response &res) {
  14832. res.set_content("ok", "text/plain");
  14833. });
  14834. auto port = svr.bind_to_any_port(HOST);
  14835. thread t([&]() { svr.listen_after_bind(); });
  14836. auto se = detail::scope_exit([&] {
  14837. svr.stop();
  14838. t.join();
  14839. });
  14840. svr.wait_until_ready();
  14841. SSLClient cli(HOST, port);
  14842. cli.enable_server_hostname_verification(false);
  14843. auto calls = 0;
  14844. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14845. calls++;
  14846. return true;
  14847. });
  14848. // cert.pem is not trusted
  14849. auto res = cli.Get("/test");
  14850. ASSERT_FALSE(res);
  14851. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14852. EXPECT_GT(calls, 0);
  14853. cli.enable_server_certificate_verification(false);
  14854. res = cli.Get("/test");
  14855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14856. EXPECT_EQ("ok", res->body);
  14857. }
  14858. // A verifier belongs to the client that set it, not to the thread that set it.
  14859. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14860. using namespace httplib::tls;
  14861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14862. ASSERT_TRUE(svr.is_valid());
  14863. svr.Get("/test", [](const Request &, Response &res) {
  14864. res.set_content("ok", "text/plain");
  14865. });
  14866. auto port = svr.bind_to_any_port(HOST);
  14867. thread t([&]() { svr.listen_after_bind(); });
  14868. auto se = detail::scope_exit([&] {
  14869. svr.stop();
  14870. t.join();
  14871. });
  14872. svr.wait_until_ready();
  14873. auto rejecting_calls = 0;
  14874. SSLClient rejecting(HOST, port);
  14875. rejecting.enable_server_certificate_verification(false);
  14876. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14877. rejecting_calls++;
  14878. return false;
  14879. });
  14880. auto accepting_calls = 0;
  14881. SSLClient accepting(HOST, port);
  14882. accepting.enable_server_certificate_verification(false);
  14883. // Set on another thread than the requests below.
  14884. thread([&]() {
  14885. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14886. accepting_calls++;
  14887. return true;
  14888. });
  14889. }).join();
  14890. // Requested on another thread than the verifier was set on.
  14891. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14892. EXPECT_GT(rejecting_calls, 0);
  14893. auto res = accepting.Get("/test");
  14894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14895. EXPECT_GT(accepting_calls, 0);
  14896. }
  14897. // A verifier replaced while a handshake runs it lives until it returns.
  14898. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14899. using namespace httplib::tls;
  14900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14901. ASSERT_TRUE(svr.is_valid());
  14902. svr.Get("/test", [](const Request &, Response &res) {
  14903. res.set_content("ok", "text/plain");
  14904. });
  14905. auto port = svr.bind_to_any_port(HOST);
  14906. thread t([&]() { svr.listen_after_bind(); });
  14907. auto se = detail::scope_exit([&] {
  14908. svr.stop();
  14909. t.join();
  14910. });
  14911. svr.wait_until_ready();
  14912. SSLClient cli(HOST, port);
  14913. cli.enable_server_certificate_verification(false);
  14914. std::promise<void> entered;
  14915. std::promise<void> replaced;
  14916. auto replaced_future = replaced.get_future();
  14917. auto first_call = true;
  14918. // Long enough to live on the heap
  14919. std::string expected(64, 'v');
  14920. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14921. if (first_call) {
  14922. first_call = false;
  14923. entered.set_value();
  14924. replaced_future.wait();
  14925. }
  14926. return expected == std::string(64, 'v');
  14927. });
  14928. thread request([&]() {
  14929. auto res = cli.Get("/test");
  14930. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14931. });
  14932. entered.get_future().wait();
  14933. cli.set_server_certificate_verifier(
  14934. [](const VerifyContext &) { return true; });
  14935. replaced.set_value();
  14936. request.join();
  14937. }
  14938. // VerifyContext::session is the same handle the other tls:: functions take.
  14939. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14940. using namespace httplib::tls;
  14941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14942. ASSERT_TRUE(svr.is_valid());
  14943. svr.Get("/test", [](const Request &, Response &res) {
  14944. res.set_content("ok", "text/plain");
  14945. });
  14946. auto port = svr.bind_to_any_port(HOST);
  14947. thread t([&]() { svr.listen_after_bind(); });
  14948. auto se = detail::scope_exit([&] {
  14949. svr.stop();
  14950. t.join();
  14951. });
  14952. svr.wait_until_ready();
  14953. SSLClient cli(HOST, port);
  14954. cli.enable_server_certificate_verification(false);
  14955. session_t verifier_session = nullptr;
  14956. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14957. verifier_session = ctx.session;
  14958. return true;
  14959. });
  14960. session_t session_verifier_session = nullptr;
  14961. cli.set_session_verifier([&](session_t session) {
  14962. session_verifier_session = session;
  14963. return SSLVerifierResponse::NoDecisionMade;
  14964. });
  14965. auto res = cli.Get("/test");
  14966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14967. EXPECT_NE(nullptr, verifier_session);
  14968. EXPECT_EQ(session_verifier_session, verifier_session);
  14969. }
  14970. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14971. using httplib::tls::TlsError;
  14972. // Test that verify_error_to_string returns empty for success
  14973. std::string success_str = TlsError::verify_error_to_string(0);
  14974. EXPECT_TRUE(success_str.empty());
  14975. // Test that verify_error_to_string returns non-empty for error codes
  14976. // Using a common error code (certificate expired)
  14977. std::string error_str =
  14978. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14979. EXPECT_FALSE(error_str.empty());
  14980. }
  14981. TEST(SessionVerifierTest, CertificateAccepted) {
  14982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14983. ASSERT_TRUE(svr.is_valid());
  14984. svr.Get("/test", [](const Request &, Response &res) {
  14985. res.set_content("ok", "text/plain");
  14986. });
  14987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14988. auto se = detail::scope_exit([&] {
  14989. svr.stop();
  14990. t.join();
  14991. });
  14992. svr.wait_until_ready();
  14993. SSLClient cli(HOST, PORT);
  14994. cli.enable_server_certificate_verification(false);
  14995. cli.set_connection_timeout(30);
  14996. bool callback_called = false;
  14997. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14998. EXPECT_NE(session, nullptr);
  14999. callback_called = true;
  15000. return SSLVerifierResponse::CertificateAccepted;
  15001. });
  15002. auto res = cli.Get("/test");
  15003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15004. EXPECT_EQ(200, res->status);
  15005. EXPECT_TRUE(callback_called);
  15006. }
  15007. TEST(SessionVerifierTest, CertificateRejected) {
  15008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15009. ASSERT_TRUE(svr.is_valid());
  15010. svr.Get("/test", [](const Request &, Response &res) {
  15011. res.set_content("ok", "text/plain");
  15012. });
  15013. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15014. auto se = detail::scope_exit([&] {
  15015. svr.stop();
  15016. t.join();
  15017. });
  15018. svr.wait_until_ready();
  15019. SSLClient cli(HOST, PORT);
  15020. cli.enable_server_certificate_verification(false);
  15021. cli.set_connection_timeout(30);
  15022. bool callback_called = false;
  15023. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15024. EXPECT_NE(session, nullptr);
  15025. callback_called = true;
  15026. return SSLVerifierResponse::CertificateRejected;
  15027. });
  15028. auto res = cli.Get("/test");
  15029. EXPECT_FALSE(res);
  15030. EXPECT_TRUE(callback_called);
  15031. }
  15032. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15034. ASSERT_TRUE(svr.is_valid());
  15035. svr.Get("/test", [](const Request &, Response &res) {
  15036. res.set_content("ok", "text/plain");
  15037. });
  15038. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15039. auto se = detail::scope_exit([&] {
  15040. svr.stop();
  15041. t.join();
  15042. });
  15043. svr.wait_until_ready();
  15044. // NoDecisionMade with verification disabled should succeed (no default check)
  15045. SSLClient cli(HOST, PORT);
  15046. cli.enable_server_certificate_verification(false);
  15047. cli.set_connection_timeout(30);
  15048. bool callback_called = false;
  15049. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15050. EXPECT_NE(session, nullptr);
  15051. callback_called = true;
  15052. return SSLVerifierResponse::NoDecisionMade;
  15053. });
  15054. auto res = cli.Get("/test");
  15055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15056. EXPECT_EQ(200, res->status);
  15057. EXPECT_TRUE(callback_called);
  15058. }
  15059. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15061. ASSERT_TRUE(svr.is_valid());
  15062. svr.Get("/test", [](const Request &, Response &res) {
  15063. res.set_content("ok", "text/plain");
  15064. });
  15065. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15066. auto se = detail::scope_exit([&] {
  15067. svr.stop();
  15068. t.join();
  15069. });
  15070. svr.wait_until_ready();
  15071. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15072. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15073. // so we only check that the request fails, not whether the callback was
  15074. // called.
  15075. SSLClient cli(HOST, PORT);
  15076. cli.enable_server_certificate_verification(true);
  15077. cli.set_connection_timeout(30);
  15078. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15079. EXPECT_NE(session, nullptr);
  15080. return SSLVerifierResponse::NoDecisionMade;
  15081. });
  15082. auto res = cli.Get("/test");
  15083. EXPECT_FALSE(res);
  15084. }
  15085. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15086. // Test SSL server using PemMemory constructor with client CA certificates
  15087. // Read PEM files
  15088. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15089. read_file(SERVER_CERT_FILE, server_cert_pem);
  15090. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15091. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15092. // Create SSLServer with PemMemory constructor including client CA
  15093. SSLServer::PemMemory server_pem = {
  15094. server_cert_pem.c_str(),
  15095. server_cert_pem.size(),
  15096. server_key_pem.c_str(),
  15097. server_key_pem.size(),
  15098. client_ca_pem.c_str(),
  15099. client_ca_pem.size(),
  15100. nullptr // no password for server key
  15101. };
  15102. SSLServer svr(server_pem);
  15103. ASSERT_TRUE(svr.is_valid());
  15104. // No SSL error should be recorded for valid setup
  15105. EXPECT_EQ(0, svr.ssl_last_error());
  15106. // Set up server endpoints
  15107. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15108. res.set_content("ok", "text/plain");
  15109. });
  15110. // Start server in a thread
  15111. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15112. svr.wait_until_ready();
  15113. // Connect with client certificate (using constructor with paths)
  15114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15115. cli.enable_server_certificate_verification(false);
  15116. auto res = cli.Get("/test-pem-ca");
  15117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15118. EXPECT_EQ(200, res->status);
  15119. EXPECT_EQ("ok", res->body);
  15120. svr.stop();
  15121. server_thread.join();
  15122. }
  15123. #endif
  15124. #ifdef _WIN32
  15125. TEST(CleanupTest, WSACleanup) {
  15126. int ret = WSACleanup();
  15127. ASSERT_EQ(0, ret);
  15128. }
  15129. #endif
  15130. #ifndef CPPHTTPLIB_SSL_ENABLED
  15131. TEST(NoSSLSupport, SimpleInterface) {
  15132. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15133. }
  15134. #endif
  15135. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15136. TEST(InvalidScheme, SimpleInterface) {
  15137. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15138. }
  15139. #endif
  15140. TEST(NoScheme, SimpleInterface) {
  15141. Client cli("yahoo.com:80");
  15142. ASSERT_TRUE(cli.is_valid());
  15143. }
  15144. TEST(SendAPI, SimpleInterface_Online) {
  15145. Client cli("http://yahoo.com");
  15146. Request req;
  15147. req.method = "GET";
  15148. req.path = "/";
  15149. auto res = cli.send(req);
  15150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15151. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15152. }
  15153. TEST(SendAPI, WithParamsInRequest) {
  15154. Server svr;
  15155. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15156. EXPECT_TRUE(req.has_param("test"));
  15157. EXPECT_EQ("test_value", req.get_param_value("test"));
  15158. });
  15159. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15160. auto se = detail::scope_exit([&] {
  15161. svr.stop();
  15162. t.join();
  15163. ASSERT_FALSE(svr.is_running());
  15164. });
  15165. svr.wait_until_ready();
  15166. Client cli(HOST, PORT);
  15167. {
  15168. Request req;
  15169. req.method = "GET";
  15170. req.path = "/";
  15171. req.params.emplace("test", "test_value");
  15172. auto res = cli.send(req);
  15173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15174. }
  15175. {
  15176. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15178. }
  15179. }
  15180. TEST(ClientImplMethods, GetSocketTest) {
  15181. httplib::Server svr;
  15182. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15183. res.status = StatusCode::OK_200;
  15184. });
  15185. auto port = svr.bind_to_any_port("127.0.0.1");
  15186. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15187. auto se = detail::scope_exit([&] {
  15188. svr.stop();
  15189. thread.join();
  15190. ASSERT_FALSE(svr.is_running());
  15191. });
  15192. svr.wait_until_ready();
  15193. {
  15194. httplib::Client cli("127.0.0.1", port);
  15195. cli.set_keep_alive(true);
  15196. // Use the behavior of cpp-httplib of opening the connection
  15197. // only when the first request happens. If that changes,
  15198. // this test would be obsolete.
  15199. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15200. // This also implicitly tests the server. But other tests would fail much
  15201. // earlier than this one to be considered.
  15202. auto res = cli.Get("/");
  15203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15204. EXPECT_EQ(StatusCode::OK_200, res->status);
  15205. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15206. }
  15207. }
  15208. #ifdef CPPHTTPLIB_SSL_ENABLED
  15209. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15210. Client cli("http://yahoo.com");
  15211. auto res = cli.Get("/");
  15212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15213. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15214. cli.set_follow_location(true);
  15215. res = cli.Get("/");
  15216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15217. EXPECT_EQ(StatusCode::OK_200, res->status);
  15218. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15219. }
  15220. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15221. Client cli("https://yahoo.com");
  15222. auto res = cli.Get("/");
  15223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15224. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15225. cli.set_follow_location(true);
  15226. res = cli.Get("/");
  15227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15228. EXPECT_EQ(StatusCode::OK_200, res->status);
  15229. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15230. }
  15231. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15232. Client cli("https://yahoo.com");
  15233. auto res = cli.Get("/");
  15234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15235. ASSERT_FALSE(!res);
  15236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15237. ASSERT_FALSE(res == nullptr);
  15238. ASSERT_TRUE(res != nullptr);
  15239. EXPECT_EQ(Error::Success, res.error());
  15240. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15241. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15242. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15243. cli.set_follow_location(true);
  15244. res = cli.Get("/");
  15245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15246. EXPECT_EQ(Error::Success, res.error());
  15247. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15248. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15249. EXPECT_EQ(StatusCode::OK_200, res->status);
  15250. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15251. }
  15252. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15253. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15254. Client cli("https://cdnjs.cloudflare.com");
  15255. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15256. Headers{{"Accept-Encoding", "br"}});
  15257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15258. EXPECT_EQ(StatusCode::OK_200, res->status);
  15259. EXPECT_EQ(287630U, res->body.size());
  15260. EXPECT_EQ("application/javascript; charset=utf-8",
  15261. res->get_header_value("Content-Type"));
  15262. }
  15263. #endif
  15264. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15265. #undef REDIR_HOST // Silence compiler warning
  15266. #define REDIR_HOST "https://httpbingo.org"
  15267. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15268. Client cli(REDIR_HOST);
  15269. cli.set_follow_location(true);
  15270. auto res =
  15271. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15273. EXPECT_EQ(StatusCode::OK_200, res->status);
  15274. }
  15275. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15276. Client cli(REDIR_HOST);
  15277. cli.set_follow_location(true);
  15278. Params params;
  15279. params.emplace("url", "http://example.com");
  15280. params.emplace("status_code", "302");
  15281. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15283. EXPECT_EQ(StatusCode::OK_200, res->status);
  15284. }
  15285. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15286. Client cli(REDIR_HOST);
  15287. cli.set_follow_location(true);
  15288. Params params;
  15289. params.emplace("url", "http://example.com");
  15290. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15292. EXPECT_EQ(StatusCode::OK_200, res->status);
  15293. }
  15294. TEST(HttpToHttpsRedirectTest, CertFile) {
  15295. auto ssl_port = PORT + 1;
  15296. Server svr;
  15297. ASSERT_TRUE(svr.is_valid());
  15298. svr.Get("/index", [&](const Request &, Response &res) {
  15299. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15300. "/index");
  15301. svr.stop();
  15302. });
  15303. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15304. ASSERT_TRUE(ssl_svr.is_valid());
  15305. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15306. res.set_content("test", "text/plain");
  15307. ssl_svr.stop();
  15308. });
  15309. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15310. thread t2 =
  15311. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15312. auto se = detail::scope_exit([&] {
  15313. t2.join();
  15314. t.join();
  15315. ASSERT_FALSE(svr.is_running());
  15316. });
  15317. svr.wait_until_ready();
  15318. ssl_svr.wait_until_ready();
  15319. Client cli("127.0.0.1", PORT);
  15320. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15321. cli.enable_server_certificate_verification(true);
  15322. cli.set_follow_location(true);
  15323. cli.set_connection_timeout(30);
  15324. auto res = cli.Get("/index");
  15325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15326. ASSERT_EQ(StatusCode::OK_200, res->status);
  15327. }
  15328. TEST(SSLClientRedirectTest, CertFile) {
  15329. auto ssl_port = PORT + 1;
  15330. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15331. ASSERT_TRUE(ssl_svr1.is_valid());
  15332. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15333. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15334. "/index");
  15335. ssl_svr1.stop();
  15336. });
  15337. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15338. ASSERT_TRUE(ssl_svr2.is_valid());
  15339. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15340. res.set_content("test", "text/plain");
  15341. ssl_svr2.stop();
  15342. });
  15343. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15344. thread t2 =
  15345. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15346. auto se = detail::scope_exit([&] {
  15347. t2.join();
  15348. t.join();
  15349. ASSERT_FALSE(ssl_svr1.is_running());
  15350. });
  15351. ssl_svr1.wait_until_ready();
  15352. ssl_svr2.wait_until_ready();
  15353. SSLClient cli("127.0.0.1", PORT);
  15354. std::string cert;
  15355. read_file(SERVER_CERT2_FILE, cert);
  15356. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15357. cli.enable_server_certificate_verification(true);
  15358. cli.set_follow_location(true);
  15359. cli.set_connection_timeout(30);
  15360. auto res = cli.Get("/index");
  15361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15362. ASSERT_EQ(StatusCode::OK_200, res->status);
  15363. }
  15364. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15365. // another port, so the client follows it with a new client.
  15366. static Result GetThroughTlsRedirectToDifferentPort(
  15367. const std::function<void(SSLClient &)> &setup,
  15368. const char *target_cert = SERVER_CERT2_FILE,
  15369. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15370. auto ssl_port = PORT + 1;
  15371. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15372. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15373. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15374. "/index");
  15375. });
  15376. SSLServer ssl_svr2(target_cert, target_key);
  15377. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15378. res.set_content("test", "text/plain");
  15379. });
  15380. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15381. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15382. auto se = detail::scope_exit([&] {
  15383. ssl_svr2.stop();
  15384. ssl_svr1.stop();
  15385. t2.join();
  15386. t.join();
  15387. });
  15388. ssl_svr1.wait_until_ready();
  15389. ssl_svr2.wait_until_ready();
  15390. SSLClient cli("127.0.0.1", PORT);
  15391. cli.set_follow_location(true);
  15392. cli.set_connection_timeout(30);
  15393. setup(cli);
  15394. return cli.Get("/index");
  15395. }
  15396. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15397. auto calls = 0;
  15398. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15399. cli.enable_server_certificate_verification(false);
  15400. // Accept the first server only.
  15401. cli.set_session_verifier([&](tls::session_t) {
  15402. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15403. : SSLVerifierResponse::CertificateRejected;
  15404. });
  15405. });
  15406. ASSERT_FALSE(res);
  15407. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15408. EXPECT_EQ(2, calls);
  15409. }
  15410. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15411. std::string pinned;
  15412. auto res = GetThroughTlsRedirectToDifferentPort(
  15413. [&](SSLClient &cli) {
  15414. cli.enable_server_certificate_verification(false);
  15415. // Pin the first certificate seen.
  15416. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15417. if (pinned.empty()) { pinned = ctx.serial(); }
  15418. return ctx.serial() == pinned;
  15419. });
  15420. },
  15421. // A certificate other than the first server's.
  15422. SERVER_CERT_FILE);
  15423. EXPECT_FALSE(res);
  15424. EXPECT_FALSE(pinned.empty());
  15425. }
  15426. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15427. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15428. std::string cert;
  15429. read_file(SERVER_CERT2_FILE, cert);
  15430. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15431. });
  15432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15433. EXPECT_EQ(StatusCode::OK_200, res->status);
  15434. }
  15435. // The target's certificate is signed by the root CA, which the first server's
  15436. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15437. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15438. auto res = GetThroughTlsRedirectToDifferentPort(
  15439. [](SSLClient &cli) {
  15440. std::string root_ca, cert;
  15441. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15442. read_file(SERVER_CERT2_FILE, cert);
  15443. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15444. cli.load_ca_cert_store(cert.data(), cert.size());
  15445. cli.enable_server_hostname_verification(false);
  15446. },
  15447. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15449. EXPECT_EQ(StatusCode::OK_200, res->status);
  15450. }
  15451. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15452. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15453. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15454. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15455. auto res = GetThroughTlsRedirectToDifferentPort(
  15456. [](SSLClient &cli) {
  15457. std::string root_ca, cert;
  15458. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15459. read_file(SERVER_CERT2_FILE, cert);
  15460. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15461. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15462. cli.enable_server_hostname_verification(false);
  15463. },
  15464. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15465. ASSERT_FALSE(res);
  15466. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15467. }
  15468. #endif
  15469. #endif
  15470. #ifdef CPPHTTPLIB_SSL_ENABLED
  15471. // Test that set_ca_cert_store() skips system certs (consistent with
  15472. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15473. // should be trusted - system certs should NOT be loaded.
  15474. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15475. // Load a specific cert that is NOT a system CA cert
  15476. std::string cert;
  15477. read_file(SERVER_CERT2_FILE, cert);
  15478. SSLClient cli("google.com");
  15479. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15480. cli.enable_server_certificate_verification(true);
  15481. // This should FAIL because:
  15482. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15483. // 2. System certs should NOT be loaded when custom store is set
  15484. // If system certs WERE loaded, this would succeed
  15485. auto res = cli.Get("/");
  15486. ASSERT_FALSE(res);
  15487. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15488. }
  15489. // Same as above, but through the native store handle path. Regression test:
  15490. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15491. // merged system certs into the user-provided store.
  15492. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15493. std::string cert;
  15494. read_file(SERVER_CERT2_FILE, cert);
  15495. SSLClient cli("google.com");
  15496. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15497. cli.enable_server_certificate_verification(true);
  15498. auto res = cli.Get("/");
  15499. ASSERT_FALSE(res);
  15500. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15501. }
  15502. // A custom store set via the native handle must still verify a server whose
  15503. // cert it does contain.
  15504. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15505. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15506. ASSERT_TRUE(svr.is_valid());
  15507. svr.Get("/test", [&](const Request &, Response &res) {
  15508. res.set_content("test", "text/plain");
  15509. });
  15510. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15511. auto se = detail::scope_exit([&] {
  15512. svr.stop();
  15513. t.join();
  15514. ASSERT_FALSE(svr.is_running());
  15515. });
  15516. svr.wait_until_ready();
  15517. SSLClient cli("127.0.0.1", PORT);
  15518. std::string cert;
  15519. read_file(SERVER_CERT2_FILE, cert);
  15520. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15521. cli.enable_server_certificate_verification(true);
  15522. cli.set_connection_timeout(30);
  15523. auto res = cli.Get("/test");
  15524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15525. ASSERT_EQ(StatusCode::OK_200, res->status);
  15526. }
  15527. // CA certs loaded through the universal Client must be transferred to the
  15528. // client created internally for following an HTTPS redirect. Regression test:
  15529. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15530. // the CA data for redirect transfer.
  15531. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15532. auto ssl_port = PORT + 1;
  15533. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15534. ASSERT_TRUE(ssl_svr1.is_valid());
  15535. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15536. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15537. "/index");
  15538. });
  15539. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15540. ASSERT_TRUE(ssl_svr2.is_valid());
  15541. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15542. res.set_content("test", "text/plain");
  15543. });
  15544. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15545. thread t2 =
  15546. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15547. auto se = detail::scope_exit([&] {
  15548. ssl_svr2.stop();
  15549. ssl_svr1.stop();
  15550. t2.join();
  15551. t.join();
  15552. ASSERT_FALSE(ssl_svr1.is_running());
  15553. });
  15554. ssl_svr1.wait_until_ready();
  15555. ssl_svr2.wait_until_ready();
  15556. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15557. std::string cert;
  15558. read_file(SERVER_CERT2_FILE, cert);
  15559. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15560. cli.enable_server_certificate_verification(true);
  15561. cli.set_follow_location(true);
  15562. cli.set_connection_timeout(30);
  15563. auto res = cli.Get("/index");
  15564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15565. ASSERT_EQ(StatusCode::OK_200, res->status);
  15566. }
  15567. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15568. // so a host signed by a system CA verifies even though a custom CA is set
  15569. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15570. std::string cert;
  15571. read_file(SERVER_CERT2_FILE, cert);
  15572. SSLClient cli("google.com");
  15573. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15574. cli.enable_system_ca(true);
  15575. cli.enable_server_certificate_verification(true);
  15576. auto res = cli.Get("/");
  15577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15578. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15579. }
  15580. // The custom CA remains effective when combined with the system CA
  15581. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15582. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15583. ASSERT_TRUE(svr.is_valid());
  15584. svr.Get("/test", [&](const Request &, Response &res) {
  15585. res.set_content("test", "text/plain");
  15586. });
  15587. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15588. auto se = detail::scope_exit([&] {
  15589. svr.stop();
  15590. t.join();
  15591. ASSERT_FALSE(svr.is_running());
  15592. });
  15593. svr.wait_until_ready();
  15594. SSLClient cli("127.0.0.1", PORT);
  15595. std::string cert;
  15596. read_file(SERVER_CERT2_FILE, cert);
  15597. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15598. cli.enable_system_ca(true);
  15599. cli.enable_server_certificate_verification(true);
  15600. cli.set_connection_timeout(30);
  15601. auto res = cli.Get("/test");
  15602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15603. ASSERT_EQ(StatusCode::OK_200, res->status);
  15604. }
  15605. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15606. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15607. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15608. static CFDictionaryRef
  15609. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15610. const SecTrustSettingsResult *result) {
  15611. auto constraint =
  15612. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15613. &kCFTypeDictionaryValueCallBacks);
  15614. if (policy) {
  15615. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15616. }
  15617. if (policy_string) {
  15618. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15619. kCFStringEncodingUTF8);
  15620. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15621. CFRelease(str);
  15622. }
  15623. if (result) {
  15624. auto number_value = static_cast<SInt32>(*result);
  15625. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15626. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15627. CFRelease(number);
  15628. }
  15629. return constraint;
  15630. }
  15631. static SecTrustSettingsResult
  15632. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15633. auto trust_settings =
  15634. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15635. for (auto constraint : constraints) {
  15636. CFArrayAppendValue(trust_settings, constraint);
  15637. CFRelease(constraint);
  15638. }
  15639. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15640. CFRelease(trust_settings);
  15641. return result;
  15642. }
  15643. // The system CA loader takes a Keychain certificate as a trusted root only
  15644. // when its Trust Settings say so for SSL, not merely because it has some.
  15645. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15646. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15647. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15648. const auto deny = kSecTrustSettingsResultDeny;
  15649. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15650. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15651. auto x509_policy = SecPolicyCreateBasicX509();
  15652. // "Always Trust", which stores no constraint at all
  15653. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15654. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15655. ssl_trust_settings_result(
  15656. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15657. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15658. ssl_trust_settings_result(
  15659. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15660. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15661. ssl_trust_settings_result(
  15662. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15663. // "Never Trust", for everything or for SSL
  15664. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15665. ssl_trust_settings_result(
  15666. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15667. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15668. ssl_trust_settings_result(
  15669. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15670. // Trusted for another policy, for one host, or not at all
  15671. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15672. ssl_trust_settings_result(
  15673. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15674. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15675. ssl_trust_settings_result({make_usage_constraint(
  15676. ssl_policy, "www.example.com", &trust_root)}));
  15677. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15678. ssl_trust_settings_result(
  15679. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15680. // The first constraint that applies to SSL decides
  15681. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15682. ssl_trust_settings_result(
  15683. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15684. make_usage_constraint(nullptr, nullptr, &deny)}));
  15685. CFRelease(x509_policy);
  15686. CFRelease(ssl_policy);
  15687. }
  15688. #endif
  15689. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15690. // skip chain verification entirely (only the certificate identity was
  15691. // checked), so a server presenting an untrusted certificate with a matching
  15692. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15693. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15694. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15695. ASSERT_TRUE(svr.is_valid());
  15696. svr.Get("/test", [&](const Request &, Response &res) {
  15697. res.set_content("test", "text/plain");
  15698. });
  15699. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15700. auto se = detail::scope_exit([&] {
  15701. svr.stop();
  15702. t.join();
  15703. ASSERT_FALSE(svr.is_running());
  15704. });
  15705. svr.wait_until_ready();
  15706. SSLClient cli("127.0.0.1", PORT);
  15707. std::string cert;
  15708. // A trusted CA that did not sign the server certificate. The server cert
  15709. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15710. // this connection.
  15711. read_file(CLIENT_CA_CERT_FILE, cert);
  15712. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15713. cli.enable_server_certificate_verification(true);
  15714. cli.set_connection_timeout(30);
  15715. auto res = cli.Get("/test");
  15716. ASSERT_FALSE(res);
  15717. }
  15718. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15719. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15720. // CA that failed to come through fails verification instead of trusting them.
  15721. // (wolfSSL does not list the system CAs it loaded.)
  15722. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15723. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15724. ASSERT_TRUE(svr.is_valid());
  15725. auto port = svr.bind_to_any_port("127.0.0.1");
  15726. ASSERT_LT(0, port);
  15727. thread t = thread([&] { svr.listen_after_bind(); });
  15728. auto se = detail::scope_exit([&] {
  15729. svr.stop();
  15730. t.join();
  15731. ASSERT_FALSE(svr.is_running());
  15732. });
  15733. svr.wait_until_ready();
  15734. // The CAs a client trusts once its first request has loaded them
  15735. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15736. Client cli("https://127.0.0.1:" + std::to_string(port));
  15737. setup(cli);
  15738. cli.Get("/");
  15739. return tls::get_ca_names(cli.tls_context()).size();
  15740. };
  15741. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15742. EXPECT_EQ(0u,
  15743. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15744. }
  15745. #endif
  15746. // A TLS setting changed between requests applies to the next one, not just to
  15747. // the next connection
  15748. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15749. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15750. ASSERT_TRUE(svr.is_valid());
  15751. svr.Get("/", [](const Request &req, Response &res) {
  15752. res.set_content(std::to_string(req.remote_port), "text/plain");
  15753. });
  15754. auto port = svr.bind_to_any_port("127.0.0.1");
  15755. ASSERT_LT(0, port);
  15756. thread t = thread([&] { svr.listen_after_bind(); });
  15757. auto se = detail::scope_exit([&] {
  15758. svr.stop();
  15759. t.join();
  15760. ASSERT_FALSE(svr.is_running());
  15761. });
  15762. svr.wait_until_ready();
  15763. SSLClient cli("127.0.0.1", port);
  15764. cli.set_keep_alive(true);
  15765. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15766. cli.enable_server_certificate_verification(false);
  15767. // The port the request went out from, so a new one means a new connection
  15768. auto client_port = [&] {
  15769. auto res = cli.Get("/");
  15770. return res ? res->body : std::string();
  15771. };
  15772. auto last = client_port();
  15773. ASSERT_FALSE(last.empty());
  15774. // Setting a value it already has keeps the connection
  15775. cli.enable_server_certificate_verification(false);
  15776. cli.enable_server_hostname_verification(true);
  15777. EXPECT_EQ(last, client_port());
  15778. cli.enable_server_certificate_verification(true);
  15779. auto res = cli.Get("/");
  15780. EXPECT_FALSE(res);
  15781. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15782. std::string ca;
  15783. read_file(SERVER_CERT2_FILE, ca);
  15784. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15785. last = client_port();
  15786. ASSERT_FALSE(last.empty());
  15787. std::vector<std::function<void()>> setters = {
  15788. [&] { cli.enable_server_hostname_verification(false); },
  15789. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15790. [&] {
  15791. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15792. },
  15793. [&] {
  15794. cli.set_server_certificate_verifier(
  15795. [](const tls::VerifyContext &) { return true; });
  15796. },
  15797. [&] {
  15798. cli.set_session_verifier(
  15799. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15800. },
  15801. };
  15802. for (const auto &setter : setters) {
  15803. setter();
  15804. auto next = client_port();
  15805. ASSERT_FALSE(next.empty());
  15806. EXPECT_NE(last, next);
  15807. last = next;
  15808. }
  15809. cli.set_session_verifier(
  15810. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15811. auto handle = cli.open_stream("GET", "/");
  15812. EXPECT_FALSE(handle.is_valid());
  15813. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15814. }
  15815. // A PEM given to create_ca_store() needs no NUL after it
  15816. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15817. std::string pem;
  15818. read_file(SERVER_CERT2_FILE, pem);
  15819. auto buf = pem + "X";
  15820. auto store = tls::create_ca_store(buf.data(), pem.size());
  15821. EXPECT_TRUE(store != nullptr);
  15822. SSLClient cli("localhost");
  15823. cli.set_ca_cert_store(store);
  15824. }
  15825. // enable_system_ca(false) prevents system CA loading entirely
  15826. TEST(SSLClientTest, DisableSystemCa_Online) {
  15827. SSLClient cli("google.com");
  15828. cli.enable_system_ca(false);
  15829. cli.enable_server_certificate_verification(true);
  15830. auto res = cli.Get("/");
  15831. ASSERT_FALSE(res);
  15832. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15833. // itself when the CA chain is empty
  15834. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15835. res.error() == Error::SSLConnection);
  15836. }
  15837. // The universal Client forwards enable_system_ca()
  15838. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15839. std::string cert;
  15840. read_file(SERVER_CERT2_FILE, cert);
  15841. Client cli("https://google.com");
  15842. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15843. cli.enable_system_ca(true);
  15844. cli.enable_server_certificate_verification(true);
  15845. auto res = cli.Get("/");
  15846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15847. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15848. }
  15849. // The system CA policy must carry over to the client created internally for
  15850. // following a cross-host HTTPS redirect
  15851. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15852. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15853. ASSERT_TRUE(svr.is_valid());
  15854. svr.Get("/index", [&](const Request &, Response &res) {
  15855. res.set_redirect("https://www.google.com/");
  15856. });
  15857. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15858. auto se = detail::scope_exit([&] {
  15859. svr.stop();
  15860. t.join();
  15861. ASSERT_FALSE(svr.is_running());
  15862. });
  15863. svr.wait_until_ready();
  15864. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15865. std::string cert;
  15866. read_file(SERVER_CERT2_FILE, cert);
  15867. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15868. cli.enable_system_ca(true);
  15869. cli.enable_server_certificate_verification(true);
  15870. cli.set_follow_location(true);
  15871. cli.set_connection_timeout(30);
  15872. // Receiving any response proves the redirect client completed the TLS
  15873. // handshake with a system-CA-signed host
  15874. auto res = cli.Get("/index");
  15875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15876. }
  15877. TEST(MultipartFormDataTest, LargeData) {
  15878. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15879. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15880. const ContentReader &content_reader) {
  15881. if (req.is_multipart_form_data()) {
  15882. std::vector<FormData> items;
  15883. content_reader(
  15884. [&](const FormData &file) {
  15885. items.push_back(file);
  15886. return true;
  15887. },
  15888. [&](const char *data, size_t data_length) {
  15889. items.back().content.append(data, data_length);
  15890. return true;
  15891. });
  15892. EXPECT_TRUE(std::string(items[0].name) == "document");
  15893. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15894. EXPECT_TRUE(items[0].filename == "2MB_data");
  15895. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15896. EXPECT_TRUE(items[1].name == "hello");
  15897. EXPECT_TRUE(items[1].content == "world");
  15898. EXPECT_TRUE(items[1].filename == "");
  15899. EXPECT_TRUE(items[1].content_type == "");
  15900. } else {
  15901. std::string body;
  15902. content_reader([&](const char *data, size_t data_length) {
  15903. body.append(data, data_length);
  15904. return true;
  15905. });
  15906. }
  15907. });
  15908. auto port = svr.bind_to_any_port(HOST);
  15909. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15910. auto se = detail::scope_exit([&] {
  15911. svr.stop();
  15912. t.join();
  15913. ASSERT_FALSE(svr.is_running());
  15914. });
  15915. svr.wait_until_ready();
  15916. {
  15917. std::string data(1024 * 1024 * 2, '.');
  15918. std::stringstream buffer;
  15919. buffer << data;
  15920. SSLClient cli(HOST, port);
  15921. cli.enable_server_certificate_verification(false);
  15922. UploadFormDataItems items{
  15923. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15924. {"hello", "world", "", ""},
  15925. };
  15926. auto res = cli.Post("/post", items);
  15927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15928. ASSERT_EQ(StatusCode::OK_200, res->status);
  15929. }
  15930. }
  15931. TEST(MultipartFormDataTest, DataProviderItems) {
  15932. std::random_device seed_gen;
  15933. std::mt19937 random(seed_gen());
  15934. std::string rand1;
  15935. rand1.resize(1000);
  15936. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15937. std::string rand2;
  15938. rand2.resize(3000);
  15939. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15940. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15941. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15942. const ContentReader &content_reader) {
  15943. ASSERT_FALSE(req.is_multipart_form_data());
  15944. std::string body;
  15945. content_reader([&](const char *data, size_t data_length) {
  15946. body.append(data, data_length);
  15947. return true;
  15948. });
  15949. EXPECT_EQ(body, "");
  15950. });
  15951. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15952. const ContentReader &content_reader) {
  15953. ASSERT_TRUE(req.is_multipart_form_data());
  15954. std::vector<FormData> items;
  15955. content_reader(
  15956. [&](const FormData &file) {
  15957. items.push_back(file);
  15958. return true;
  15959. },
  15960. [&](const char *data, size_t data_length) {
  15961. items.back().content.append(data, data_length);
  15962. return true;
  15963. });
  15964. ASSERT_TRUE(items.size() == 2);
  15965. EXPECT_EQ(std::string(items[0].name), "name1");
  15966. EXPECT_EQ(items[0].content, "Testing123");
  15967. EXPECT_EQ(items[0].filename, "filename1");
  15968. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15969. EXPECT_EQ(items[1].name, "name2");
  15970. EXPECT_EQ(items[1].content, "Testing456");
  15971. EXPECT_EQ(items[1].filename, "");
  15972. EXPECT_EQ(items[1].content_type, "");
  15973. });
  15974. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15975. const ContentReader &content_reader) {
  15976. ASSERT_TRUE(req.is_multipart_form_data());
  15977. std::vector<FormData> items;
  15978. content_reader(
  15979. [&](const FormData &file) {
  15980. items.push_back(file);
  15981. return true;
  15982. },
  15983. [&](const char *data, size_t data_length) {
  15984. items.back().content.append(data, data_length);
  15985. return true;
  15986. });
  15987. ASSERT_TRUE(items.size() == 2);
  15988. EXPECT_EQ(items[0].name, "name3");
  15989. EXPECT_EQ(items[0].content, rand1);
  15990. EXPECT_EQ(items[0].filename, "filename3");
  15991. EXPECT_EQ(items[0].content_type, "");
  15992. EXPECT_EQ(items[1].name, "name4");
  15993. EXPECT_EQ(items[1].content, rand2);
  15994. EXPECT_EQ(items[1].filename, "filename4");
  15995. EXPECT_EQ(items[1].content_type, "");
  15996. });
  15997. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15998. const ContentReader &content_reader) {
  15999. ASSERT_TRUE(req.is_multipart_form_data());
  16000. std::vector<FormData> items;
  16001. content_reader(
  16002. [&](const FormData &file) {
  16003. items.push_back(file);
  16004. return true;
  16005. },
  16006. [&](const char *data, size_t data_length) {
  16007. items.back().content.append(data, data_length);
  16008. return true;
  16009. });
  16010. ASSERT_TRUE(items.size() == 4);
  16011. EXPECT_EQ(std::string(items[0].name), "name1");
  16012. EXPECT_EQ(items[0].content, "Testing123");
  16013. EXPECT_EQ(items[0].filename, "filename1");
  16014. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16015. EXPECT_EQ(items[1].name, "name2");
  16016. EXPECT_EQ(items[1].content, "Testing456");
  16017. EXPECT_EQ(items[1].filename, "");
  16018. EXPECT_EQ(items[1].content_type, "");
  16019. EXPECT_EQ(items[2].name, "name3");
  16020. EXPECT_EQ(items[2].content, rand1);
  16021. EXPECT_EQ(items[2].filename, "filename3");
  16022. EXPECT_EQ(items[2].content_type, "");
  16023. EXPECT_EQ(items[3].name, "name4");
  16024. EXPECT_EQ(items[3].content, rand2);
  16025. EXPECT_EQ(items[3].filename, "filename4");
  16026. EXPECT_EQ(items[3].content_type, "");
  16027. });
  16028. auto port = svr.bind_to_any_port("localhost");
  16029. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16030. auto se = detail::scope_exit([&] {
  16031. svr.stop();
  16032. t.join();
  16033. ASSERT_FALSE(svr.is_running());
  16034. });
  16035. svr.wait_until_ready();
  16036. {
  16037. SSLClient cli("localhost", port);
  16038. cli.enable_server_certificate_verification(false);
  16039. UploadFormDataItems items{
  16040. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16041. {"name2", "Testing456", "", ""}, // not a file
  16042. };
  16043. {
  16044. auto res = cli.Post("/post-none", {}, {}, {});
  16045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16046. ASSERT_EQ(StatusCode::OK_200, res->status);
  16047. }
  16048. FormDataProviderItems providers;
  16049. {
  16050. auto res =
  16051. cli.Post("/post-items", {}, items, providers); // empty providers
  16052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16053. ASSERT_EQ(StatusCode::OK_200, res->status);
  16054. }
  16055. providers.push_back({"name3",
  16056. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16057. // test the offset is given correctly at each step
  16058. if (!offset)
  16059. sink.os.write(rand1.data(), 30);
  16060. else if (offset == 30)
  16061. sink.os.write(rand1.data() + 30, 300);
  16062. else if (offset == 330)
  16063. sink.os.write(rand1.data() + 330, 670);
  16064. else if (offset == rand1.size())
  16065. sink.done();
  16066. return true;
  16067. },
  16068. "filename3",
  16069. {}});
  16070. providers.push_back({"name4",
  16071. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16072. // test the offset is given correctly at each step
  16073. if (!offset)
  16074. sink.os.write(rand2.data(), 2000);
  16075. else if (offset == 2000)
  16076. sink.os.write(rand2.data() + 2000, 1);
  16077. else if (offset == 2001)
  16078. sink.os.write(rand2.data() + 2001, 999);
  16079. else if (offset == rand2.size())
  16080. sink.done();
  16081. return true;
  16082. },
  16083. "filename4",
  16084. {}});
  16085. {
  16086. auto res = cli.Post("/post-providers", {}, {}, providers);
  16087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16088. ASSERT_EQ(StatusCode::OK_200, res->status);
  16089. }
  16090. {
  16091. auto res = cli.Post("/post-both", {}, items, providers);
  16092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16093. ASSERT_EQ(StatusCode::OK_200, res->status);
  16094. }
  16095. }
  16096. }
  16097. TEST(MultipartFormDataTest, BadHeader) {
  16098. Server svr;
  16099. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16100. res.set_content("ok", "text/plain");
  16101. });
  16102. thread t = thread([&] { svr.listen(HOST, PORT); });
  16103. auto se = detail::scope_exit([&] {
  16104. svr.stop();
  16105. t.join();
  16106. ASSERT_FALSE(svr.is_running());
  16107. });
  16108. svr.wait_until_ready();
  16109. const std::string body =
  16110. "This is the preamble. It is to be ignored, though it\r\n"
  16111. "is a handy place for composition agents to include an\r\n"
  16112. "explanatory note to non-MIME conformant readers.\r\n"
  16113. "\r\n"
  16114. "\r\n"
  16115. "--simple boundary\r\n"
  16116. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16117. ": BAD...\r\n"
  16118. "\r\n"
  16119. "value1\r\n"
  16120. "--simple boundary\r\n"
  16121. "Content-Disposition: form-data; name=\"field2\"; "
  16122. "filename=\"example.txt\"\r\n"
  16123. "\r\n"
  16124. "value2\r\n"
  16125. "--simple boundary--\r\n"
  16126. "This is the epilogue. It is also to be ignored.\r\n";
  16127. std::string content_type =
  16128. R"(multipart/form-data; boundary="simple boundary")";
  16129. Client cli(HOST, PORT);
  16130. auto res = cli.Post("/post", body, content_type.c_str());
  16131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16132. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16133. }
  16134. TEST(MultipartFormDataTest, WithPreamble) {
  16135. Server svr;
  16136. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16137. res.set_content("ok", "text/plain");
  16138. });
  16139. thread t = thread([&] { svr.listen(HOST, PORT); });
  16140. auto se = detail::scope_exit([&] {
  16141. svr.stop();
  16142. t.join();
  16143. ASSERT_FALSE(svr.is_running());
  16144. });
  16145. svr.wait_until_ready();
  16146. const std::string body =
  16147. "This is the preamble. It is to be ignored, though it\r\n"
  16148. "is a handy place for composition agents to include an\r\n"
  16149. "explanatory note to non-MIME conformant readers.\r\n"
  16150. "\r\n"
  16151. "\r\n"
  16152. "--simple boundary\r\n"
  16153. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16154. "\r\n"
  16155. "value1\r\n"
  16156. "--simple boundary\r\n"
  16157. "Content-Disposition: form-data; name=\"field2\"; "
  16158. "filename=\"example.txt\"\r\n"
  16159. "\r\n"
  16160. "value2\r\n"
  16161. "--simple boundary--\r\n"
  16162. "This is the epilogue. It is also to be ignored.\r\n";
  16163. std::string content_type =
  16164. R"(multipart/form-data; boundary="simple boundary")";
  16165. Client cli(HOST, PORT);
  16166. auto res = cli.Post("/post", body, content_type.c_str());
  16167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16168. EXPECT_EQ(StatusCode::OK_200, res->status);
  16169. }
  16170. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16172. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16173. const ContentReader &content_reader) {
  16174. if (req.is_multipart_form_data()) {
  16175. std::vector<FormData> items;
  16176. content_reader(
  16177. [&](const FormData &file) {
  16178. items.push_back(file);
  16179. return true;
  16180. },
  16181. [&](const char *data, size_t data_length) {
  16182. items.back().content.append(data, data_length);
  16183. return true;
  16184. });
  16185. EXPECT_TRUE(std::string(items[0].name) == "document");
  16186. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16187. EXPECT_TRUE(items[0].filename == "2MB_data");
  16188. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16189. EXPECT_TRUE(items[1].name == "hello");
  16190. EXPECT_TRUE(items[1].content == "world");
  16191. EXPECT_TRUE(items[1].filename == "");
  16192. EXPECT_TRUE(items[1].content_type == "");
  16193. } else {
  16194. std::string body;
  16195. content_reader([&](const char *data, size_t data_length) {
  16196. body.append(data, data_length);
  16197. return true;
  16198. });
  16199. }
  16200. });
  16201. auto port = svr.bind_to_any_port("localhost");
  16202. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16203. auto se = detail::scope_exit([&] {
  16204. svr.stop();
  16205. t.join();
  16206. ASSERT_FALSE(svr.is_running());
  16207. });
  16208. svr.wait_until_ready();
  16209. {
  16210. std::string data(1024 * 1024 * 2, '.');
  16211. std::stringstream buffer;
  16212. buffer << data;
  16213. SSLClient cli("localhost", port);
  16214. cli.enable_server_certificate_verification(false);
  16215. UploadFormDataItems items{
  16216. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16217. {"hello", "world", "", ""},
  16218. };
  16219. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16221. ASSERT_EQ(StatusCode::OK_200, res->status);
  16222. }
  16223. }
  16224. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16225. std::string data(1024 * 1024 * 2, '&');
  16226. std::stringstream buffer;
  16227. buffer << data;
  16228. Client cli("https://localhost:8080");
  16229. UploadFormDataItems items{
  16230. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16231. {"hello", "world", "", ""},
  16232. };
  16233. for (const char &c : " \t\r\n") {
  16234. auto res =
  16235. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16236. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16237. ASSERT_FALSE(res);
  16238. }
  16239. }
  16240. TEST(MultipartFormDataTest, PutFormData) {
  16241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16242. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16243. const ContentReader &content_reader) {
  16244. if (req.is_multipart_form_data()) {
  16245. std::vector<FormData> items;
  16246. content_reader(
  16247. [&](const FormData &file) {
  16248. items.push_back(file);
  16249. return true;
  16250. },
  16251. [&](const char *data, size_t data_length) {
  16252. items.back().content.append(data, data_length);
  16253. return true;
  16254. });
  16255. EXPECT_TRUE(std::string(items[0].name) == "document");
  16256. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16257. EXPECT_TRUE(items[0].filename == "2MB_data");
  16258. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16259. EXPECT_TRUE(items[1].name == "hello");
  16260. EXPECT_TRUE(items[1].content == "world");
  16261. EXPECT_TRUE(items[1].filename == "");
  16262. EXPECT_TRUE(items[1].content_type == "");
  16263. } else {
  16264. std::string body;
  16265. content_reader([&](const char *data, size_t data_length) {
  16266. body.append(data, data_length);
  16267. return true;
  16268. });
  16269. }
  16270. });
  16271. auto port = svr.bind_to_any_port("localhost");
  16272. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16273. auto se = detail::scope_exit([&] {
  16274. svr.stop();
  16275. t.join();
  16276. ASSERT_FALSE(svr.is_running());
  16277. });
  16278. svr.wait_until_ready();
  16279. {
  16280. std::string data(1024 * 1024 * 2, '&');
  16281. std::stringstream buffer;
  16282. buffer << data;
  16283. SSLClient cli("localhost", port);
  16284. cli.enable_server_certificate_verification(false);
  16285. UploadFormDataItems items{
  16286. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16287. {"hello", "world", "", ""},
  16288. };
  16289. auto res = cli.Put("/put", items);
  16290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16291. ASSERT_EQ(StatusCode::OK_200, res->status);
  16292. }
  16293. }
  16294. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16295. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16296. svr.Put("/put_customboundary",
  16297. [&](const Request &req, const Response & /*res*/,
  16298. const ContentReader &content_reader) {
  16299. if (req.is_multipart_form_data()) {
  16300. std::vector<FormData> items;
  16301. content_reader(
  16302. [&](const FormData &file) {
  16303. items.push_back(file);
  16304. return true;
  16305. },
  16306. [&](const char *data, size_t data_length) {
  16307. items.back().content.append(data, data_length);
  16308. return true;
  16309. });
  16310. EXPECT_TRUE(std::string(items[0].name) == "document");
  16311. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16312. EXPECT_TRUE(items[0].filename == "2MB_data");
  16313. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16314. EXPECT_TRUE(items[1].name == "hello");
  16315. EXPECT_TRUE(items[1].content == "world");
  16316. EXPECT_TRUE(items[1].filename == "");
  16317. EXPECT_TRUE(items[1].content_type == "");
  16318. } else {
  16319. std::string body;
  16320. content_reader([&](const char *data, size_t data_length) {
  16321. body.append(data, data_length);
  16322. return true;
  16323. });
  16324. }
  16325. });
  16326. auto port = svr.bind_to_any_port("localhost");
  16327. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16328. auto se = detail::scope_exit([&] {
  16329. svr.stop();
  16330. t.join();
  16331. ASSERT_FALSE(svr.is_running());
  16332. });
  16333. svr.wait_until_ready();
  16334. {
  16335. std::string data(1024 * 1024 * 2, '&');
  16336. std::stringstream buffer;
  16337. buffer << data;
  16338. SSLClient cli("localhost", port);
  16339. cli.enable_server_certificate_verification(false);
  16340. UploadFormDataItems items{
  16341. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16342. {"hello", "world", "", ""},
  16343. };
  16344. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16346. ASSERT_EQ(StatusCode::OK_200, res->status);
  16347. }
  16348. }
  16349. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16350. std::string data(1024 * 1024 * 2, '&');
  16351. std::stringstream buffer;
  16352. buffer << data;
  16353. Client cli("https://localhost:8080");
  16354. cli.enable_server_certificate_verification(false);
  16355. UploadFormDataItems items{
  16356. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16357. {"hello", "world", "", ""},
  16358. };
  16359. for (const char &c : " \t\r\n") {
  16360. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16361. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16362. ASSERT_FALSE(res);
  16363. }
  16364. }
  16365. TEST(MultipartFormDataTest, AlternateFilename) {
  16366. auto handled = false;
  16367. Server svr;
  16368. svr.Post("/test", [&](const Request &req, Response &res) {
  16369. ASSERT_EQ(2u, req.form.files.size());
  16370. ASSERT_EQ(1u, req.form.fields.size());
  16371. // Test files
  16372. const auto &file1 = req.form.get_file("file1");
  16373. ASSERT_EQ("file1", file1.name);
  16374. ASSERT_EQ("A.txt", file1.filename);
  16375. ASSERT_EQ("text/plain", file1.content_type);
  16376. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16377. const auto &file2 = req.form.get_file("file2");
  16378. ASSERT_EQ("file2", file2.name);
  16379. ASSERT_EQ("a.html", file2.filename);
  16380. ASSERT_EQ("text/html", file2.content_type);
  16381. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16382. file2.content);
  16383. // Test text field
  16384. const auto &text = req.form.get_field("text");
  16385. ASSERT_EQ("text default", text);
  16386. res.set_content("ok", "text/plain");
  16387. handled = true;
  16388. });
  16389. thread t = thread([&] { svr.listen(HOST, PORT); });
  16390. auto se = detail::scope_exit([&] {
  16391. svr.stop();
  16392. t.join();
  16393. ASSERT_FALSE(svr.is_running());
  16394. ASSERT_TRUE(handled);
  16395. });
  16396. svr.wait_until_ready();
  16397. auto req = "POST /test HTTP/1.1\r\n"
  16398. "Host: localhost\r\n"
  16399. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16400. "Content-Length: 399\r\n"
  16401. "\r\n"
  16402. "----------\r\n"
  16403. "Content-Disposition: form-data; name=\"text\"\r\n"
  16404. "\r\n"
  16405. "text default\r\n"
  16406. "----------\r\n"
  16407. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16408. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16409. "Content-Type: text/plain\r\n"
  16410. "\r\n"
  16411. "Content of a.txt.\r\n"
  16412. "\r\n"
  16413. "----------\r\n"
  16414. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16415. "\"a.html\"\r\n"
  16416. "Content-Type: text/html\r\n"
  16417. "\r\n"
  16418. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16419. "\r\n"
  16420. "------------\r\n";
  16421. ASSERT_TRUE(send_request(1, req));
  16422. }
  16423. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16424. auto handled = false;
  16425. Server svr;
  16426. svr.Post("/test", [&](const Request &req, Response &res) {
  16427. // Case-insensitive "utf-8''" prefix with a long value
  16428. const auto &file = req.form.get_file("file1");
  16429. ASSERT_EQ("file1", file.name);
  16430. // 8000 chars exercises both the Content-Disposition parser and the
  16431. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16432. // Prior to the fix, std::regex_match on this header would cause O(N)
  16433. // stack recursion in libstdc++, leading to SIGSEGV.
  16434. std::string expected_filename(8000, 'A');
  16435. ASSERT_EQ(expected_filename, file.filename);
  16436. res.set_content("ok", "text/plain");
  16437. handled = true;
  16438. });
  16439. thread t = thread([&] { svr.listen(HOST, PORT); });
  16440. auto se = detail::scope_exit([&] {
  16441. svr.stop();
  16442. t.join();
  16443. ASSERT_FALSE(svr.is_running());
  16444. ASSERT_TRUE(handled);
  16445. });
  16446. svr.wait_until_ready();
  16447. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16448. // Regression test for GHSA-qq6v-r583-3h69
  16449. std::string long_filename(8000, 'A');
  16450. std::string body = "----------\r\n"
  16451. "Content-Disposition: form-data; name=\"file1\"; "
  16452. "filename*=\"Utf-8''" +
  16453. long_filename +
  16454. "\"\r\n"
  16455. "\r\n"
  16456. "hello\r\n"
  16457. "------------\r\n";
  16458. auto req = "POST /test HTTP/1.1\r\n"
  16459. "Host: localhost\r\n"
  16460. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16461. "Content-Length: " +
  16462. std::to_string(body.size()) + "\r\n\r\n" + body;
  16463. ASSERT_TRUE(send_request(1, req));
  16464. }
  16465. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16466. auto handled = false;
  16467. Server svr;
  16468. svr.Post("/test", [&](const Request &req, Response &) {
  16469. ASSERT_EQ(2u, req.form.fields.size());
  16470. const auto &text1 = req.form.get_field("text1");
  16471. ASSERT_EQ("text1", text1);
  16472. const auto &text2 = req.form.get_field("text2");
  16473. ASSERT_EQ("text2", text2);
  16474. handled = true;
  16475. });
  16476. thread t = thread([&] { svr.listen(HOST, PORT); });
  16477. auto se = detail::scope_exit([&] {
  16478. svr.stop();
  16479. t.join();
  16480. ASSERT_FALSE(svr.is_running());
  16481. ASSERT_TRUE(handled);
  16482. });
  16483. svr.wait_until_ready();
  16484. auto req = "POST /test HTTP/1.1\r\n"
  16485. "Host: localhost\r\n"
  16486. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16487. "Content-Length: 146\r\n"
  16488. "\r\n----------\r\n"
  16489. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16490. "\r\n"
  16491. "text1"
  16492. "\r\n----------\r\n"
  16493. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16494. "\r\n"
  16495. "text2"
  16496. "\r\n------------";
  16497. std::string response;
  16498. ASSERT_TRUE(send_request(1, req, &response));
  16499. ASSERT_EQ("200", response.substr(9, 3));
  16500. }
  16501. TEST(MultipartFormDataTest, ContentLength) {
  16502. auto handled = false;
  16503. Server svr;
  16504. svr.Post("/test", [&](const Request &req, Response &) {
  16505. ASSERT_EQ(2u, req.form.fields.size());
  16506. const auto &text1 = req.form.get_field("text1");
  16507. ASSERT_EQ("text1", text1);
  16508. const auto &text2 = req.form.get_field("text2");
  16509. ASSERT_EQ("text2", text2);
  16510. handled = true;
  16511. });
  16512. thread t = thread([&] { svr.listen(HOST, PORT); });
  16513. auto se = detail::scope_exit([&] {
  16514. svr.stop();
  16515. t.join();
  16516. ASSERT_FALSE(svr.is_running());
  16517. ASSERT_TRUE(handled);
  16518. });
  16519. svr.wait_until_ready();
  16520. auto req = "POST /test HTTP/1.1\r\n"
  16521. "Host: localhost\r\n"
  16522. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16523. "Content-Length: 167\r\n"
  16524. "\r\n----------\r\n"
  16525. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16526. "Content-Length: 5\r\n"
  16527. "\r\n"
  16528. "text1"
  16529. "\r\n----------\r\n"
  16530. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16531. "\r\n"
  16532. "text2"
  16533. "\r\n------------\r\n";
  16534. std::string response;
  16535. ASSERT_TRUE(send_request(1, req, &response));
  16536. ASSERT_EQ("200", response.substr(9, 3));
  16537. }
  16538. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16539. auto handled = false;
  16540. Server svr;
  16541. svr.Post("/test", [&](const Request &req, Response &) {
  16542. ASSERT_EQ(2u, req.form.fields.size());
  16543. const auto &text1 = req.form.get_field("text1");
  16544. ASSERT_EQ("text1", text1);
  16545. // TODO: Add header access for text fields if needed
  16546. const auto &text2 = req.form.get_field("text2");
  16547. ASSERT_EQ("text2", text2);
  16548. // TODO: Header access for text fields needs to be implemented
  16549. // auto &headers = it->second.headers;
  16550. // ASSERT_EQ(3U, headers.size());
  16551. // auto custom_header = headers.find("x-whatever");
  16552. // ASSERT_TRUE(custom_header != headers.end());
  16553. // ASSERT_NE("customvalue", custom_header->second);
  16554. // ASSERT_EQ("CustomValue", custom_header->second);
  16555. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16556. handled = true;
  16557. });
  16558. thread t = thread([&] { svr.listen(HOST, PORT); });
  16559. auto se = detail::scope_exit([&] {
  16560. svr.stop();
  16561. t.join();
  16562. ASSERT_FALSE(svr.is_running());
  16563. ASSERT_TRUE(handled);
  16564. });
  16565. svr.wait_until_ready();
  16566. auto req = "POST /test HTTP/1.1\r\n"
  16567. "Host: localhost\r\n"
  16568. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16569. "Content-Length: 232\r\n"
  16570. "\r\n----------\r\n"
  16571. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16572. "Content-Length: 5\r\n"
  16573. "X-Test: 1\r\n"
  16574. "\r\n"
  16575. "text1"
  16576. "\r\n----------\r\n"
  16577. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16578. "Content-Type: text/plain\r\n"
  16579. "X-Whatever: CustomValue\r\n"
  16580. "\r\n"
  16581. "text2"
  16582. "\r\n------------\r\n"
  16583. "That should be disregarded. Not even read";
  16584. std::string response;
  16585. ASSERT_TRUE(send_request(1, req, &response));
  16586. ASSERT_EQ("200", response.substr(9, 3));
  16587. }
  16588. TEST(MultipartFormDataTest, LargeHeader) {
  16589. auto handled = false;
  16590. Server svr;
  16591. svr.Post("/test", [&](const Request &req, Response &) {
  16592. ASSERT_EQ(1u, req.form.fields.size());
  16593. const auto &text = req.form.get_field("name1");
  16594. ASSERT_EQ("text1", text);
  16595. handled = true;
  16596. });
  16597. thread t = thread([&] { svr.listen(HOST, PORT); });
  16598. auto se = detail::scope_exit([&] {
  16599. svr.stop();
  16600. t.join();
  16601. ASSERT_FALSE(svr.is_running());
  16602. ASSERT_TRUE(handled);
  16603. });
  16604. svr.wait_until_ready();
  16605. auto boundary = std::string("cpp-httplib-multipart-data");
  16606. std::string content = "--" + boundary +
  16607. "\r\n"
  16608. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16609. "\r\n"
  16610. "text1\r\n"
  16611. "--" +
  16612. boundary + "--\r\n";
  16613. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16614. "Host: localhost\r\n"
  16615. "Content-Type: multipart/form-data;boundary=" +
  16616. boundary +
  16617. "\r\n"
  16618. "Content-Length: " +
  16619. std::to_string(content.size()) +
  16620. "\r\n"
  16621. "Dummy-Header: ";
  16622. std::string header_suffix = "\r\n"
  16623. "\r\n";
  16624. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16625. size_t header_dummy_size =
  16626. read_buff_size -
  16627. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16628. auto header_dummy = std::string(header_dummy_size, '@');
  16629. auto req = header_prefix + header_dummy + header_suffix + content;
  16630. std::string response;
  16631. ASSERT_TRUE(send_request(1, req, &response));
  16632. ASSERT_EQ("200", response.substr(9, 3));
  16633. }
  16634. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16635. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16636. // (not chunked Transfer-Encoding) after the streaming refactor.
  16637. auto handled = false;
  16638. Server svr;
  16639. svr.Post("/upload", [&](const Request &req, Response &res) {
  16640. auto cl_it = req.headers.find("Content-Length");
  16641. EXPECT_TRUE(cl_it != req.headers.end());
  16642. auto te_it = req.headers.find("Transfer-Encoding");
  16643. EXPECT_TRUE(te_it == req.headers.end());
  16644. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16645. res.set_content("ok", "text/plain");
  16646. handled = true;
  16647. });
  16648. auto port = svr.bind_to_any_port(HOST);
  16649. auto t = thread([&] { svr.listen_after_bind(); });
  16650. auto se = detail::scope_exit([&] {
  16651. svr.stop();
  16652. t.join();
  16653. ASSERT_FALSE(svr.is_running());
  16654. ASSERT_TRUE(handled);
  16655. });
  16656. svr.wait_until_ready();
  16657. UploadFormDataItems items = {
  16658. {"field1", "hello", "", "text/plain"},
  16659. {"file1", "world", "test.txt", "application/octet-stream"},
  16660. };
  16661. Client cli(HOST, port);
  16662. auto res = cli.Post("/upload", {}, items);
  16663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16664. EXPECT_EQ(StatusCode::OK_200, res->status);
  16665. }
  16666. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16667. // Verify that make_multipart_content_provider coalesces many small segments
  16668. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16669. constexpr size_t kItemCount = 1000;
  16670. UploadFormDataItems items;
  16671. items.reserve(kItemCount);
  16672. for (size_t i = 0; i < kItemCount; i++) {
  16673. items.push_back(
  16674. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16675. }
  16676. const std::string boundary = "----test-boundary";
  16677. auto content_length = detail::get_multipart_content_length(items, boundary);
  16678. auto provider = detail::make_multipart_content_provider(items, boundary);
  16679. // Drive the provider the same way write_content_with_progress does
  16680. size_t write_count = 0;
  16681. size_t total_bytes = 0;
  16682. DataSink sink;
  16683. size_t offset = 0;
  16684. sink.write = [&](const char *d, size_t l) -> bool {
  16685. (void)d;
  16686. write_count++;
  16687. total_bytes += l;
  16688. offset += l;
  16689. return true;
  16690. };
  16691. sink.is_writable = []() -> bool { return true; };
  16692. while (offset < content_length) {
  16693. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16694. }
  16695. EXPECT_EQ(content_length, total_bytes);
  16696. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16697. // With buffering into 64KB blocks, write_count should be much smaller.
  16698. auto segment_count = 3 * kItemCount + 1;
  16699. EXPECT_LT(write_count, segment_count / 10);
  16700. }
  16701. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16702. // Integration test: send many UploadFormDataItems and verify the server
  16703. // receives all of them correctly (#2410).
  16704. constexpr size_t kItemCount = 500;
  16705. auto handled = false;
  16706. Server svr;
  16707. svr.Post("/upload", [&](const Request &req, Response &res) {
  16708. EXPECT_EQ(kItemCount, req.form.fields.size());
  16709. for (size_t i = 0; i < kItemCount; i++) {
  16710. auto key = "field" + std::to_string(i);
  16711. auto val = "value" + std::to_string(i);
  16712. auto it = req.form.fields.find(key);
  16713. if (it != req.form.fields.end()) {
  16714. EXPECT_EQ(val, it->second.content);
  16715. } else {
  16716. ADD_FAILURE() << "Missing field: " << key;
  16717. }
  16718. }
  16719. res.set_content("ok", "text/plain");
  16720. handled = true;
  16721. });
  16722. auto port = svr.bind_to_any_port(HOST);
  16723. auto t = thread([&] { svr.listen_after_bind(); });
  16724. auto se = detail::scope_exit([&] {
  16725. svr.stop();
  16726. t.join();
  16727. ASSERT_FALSE(svr.is_running());
  16728. ASSERT_TRUE(handled);
  16729. });
  16730. svr.wait_until_ready();
  16731. UploadFormDataItems items;
  16732. items.reserve(kItemCount);
  16733. for (size_t i = 0; i < kItemCount; i++) {
  16734. items.push_back(
  16735. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16736. }
  16737. Client cli(HOST, port);
  16738. auto res = cli.Post("/upload", items);
  16739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16740. EXPECT_EQ(StatusCode::OK_200, res->status);
  16741. }
  16742. TEST(MultipartFormDataTest, MakeFileProvider) {
  16743. // Verify make_file_provider sends a file's contents correctly.
  16744. const std::string file_content(4096, 'Z');
  16745. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16746. {
  16747. std::ofstream ofs(tmp_path, std::ios::binary);
  16748. ofs.write(file_content.data(),
  16749. static_cast<std::streamsize>(file_content.size()));
  16750. }
  16751. auto handled = false;
  16752. Server svr;
  16753. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16754. const ContentReader &content_reader) {
  16755. ASSERT_TRUE(req.is_multipart_form_data());
  16756. std::vector<FormData> items;
  16757. content_reader(
  16758. [&](const FormData &file) {
  16759. items.push_back(file);
  16760. return true;
  16761. },
  16762. [&](const char *data, size_t data_length) {
  16763. items.back().content.append(data, data_length);
  16764. return true;
  16765. });
  16766. ASSERT_EQ(1u, items.size());
  16767. EXPECT_EQ("myfile", items[0].name);
  16768. EXPECT_EQ("data.bin", items[0].filename);
  16769. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16770. EXPECT_EQ(file_content, items[0].content);
  16771. handled = true;
  16772. });
  16773. auto port = svr.bind_to_any_port(HOST);
  16774. auto t = thread([&] { svr.listen_after_bind(); });
  16775. auto se = detail::scope_exit([&] {
  16776. svr.stop();
  16777. t.join();
  16778. ASSERT_FALSE(svr.is_running());
  16779. ASSERT_TRUE(handled);
  16780. std::remove(tmp_path.c_str());
  16781. });
  16782. svr.wait_until_ready();
  16783. FormDataProviderItems providers;
  16784. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16785. "application/octet-stream"));
  16786. Client cli(HOST, port);
  16787. auto res = cli.Post("/upload", {}, {}, providers);
  16788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16789. EXPECT_EQ(StatusCode::OK_200, res->status);
  16790. }
  16791. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16792. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16793. // (100) headers is rejected with a 400 Bad Request response.
  16794. Server svr;
  16795. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16796. res.set_content("ok", "text/plain");
  16797. });
  16798. thread t = thread([&] { svr.listen(HOST, PORT); });
  16799. auto se = detail::scope_exit([&] {
  16800. svr.stop();
  16801. t.join();
  16802. ASSERT_FALSE(svr.is_running());
  16803. });
  16804. svr.wait_until_ready();
  16805. // Build a multipart part with 101 custom headers (exceeding
  16806. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16807. std::stringstream body;
  16808. body << "--simpleboundary\r\n"
  16809. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16810. for (int i = 0; i < 101; i++) {
  16811. body << "X-Custom-Header-" << i << ": value\r\n";
  16812. }
  16813. body << "\r\n"
  16814. << "value1\r\n"
  16815. << "--simpleboundary--\r\n";
  16816. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16817. Client cli(HOST, PORT);
  16818. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16820. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16821. }
  16822. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16823. // A body that never contains the declared boundary must not be accumulated
  16824. // while the parser waits for it. Buffering it would also make every read
  16825. // rescan everything seen so far, which is quadratic in the body size.
  16826. Server svr;
  16827. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16828. res.set_content("ok", "text/plain");
  16829. });
  16830. auto port = svr.bind_to_any_port(HOST);
  16831. thread t = thread([&] { svr.listen_after_bind(); });
  16832. auto se = detail::scope_exit([&] {
  16833. svr.stop();
  16834. t.join();
  16835. ASSERT_FALSE(svr.is_running());
  16836. });
  16837. svr.wait_until_ready();
  16838. Client cli(HOST, port);
  16839. cli.set_read_timeout(60, 0);
  16840. cli.set_write_timeout(60, 0);
  16841. // '-' is the worst case: it matches the first character of the boundary, so
  16842. // every position has to be checked against it.
  16843. auto post_dashes = [&](size_t size) {
  16844. const std::string body(size, '-');
  16845. auto start = std::chrono::steady_clock::now();
  16846. auto res =
  16847. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16848. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16849. std::chrono::steady_clock::now() - start)
  16850. .count();
  16851. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16852. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16853. return ms;
  16854. };
  16855. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16856. // Windows.
  16857. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16858. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16859. // Comparing the two sizes rather than checking an absolute duration keeps
  16860. // this meaningful across build types and CI load, both of which move the
  16861. // absolute numbers by more than an order of magnitude. Four times the bytes
  16862. // costs about four times the time when parsing is linear, and about sixteen
  16863. // times when the body is buffered and rescanned.
  16864. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16865. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16866. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16867. << "ms, which suggests the body is being buffered and rescanned";
  16868. }
  16869. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16870. // A boundary can only be followed by CRLF or by "--", so anything else is
  16871. // malformed no matter what comes next. The parser must say so right away
  16872. // instead of buffering the rest of the declared body.
  16873. Server svr;
  16874. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16875. res.set_content("ok", "text/plain");
  16876. });
  16877. auto port = svr.bind_to_any_port(HOST);
  16878. thread t = thread([&] { svr.listen_after_bind(); });
  16879. auto se = detail::scope_exit([&] {
  16880. svr.stop();
  16881. t.join();
  16882. ASSERT_FALSE(svr.is_running());
  16883. });
  16884. svr.wait_until_ready();
  16885. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16886. // buffers instead of failing would still be waiting for the remaining bytes.
  16887. const std::string body = "--zzzz\r\n"
  16888. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16889. "\r\n"
  16890. "text1"
  16891. "\r\n--zzzzXX";
  16892. const std::string req = "POST /post HTTP/1.1\r\n"
  16893. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16894. "Content-Length: 1048576\r\n"
  16895. "\r\n" +
  16896. body;
  16897. std::string response;
  16898. ASSERT_TRUE(send_request(3, req, &response, port));
  16899. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16900. EXPECT_EQ("400", response.substr(9, 3));
  16901. }
  16902. // Posts a multipart body split into two writes, so that the server sees the
  16903. // split at whatever offset the caller chose, and expects the single "text1"
  16904. // field to come through.
  16905. static void expect_split_multipart_ok(const std::string &body1,
  16906. const std::string &body2) {
  16907. auto handled = false;
  16908. Server svr;
  16909. svr.Post("/post", [&](const Request &req, Response &) {
  16910. EXPECT_EQ(1u, req.form.fields.size());
  16911. EXPECT_EQ("text1", req.form.get_field("text1"));
  16912. handled = true;
  16913. });
  16914. auto port = svr.bind_to_any_port(HOST);
  16915. thread t = thread([&] { svr.listen_after_bind(); });
  16916. auto se = detail::scope_exit([&] {
  16917. svr.stop();
  16918. t.join();
  16919. ASSERT_FALSE(svr.is_running());
  16920. ASSERT_TRUE(handled);
  16921. });
  16922. svr.wait_until_ready();
  16923. // "Connection: close" makes the server close once it has answered, so the
  16924. // response drain ends immediately instead of idling until the read timeout.
  16925. const std::string head =
  16926. "POST /post HTTP/1.1\r\n"
  16927. "Host: localhost\r\n"
  16928. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16929. "Connection: close\r\n"
  16930. "Content-Length: " +
  16931. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16932. std::string response;
  16933. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16934. ASSERT_GE(response.size(), 12u) << "no response";
  16935. EXPECT_EQ("200", response.substr(9, 3));
  16936. }
  16937. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16938. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16939. // ignored, including when it does not arrive in the same read as the
  16940. // close-delimiter itself.
  16941. expect_split_multipart_ok("--zzzz\r\n"
  16942. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16943. "\r\n"
  16944. "text1"
  16945. "\r\n--zzzz--",
  16946. "\r\nthis epilogue must be ignored\r\n");
  16947. }
  16948. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16949. // The initial boundary may be preceded by a preamble of any length and may
  16950. // straddle a read boundary. Discarding data while waiting for it must not
  16951. // throw away a partial boundary sitting at the end of the buffer.
  16952. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16953. "zz\r\n"
  16954. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16955. "\r\n"
  16956. "text1"
  16957. "\r\n--zzzz--\r\n");
  16958. }
  16959. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16960. // The received boundary was only checked for being non-empty, so it could be
  16961. // as long as a header is allowed to be. The parser scans the body for
  16962. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16963. // costs a nearly full comparison at nearly every position, making the
  16964. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16965. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16966. Server svr;
  16967. svr.Post("/post", [](const Request &req, Response &res) {
  16968. EXPECT_EQ(1u, req.form.fields.size());
  16969. EXPECT_EQ("text1", req.form.get_field("text1"));
  16970. res.set_content("ok", "text/plain");
  16971. });
  16972. auto port = svr.bind_to_any_port(HOST);
  16973. thread t = thread([&] { svr.listen_after_bind(); });
  16974. auto se = detail::scope_exit([&] {
  16975. svr.stop();
  16976. t.join();
  16977. ASSERT_FALSE(svr.is_running());
  16978. });
  16979. svr.wait_until_ready();
  16980. Client cli(HOST, port);
  16981. auto post_with_boundary_of_length = [&](size_t len) {
  16982. const std::string boundary(len, 'a');
  16983. const std::string body =
  16984. "--" + boundary +
  16985. "\r\n"
  16986. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16987. "\r\n"
  16988. "text1"
  16989. "\r\n--" +
  16990. boundary + "--\r\n";
  16991. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16992. };
  16993. auto res = post_with_boundary_of_length(70);
  16994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16995. EXPECT_EQ(StatusCode::OK_200, res->status);
  16996. res = post_with_boundary_of_length(71);
  16997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16998. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16999. }
  17000. TEST(MakeFileBodyTest, Basic) {
  17001. const std::string file_content(4096, 'Z');
  17002. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17003. {
  17004. std::ofstream ofs(tmp_path, std::ios::binary);
  17005. ofs.write(file_content.data(),
  17006. static_cast<std::streamsize>(file_content.size()));
  17007. }
  17008. auto handled = false;
  17009. Server svr;
  17010. svr.Post("/upload", [&](const Request &req, Response &res) {
  17011. EXPECT_EQ(file_content, req.body);
  17012. handled = true;
  17013. res.status = StatusCode::OK_200;
  17014. });
  17015. auto port = svr.bind_to_any_port(HOST);
  17016. auto t = thread([&] { svr.listen_after_bind(); });
  17017. auto se = detail::scope_exit([&] {
  17018. svr.stop();
  17019. t.join();
  17020. ASSERT_FALSE(svr.is_running());
  17021. ASSERT_TRUE(handled);
  17022. std::remove(tmp_path.c_str());
  17023. });
  17024. svr.wait_until_ready();
  17025. auto fb = make_file_body(tmp_path);
  17026. ASSERT_GT(fb.first, 0u);
  17027. Client cli(HOST, port);
  17028. auto res =
  17029. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17031. EXPECT_EQ(StatusCode::OK_200, res->status);
  17032. }
  17033. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17034. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17035. {
  17036. std::ofstream ofs(path, std::ios::binary);
  17037. const std::string content(100, 'A');
  17038. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17039. }
  17040. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17041. auto body = make_file_body(path);
  17042. ASSERT_EQ(100u, body.first);
  17043. ASSERT_TRUE(static_cast<bool>(body.second));
  17044. // Rewritten shorter after its length was measured - and, on a server, after
  17045. // that length has already gone out as Content-Length.
  17046. {
  17047. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17048. const std::string content(10, 'A');
  17049. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17050. }
  17051. std::string written;
  17052. DataSink sink;
  17053. sink.write = [&](const char *d, size_t l) {
  17054. written.append(d, l);
  17055. return true;
  17056. };
  17057. // The provider has to report failure. write_content_with_progress() advances
  17058. // its offset only by what was written, so a provider that returns true
  17059. // without completing the length it promised is called again straight away,
  17060. // and again.
  17061. EXPECT_FALSE(body.second(0, body.first, sink));
  17062. EXPECT_EQ(std::string(10, 'A'), written);
  17063. }
  17064. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17065. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17066. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17067. {
  17068. std::ofstream ofs(path, std::ios::binary);
  17069. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17070. }
  17071. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17072. auto body = make_file_body(path);
  17073. ASSERT_EQ(content.size(), body.first);
  17074. ASSERT_TRUE(static_cast<bool>(body.second));
  17075. std::string written;
  17076. DataSink sink;
  17077. sink.write = [&](const char *d, size_t l) {
  17078. written.append(d, l);
  17079. return true;
  17080. };
  17081. EXPECT_TRUE(body.second(0, body.first, sink));
  17082. EXPECT_EQ(content, written);
  17083. }
  17084. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17085. static constexpr unsigned int number_of_tasks{1000000};
  17086. std::atomic_uint count{0};
  17087. std::unique_ptr<TaskQueue> task_queue{
  17088. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17089. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17090. auto queued = task_queue->enqueue(
  17091. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17092. EXPECT_TRUE(queued);
  17093. }
  17094. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17095. task_queue->shutdown();
  17096. #else
  17097. EXPECT_NO_THROW(task_queue->shutdown());
  17098. #endif
  17099. EXPECT_EQ(number_of_tasks, count.load());
  17100. }
  17101. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17102. static constexpr unsigned int number_of_tasks{1000000};
  17103. static constexpr unsigned int qlimit{2};
  17104. unsigned int queued_count{0};
  17105. std::atomic_uint count{0};
  17106. std::unique_ptr<TaskQueue> task_queue{
  17107. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17108. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17109. if (task_queue->enqueue(
  17110. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17111. queued_count++;
  17112. }
  17113. }
  17114. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17115. task_queue->shutdown();
  17116. #else
  17117. EXPECT_NO_THROW(task_queue->shutdown());
  17118. #endif
  17119. EXPECT_EQ(queued_count, count.load());
  17120. EXPECT_TRUE(queued_count <= number_of_tasks);
  17121. EXPECT_TRUE(queued_count >= qlimit);
  17122. }
  17123. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17124. // Use a short idle timeout so a dynamic thread spawns, times out and
  17125. // exits during the test, and the pool keeps working afterwards.
  17126. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17127. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17128. /*idle_timeout_sec=*/1}};
  17129. std::atomic_uint count{0};
  17130. std::condition_variable cv;
  17131. std::mutex mtx;
  17132. bool release = false;
  17133. // Block the base thread so the second task spawns a dynamic thread.
  17134. EXPECT_TRUE(task_queue->enqueue([&] {
  17135. std::unique_lock<std::mutex> lock(mtx);
  17136. while (!release) {
  17137. cv.wait(lock);
  17138. }
  17139. count++;
  17140. }));
  17141. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17142. // Let the dynamic thread finish its task and exceed the idle timeout.
  17143. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17144. {
  17145. std::unique_lock<std::mutex> lock(mtx);
  17146. release = true;
  17147. }
  17148. cv.notify_all();
  17149. // The pool must still accept and run tasks after the dynamic thread exited.
  17150. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17151. task_queue->shutdown();
  17152. EXPECT_EQ(3u, count.load());
  17153. }
  17154. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17155. static constexpr size_t number_of_tasks{32};
  17156. std::unique_ptr<TaskQueue> task_queue{
  17157. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17158. // Let the base threads go idle so the burst below finds them waiting.
  17159. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17160. std::mutex mtx;
  17161. std::condition_variable cv;
  17162. size_t running = 0;
  17163. bool release = false;
  17164. for (size_t i = 0; i < number_of_tasks; i++) {
  17165. EXPECT_TRUE(task_queue->enqueue([&] {
  17166. std::unique_lock<std::mutex> lock(mtx);
  17167. running++;
  17168. cv.notify_all();
  17169. cv.wait(lock, [&] { return release; });
  17170. }));
  17171. }
  17172. {
  17173. std::unique_lock<std::mutex> lock(mtx);
  17174. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17175. [&] { return running == number_of_tasks; }));
  17176. release = true;
  17177. }
  17178. cv.notify_all();
  17179. task_queue->shutdown();
  17180. }
  17181. TEST(TaskQueueTest, MaxQueuedRequests) {
  17182. static constexpr unsigned int qlimit{3};
  17183. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17184. std::condition_variable sem_cv;
  17185. std::mutex sem_mtx;
  17186. int credits = 0;
  17187. bool queued;
  17188. /* Fill up the queue with tasks that will block until we give them credits to
  17189. * complete. */
  17190. for (unsigned int n = 0; n <= qlimit;) {
  17191. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17192. std::unique_lock<std::mutex> lock(sem_mtx);
  17193. while (credits <= 0) {
  17194. sem_cv.wait(lock);
  17195. }
  17196. /* Consume the credit and signal the test code if they are all gone. */
  17197. if (--credits == 0) { sem_cv.notify_one(); }
  17198. });
  17199. if (n < qlimit) {
  17200. /* The first qlimit enqueues must succeed. */
  17201. EXPECT_TRUE(queued);
  17202. } else {
  17203. /* The last one will succeed only when the worker thread
  17204. * starts and dequeues the first blocking task. Although
  17205. * not necessary for the correctness of this test, we sleep for
  17206. * a short while to avoid busy waiting. */
  17207. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17208. }
  17209. if (queued) { n++; }
  17210. }
  17211. /* Further enqueues must fail since the queue is full. */
  17212. for (auto i = 0; i < 4; i++) {
  17213. queued = task_queue->enqueue([] {});
  17214. EXPECT_FALSE(queued);
  17215. }
  17216. /* Give the credits to allow the previous tasks to complete. */
  17217. {
  17218. std::unique_lock<std::mutex> lock(sem_mtx);
  17219. credits += qlimit + 1;
  17220. }
  17221. sem_cv.notify_all();
  17222. /* Wait for all the credits to be consumed. */
  17223. {
  17224. std::unique_lock<std::mutex> lock(sem_mtx);
  17225. while (credits > 0) {
  17226. sem_cv.wait(lock);
  17227. }
  17228. }
  17229. /* Check that we are able again to enqueue at least qlimit tasks. */
  17230. for (unsigned int i = 0; i < qlimit; i++) {
  17231. queued = task_queue->enqueue([] {});
  17232. EXPECT_TRUE(queued);
  17233. }
  17234. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17235. task_queue->shutdown();
  17236. #else
  17237. EXPECT_NO_THROW(task_queue->shutdown());
  17238. #endif
  17239. }
  17240. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17241. Server svr;
  17242. std::string method;
  17243. std::string body;
  17244. auto has_content_length = false;
  17245. auto has_transfer_encoding = false;
  17246. std::atomic<int> bad_requests{0};
  17247. // Leftover body bytes get parsed as a malformed request and answered with
  17248. // 400
  17249. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17250. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17251. });
  17252. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17253. res.set_redirect("/down", StatusCode::SeeOther_303);
  17254. });
  17255. svr.Get("/down", [&](const Request &req, Response &res) {
  17256. method = req.method;
  17257. body = req.body;
  17258. has_content_length = req.has_header("Content-Length");
  17259. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17260. res.set_content("ok", "text/plain");
  17261. });
  17262. auto port = svr.bind_to_any_port(HOST);
  17263. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17264. auto se = detail::scope_exit([&] {
  17265. svr.stop();
  17266. thread.join();
  17267. ASSERT_FALSE(svr.is_running());
  17268. });
  17269. svr.wait_until_ready();
  17270. const std::string payload = "SECRET-BODY";
  17271. auto check = [&](Client &cli, const Result &res) {
  17272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17273. EXPECT_EQ(StatusCode::OK_200, res->status);
  17274. EXPECT_EQ("ok", res->body);
  17275. EXPECT_EQ("GET", method);
  17276. EXPECT_TRUE(body.empty());
  17277. EXPECT_FALSE(has_content_length);
  17278. EXPECT_FALSE(has_transfer_encoding);
  17279. // Nothing of the original body may be left on the connection
  17280. auto res2 = cli.Get("/down");
  17281. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17282. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17283. EXPECT_EQ("ok", res2->body);
  17284. EXPECT_EQ(0, bad_requests);
  17285. };
  17286. // With content length
  17287. {
  17288. Client cli(HOST, port);
  17289. cli.set_keep_alive(true);
  17290. cli.set_follow_location(true);
  17291. auto res = cli.Post(
  17292. "/up", payload.size(),
  17293. [&](size_t offset, size_t length, DataSink &sink) {
  17294. return sink.write(payload.data() + offset, length);
  17295. },
  17296. "text/plain");
  17297. check(cli, res);
  17298. }
  17299. // Without content length (chunked)
  17300. {
  17301. Client cli(HOST, port);
  17302. cli.set_keep_alive(true);
  17303. cli.set_follow_location(true);
  17304. auto res = cli.Post(
  17305. "/up",
  17306. [&](size_t /*offset*/, DataSink &sink) {
  17307. sink.write(payload.data(), payload.size());
  17308. sink.done();
  17309. return true;
  17310. },
  17311. "text/plain");
  17312. check(cli, res);
  17313. }
  17314. }
  17315. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17316. Server svr;
  17317. std::string target;
  17318. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17319. // Echo the still-encoded name back in the Location
  17320. const std::string prefix = "/start/";
  17321. res.status = StatusCode::Found_302;
  17322. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17323. });
  17324. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17325. target = req.target;
  17326. res.set_content("ok", "text/plain");
  17327. });
  17328. auto port = svr.bind_to_any_port(HOST);
  17329. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17330. auto se = detail::scope_exit([&] {
  17331. svr.stop();
  17332. thread.join();
  17333. ASSERT_FALSE(svr.is_running());
  17334. });
  17335. svr.wait_until_ready();
  17336. // Decoding the Location path would turn the first four into a path
  17337. // separator, a query delimiter, a fragment delimiter and a different
  17338. // percent-encoded octet. The rest must keep reaching the server as they are.
  17339. const std::vector<std::string> names = {
  17340. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17341. };
  17342. for (auto path_encode : {true, false}) {
  17343. Client cli(HOST, port);
  17344. cli.set_follow_location(true);
  17345. cli.set_path_encode(path_encode);
  17346. for (const auto &name : names) {
  17347. target.clear();
  17348. auto res = cli.Get("/start/" + name);
  17349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17350. EXPECT_EQ(StatusCode::OK_200, res->status);
  17351. EXPECT_EQ("/dest/" + name, target);
  17352. }
  17353. }
  17354. }
  17355. TEST(RedirectTest, NotModifiedIsReturned) {
  17356. Server svr;
  17357. svr.Get("/cached", [](const Request &, Response &res) {
  17358. res.status = StatusCode::NotModified_304;
  17359. });
  17360. auto port = svr.bind_to_any_port(HOST);
  17361. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17362. auto se = detail::scope_exit([&] {
  17363. svr.stop();
  17364. thread.join();
  17365. ASSERT_FALSE(svr.is_running());
  17366. });
  17367. svr.wait_until_ready();
  17368. Client cli(HOST, port);
  17369. cli.set_follow_location(true);
  17370. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17372. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17373. }
  17374. TEST(RedirectTest, NoLocationIsReturned) {
  17375. Server svr;
  17376. svr.Get("/no-location", [](const Request &, Response &res) {
  17377. res.status = StatusCode::Found_302;
  17378. res.set_content("no location", "text/plain");
  17379. });
  17380. auto port = svr.bind_to_any_port(HOST);
  17381. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17382. auto se = detail::scope_exit([&] {
  17383. svr.stop();
  17384. thread.join();
  17385. ASSERT_FALSE(svr.is_running());
  17386. });
  17387. svr.wait_until_ready();
  17388. Client cli(HOST, port);
  17389. cli.set_follow_location(true);
  17390. auto res = cli.Get("/no-location");
  17391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17392. EXPECT_EQ(StatusCode::Found_302, res->status);
  17393. EXPECT_EQ("no location", res->body);
  17394. // The callbacks see the body of the response that is returned
  17395. auto handler_called = false;
  17396. auto progress_called = false;
  17397. std::string body;
  17398. auto res2 = cli.Get(
  17399. "/no-location",
  17400. [&](const Response &) {
  17401. handler_called = true;
  17402. return true;
  17403. },
  17404. [&](const char *data, size_t data_length) {
  17405. body.append(data, data_length);
  17406. return true;
  17407. },
  17408. [&](size_t, size_t) {
  17409. progress_called = true;
  17410. return true;
  17411. });
  17412. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17413. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17414. EXPECT_TRUE(handler_called);
  17415. EXPECT_TRUE(progress_called);
  17416. EXPECT_EQ("no location", body);
  17417. }
  17418. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17419. Server svr;
  17420. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17421. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17422. });
  17423. svr.Get("/hello", [](const Request &req, Response &res) {
  17424. res.set_content(req.get_param_value("key"), "text/plain");
  17425. });
  17426. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17427. auto se = detail::scope_exit([&] {
  17428. svr.stop();
  17429. thread.join();
  17430. ASSERT_FALSE(svr.is_running());
  17431. });
  17432. svr.wait_until_ready();
  17433. {
  17434. Client cli(HOST, PORT);
  17435. cli.set_follow_location(true);
  17436. auto res = cli.Get("/");
  17437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17438. EXPECT_EQ(StatusCode::OK_200, res->status);
  17439. EXPECT_EQ("val&key2=val2", res->body);
  17440. }
  17441. }
  17442. #endif
  17443. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17444. Server svr;
  17445. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17446. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17447. });
  17448. svr.Get("/hello", [](const Request &req, Response &res) {
  17449. res.set_content(req.get_param_value("key"), "text/plain");
  17450. });
  17451. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17452. auto se = detail::scope_exit([&] {
  17453. svr.stop();
  17454. thread.join();
  17455. ASSERT_FALSE(svr.is_running());
  17456. });
  17457. svr.wait_until_ready();
  17458. {
  17459. Client cli(HOST, PORT);
  17460. cli.set_follow_location(true);
  17461. auto res = cli.Get("/");
  17462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17463. EXPECT_EQ(StatusCode::OK_200, res->status);
  17464. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17465. }
  17466. }
  17467. TEST(RedirectTest, RedirectWithPlusInPath) {
  17468. Server svr;
  17469. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17470. res.set_redirect("/a+b");
  17471. });
  17472. // Route pattern uses regex; escape + as \\+
  17473. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17474. res.set_content(req.path, "text/plain");
  17475. });
  17476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17477. auto se = detail::scope_exit([&] {
  17478. svr.stop();
  17479. thread.join();
  17480. ASSERT_FALSE(svr.is_running());
  17481. });
  17482. svr.wait_until_ready();
  17483. {
  17484. Client cli(HOST, PORT);
  17485. cli.set_follow_location(true);
  17486. auto res = cli.Get("/");
  17487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17488. EXPECT_EQ(StatusCode::OK_200, res->status);
  17489. EXPECT_EQ("/a+b", res->body);
  17490. }
  17491. }
  17492. TEST(RedirectTest, ResolveRelativeLocation) {
  17493. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17494. const std::vector<std::pair<std::string, std::string>> cases = {
  17495. {"g", "/b/c/g"},
  17496. {"./g", "/b/c/g"},
  17497. {"g/", "/b/c/g/"},
  17498. {"?y", "/b/c/d;p?y"},
  17499. {"g?y", "/b/c/g?y"},
  17500. {"#s", "/b/c/d;p?q#s"},
  17501. {"g#s", "/b/c/g#s"},
  17502. {"g?y#s", "/b/c/g?y#s"},
  17503. {";x", "/b/c/;x"},
  17504. {"g;x", "/b/c/g;x"},
  17505. {".", "/b/c/"},
  17506. {"./", "/b/c/"},
  17507. {"..", "/b/"},
  17508. {"../", "/b/"},
  17509. {"../g", "/b/g"},
  17510. {"../..", "/"},
  17511. {"../../", "/"},
  17512. {"../../g", "/g"},
  17513. {"../../../g", "/g"},
  17514. {"g.", "/b/c/g."},
  17515. {".g", "/b/c/.g"},
  17516. {"g..", "/b/c/g.."},
  17517. {"..g", "/b/c/..g"},
  17518. {"./../g", "/b/g"},
  17519. {"./g/.", "/b/c/g/"},
  17520. {"g/./h", "/b/c/g/h"},
  17521. {"g/../h", "/b/c/h"},
  17522. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17523. {"g;x=1/../y", "/b/c/y"},
  17524. {"g?y/./x", "/b/c/g?y/./x"},
  17525. {"g#s/../x", "/b/c/g#s/../x"},
  17526. // Not relative-path references, so left for parse_url.
  17527. {"/g", "/g"},
  17528. {"//g", "//g"},
  17529. {"http://g/x", "http://g/x"},
  17530. {"g:h", "g:h"},
  17531. };
  17532. for (const auto &c : cases) {
  17533. EXPECT_EQ(c.second,
  17534. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17535. << c.first;
  17536. }
  17537. // A result starting with "//" is still a path, not a network-path reference
  17538. EXPECT_EQ("/.//g",
  17539. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  17540. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  17541. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  17542. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  17543. }
  17544. TEST(RedirectTest, RemoveDotSegments) {
  17545. // RFC 3986 section 5.2.4
  17546. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17547. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17548. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17549. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17550. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17551. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17552. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17553. }
  17554. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17555. Server svr;
  17556. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17557. res.set_redirect("/dir/../target?x=1");
  17558. });
  17559. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17560. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17561. "/dir/./../target");
  17562. });
  17563. svr.Get("/target", [](const Request &req, Response &res) {
  17564. res.set_content(req.path, "text/plain");
  17565. });
  17566. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17567. auto se = detail::scope_exit([&] {
  17568. svr.stop();
  17569. th.join();
  17570. ASSERT_FALSE(svr.is_running());
  17571. });
  17572. svr.wait_until_ready();
  17573. Client cli("localhost", PORT);
  17574. cli.set_follow_location(true);
  17575. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17576. auto res = cli.Get(path);
  17577. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17578. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17579. EXPECT_EQ("/target", res->body) << path;
  17580. }
  17581. }
  17582. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17583. Server svr;
  17584. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17585. res.set_redirect(req.get_param_value("to"));
  17586. });
  17587. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17588. res.set_content(req.target, "text/plain");
  17589. });
  17590. svr.Get("/other", [](const Request &req, Response &res) {
  17591. res.set_content(req.target, "text/plain");
  17592. });
  17593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17594. auto se = detail::scope_exit([&] {
  17595. svr.stop();
  17596. thread.join();
  17597. ASSERT_FALSE(svr.is_running());
  17598. });
  17599. svr.wait_until_ready();
  17600. const std::vector<std::pair<std::string, std::string>> cases = {
  17601. {"next", "/dir/next"},
  17602. {"./next?x=1", "/dir/next?x=1"},
  17603. {"../other", "/other"},
  17604. };
  17605. for (const auto &c : cases) {
  17606. Client cli(HOST, PORT);
  17607. cli.set_follow_location(true);
  17608. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17609. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17610. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17611. EXPECT_EQ(c.second, res->body) << c.first;
  17612. }
  17613. }
  17614. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  17615. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  17616. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  17617. Server other;
  17618. std::atomic<int> other_hits{0};
  17619. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  17620. other_hits++;
  17621. res.set_content("other", "text/plain");
  17622. });
  17623. auto other_port = other.bind_to_any_port("127.0.0.1");
  17624. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  17625. Server svr;
  17626. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17627. res.set_redirect(req.get_param_value("to"));
  17628. });
  17629. svr.Get(".*", [](const Request &req, Response &res) {
  17630. res.set_content(req.path, "text/plain");
  17631. });
  17632. auto port = svr.bind_to_any_port(HOST);
  17633. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17634. auto se = detail::scope_exit([&] {
  17635. svr.stop();
  17636. thread.join();
  17637. other.stop();
  17638. other_thread.join();
  17639. ASSERT_FALSE(svr.is_running());
  17640. ASSERT_FALSE(other.is_running());
  17641. });
  17642. svr.wait_until_ready();
  17643. other.wait_until_ready();
  17644. auto authority = "127.0.0.1:" + std::to_string(other_port);
  17645. for (const auto &to :
  17646. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  17647. Client cli(HOST, port);
  17648. cli.set_follow_location(true);
  17649. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  17650. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  17651. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  17652. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  17653. }
  17654. EXPECT_EQ(0, other_hits.load());
  17655. }
  17656. #ifdef CPPHTTPLIB_SSL_ENABLED
  17657. TEST(RedirectTest, Issue2185_Online) {
  17658. SSLClient client("github.com");
  17659. client.set_follow_location(true);
  17660. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17661. "Coollab-Windows.zip");
  17662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17663. EXPECT_EQ(StatusCode::OK_200, res->status);
  17664. EXPECT_EQ(9920427U, res->body.size());
  17665. }
  17666. #endif
  17667. TEST(VulnerabilityTest, CRLFInjection) {
  17668. Server svr;
  17669. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17670. res.set_content("Hello 1", "text/plain");
  17671. });
  17672. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17673. res.set_content("Hello 2", "text/plain");
  17674. });
  17675. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17676. res.set_content("Hello 3", "text/plain");
  17677. });
  17678. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17679. res.set_content("Hello 4", "text/plain");
  17680. });
  17681. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17682. for (const auto &x : req.headers) {
  17683. auto key = x.first;
  17684. EXPECT_STRNE("evil", key.c_str());
  17685. }
  17686. });
  17687. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17688. auto se = detail::scope_exit([&] {
  17689. svr.stop();
  17690. thread.join();
  17691. ASSERT_FALSE(svr.is_running());
  17692. });
  17693. svr.wait_until_ready();
  17694. {
  17695. Client cli(HOST, PORT);
  17696. cli.Post("/test1", "A=B",
  17697. "application/x-www-form-urlencoded\r\nevil: hello1");
  17698. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17699. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17700. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17701. }
  17702. }
  17703. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17704. auto server_thread = std::thread([] {
  17705. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17706. default_socket_options(srv);
  17707. sockaddr_in addr{};
  17708. addr.sin_family = AF_INET;
  17709. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17710. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17711. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17712. ::listen(srv, 1);
  17713. sockaddr_in cli_addr{};
  17714. socklen_t cli_len = sizeof(cli_addr);
  17715. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17716. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17717. std::string buf_all;
  17718. char buf[2048];
  17719. ssize_t n;
  17720. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17721. buf_all.append(buf, static_cast<size_t>(n));
  17722. size_t pos;
  17723. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17724. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17725. auto e = request_block.find("\r\n");
  17726. if (e != std::string::npos) {
  17727. auto request_line = request_block.substr(0, e);
  17728. std::string msg =
  17729. "CRLF injection detected in request line: '" + request_line + "'";
  17730. EXPECT_FALSE(true) << msg;
  17731. }
  17732. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17733. ::send(cli,
  17734. #ifdef _WIN32
  17735. static_cast<const char *>(resp.c_str()),
  17736. static_cast<int>(resp.size()),
  17737. #else
  17738. resp.c_str(), resp.size(),
  17739. #endif
  17740. 0);
  17741. buf_all.erase(0, pos + 4);
  17742. }
  17743. }
  17744. detail::close_socket(cli);
  17745. detail::close_socket(srv);
  17746. });
  17747. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17748. auto cli = Client("127.0.0.1", PORT + 1);
  17749. auto headers = Headers{
  17750. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17751. {"Connection", "keep-alive"}};
  17752. auto res = cli.Get("/hi", headers);
  17753. EXPECT_FALSE(res);
  17754. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17755. server_thread.join();
  17756. }
  17757. // A request rejected before any byte reaches the socket must fail right away
  17758. // instead of waiting for a response the server will never send.
  17759. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17760. // The kernel completes the TCP handshake from the listen backlog, so the
  17761. // client connects, but nothing ever reads, responds or closes.
  17762. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17763. default_socket_options(srv);
  17764. sockaddr_in addr{};
  17765. addr.sin_family = AF_INET;
  17766. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17768. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17769. ASSERT_EQ(0, ::listen(srv, 8));
  17770. auto cli = Client("127.0.0.1", PORT + 1);
  17771. cli.set_read_timeout(10, 0);
  17772. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17773. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17774. std::chrono::steady_clock::now() - start)
  17775. .count();
  17776. };
  17777. {
  17778. Request req;
  17779. req.method = "GE T";
  17780. req.path = "/";
  17781. auto start = std::chrono::steady_clock::now();
  17782. auto res = cli.send(req);
  17783. EXPECT_FALSE(res);
  17784. EXPECT_EQ(Error::Write, res.error());
  17785. EXPECT_LT(elapsed_ms(start), 1000);
  17786. }
  17787. {
  17788. auto start = std::chrono::steady_clock::now();
  17789. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17790. EXPECT_FALSE(res);
  17791. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17792. EXPECT_LT(elapsed_ms(start), 1000);
  17793. }
  17794. EXPECT_FALSE(cli.is_socket_open());
  17795. detail::close_socket(srv);
  17796. }
  17797. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17798. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17799. default_socket_options(srv);
  17800. sockaddr_in addr{};
  17801. addr.sin_family = AF_INET;
  17802. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17803. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17804. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17805. ASSERT_EQ(0, ::listen(srv, 1));
  17806. std::string received;
  17807. auto server_thread = std::thread([&] {
  17808. auto sock = ::accept(srv, nullptr, nullptr);
  17809. if (sock == INVALID_SOCKET) { return; }
  17810. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17811. char buf[2048];
  17812. ssize_t n;
  17813. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17814. received.append(buf, static_cast<size_t>(n));
  17815. }
  17816. detail::close_socket(sock);
  17817. });
  17818. {
  17819. auto cli = Client("127.0.0.1", PORT + 1);
  17820. // "Z" sorts after the default headers, so writing straight to the socket
  17821. // would have sent the request line and those headers before the rejection.
  17822. auto handle =
  17823. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17824. EXPECT_FALSE(handle.is_valid());
  17825. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17826. }
  17827. server_thread.join();
  17828. detail::close_socket(srv);
  17829. EXPECT_TRUE(received.empty()) << received;
  17830. }
  17831. TEST(PathParamsTest, StaticMatch) {
  17832. const auto pattern = "/users/all";
  17833. detail::PathParamsMatcher matcher(pattern);
  17834. Request request;
  17835. request.path = "/users/all";
  17836. ASSERT_TRUE(matcher.match(request));
  17837. std::unordered_map<std::string, std::string> expected_params = {};
  17838. EXPECT_EQ(request.path_params, expected_params);
  17839. }
  17840. TEST(PathParamsTest, StaticMismatch) {
  17841. const auto pattern = "/users/all";
  17842. detail::PathParamsMatcher matcher(pattern);
  17843. Request request;
  17844. request.path = "/users/1";
  17845. ASSERT_FALSE(matcher.match(request));
  17846. }
  17847. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17848. const auto pattern = "/users/:id/subscriptions";
  17849. detail::PathParamsMatcher matcher(pattern);
  17850. Request request;
  17851. request.path = "/users/42/subscriptions";
  17852. ASSERT_TRUE(matcher.match(request));
  17853. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17854. EXPECT_EQ(request.path_params, expected_params);
  17855. }
  17856. TEST(PathParamsTest, SingleParamInTheEnd) {
  17857. const auto pattern = "/users/:id";
  17858. detail::PathParamsMatcher matcher(pattern);
  17859. Request request;
  17860. request.path = "/users/24";
  17861. ASSERT_TRUE(matcher.match(request));
  17862. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17863. EXPECT_EQ(request.path_params, expected_params);
  17864. }
  17865. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17866. const auto pattern = "/users/:id/";
  17867. detail::PathParamsMatcher matcher(pattern);
  17868. Request request;
  17869. request.path = "/users/42/";
  17870. ASSERT_TRUE(matcher.match(request));
  17871. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17872. EXPECT_EQ(request.path_params, expected_params);
  17873. }
  17874. TEST(PathParamsTest, EmptyParam) {
  17875. const auto pattern = "/users/:id/";
  17876. detail::PathParamsMatcher matcher(pattern);
  17877. Request request;
  17878. request.path = "/users//";
  17879. ASSERT_TRUE(matcher.match(request));
  17880. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17881. EXPECT_EQ(request.path_params, expected_params);
  17882. }
  17883. TEST(PathParamsTest, FragmentMismatch) {
  17884. const auto pattern = "/users/:id/";
  17885. detail::PathParamsMatcher matcher(pattern);
  17886. Request request;
  17887. request.path = "/admins/24/";
  17888. ASSERT_FALSE(matcher.match(request));
  17889. }
  17890. TEST(PathParamsTest, ExtraFragments) {
  17891. const auto pattern = "/users/:id";
  17892. detail::PathParamsMatcher matcher(pattern);
  17893. Request request;
  17894. request.path = "/users/42/subscriptions";
  17895. ASSERT_FALSE(matcher.match(request));
  17896. }
  17897. TEST(PathParamsTest, MissingTrailingParam) {
  17898. const auto pattern = "/users/:id";
  17899. detail::PathParamsMatcher matcher(pattern);
  17900. Request request;
  17901. request.path = "/users";
  17902. ASSERT_FALSE(matcher.match(request));
  17903. }
  17904. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17905. const auto pattern = "/users/:id/subscriptions";
  17906. detail::PathParamsMatcher matcher(pattern);
  17907. Request request;
  17908. request.path = "/users/subscriptions";
  17909. ASSERT_FALSE(matcher.match(request));
  17910. }
  17911. TEST(PathParamsTest, MultipleParams) {
  17912. const auto pattern = "/users/:userid/subscriptions/:subid";
  17913. detail::PathParamsMatcher matcher(pattern);
  17914. Request request;
  17915. request.path = "/users/42/subscriptions/2";
  17916. ASSERT_TRUE(matcher.match(request));
  17917. std::unordered_map<std::string, std::string> expected_params = {
  17918. {"userid", "42"}, {"subid", "2"}};
  17919. EXPECT_EQ(request.path_params, expected_params);
  17920. }
  17921. TEST(PathParamsTest, SequenceOfParams) {
  17922. const auto pattern = "/values/:x/:y/:z";
  17923. detail::PathParamsMatcher matcher(pattern);
  17924. Request request;
  17925. request.path = "/values/1/2/3";
  17926. ASSERT_TRUE(matcher.match(request));
  17927. std::unordered_map<std::string, std::string> expected_params = {
  17928. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17929. EXPECT_EQ(request.path_params, expected_params);
  17930. }
  17931. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17932. const auto pattern = "/prefix:suffix";
  17933. detail::PathParamsMatcher matcher(pattern);
  17934. Request request;
  17935. request.path = "/prefix:suffix";
  17936. ASSERT_TRUE(matcher.match(request));
  17937. const std::unordered_map<std::string, std::string> expected_params = {};
  17938. EXPECT_EQ(request.path_params, expected_params);
  17939. }
  17940. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17941. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17942. // calling thread's stack on a long enough path for a quantified pattern;
  17943. // RegexMatcher must refuse to run regex matching on paths beyond
  17944. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17945. detail::RegexMatcher matcher("/files/(.*)");
  17946. Request within_limit;
  17947. within_limit.path = "/files/" + std::string(10, 'A');
  17948. EXPECT_TRUE(matcher.match(within_limit));
  17949. Request over_limit;
  17950. over_limit.path =
  17951. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17952. EXPECT_FALSE(matcher.match(over_limit));
  17953. }
  17954. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17955. Server svr;
  17956. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17957. res.set_content("ok", "text/plain");
  17958. });
  17959. auto port = svr.bind_to_any_port(HOST);
  17960. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17961. auto se = detail::scope_exit([&] {
  17962. svr.stop();
  17963. thread.join();
  17964. ASSERT_FALSE(svr.is_running());
  17965. });
  17966. svr.wait_until_ready();
  17967. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17968. // request URI limit; this used to be able to crash the process.
  17969. std::string path =
  17970. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17971. std::string req = "GET " + path +
  17972. " HTTP/1.1\r\n"
  17973. "Host: " +
  17974. std::string(HOST) + ":" + std::to_string(port) +
  17975. "\r\n"
  17976. "Connection: close\r\n"
  17977. "\r\n";
  17978. std::string response;
  17979. ASSERT_TRUE(send_request(5, req, &response, port));
  17980. EXPECT_NE(std::string::npos, response.find("404"));
  17981. }
  17982. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17983. Server svr;
  17984. auto handler = [](const Request & /*req*/, Response &res) {
  17985. res.set_content("hit", "text/plain");
  17986. };
  17987. // No regex metacharacter, so this one is compared literally
  17988. svr.Get("/literal/route", handler);
  17989. // '.' is a regex metacharacter, so this one must keep regex semantics
  17990. svr.Get("/a.c", handler);
  17991. auto port = svr.bind_to_any_port(HOST);
  17992. std::thread t([&]() { svr.listen_after_bind(); });
  17993. auto se = detail::scope_exit([&] {
  17994. svr.stop();
  17995. t.join();
  17996. ASSERT_FALSE(svr.is_running());
  17997. });
  17998. svr.wait_until_ready();
  17999. Client cli(HOST, port);
  18000. struct {
  18001. const char *path;
  18002. int status;
  18003. } cases[] = {
  18004. {"/literal/route", StatusCode::OK_200},
  18005. {"/literal/routes", StatusCode::NotFound_404},
  18006. {"/literal/rout", StatusCode::NotFound_404},
  18007. {"/abc", StatusCode::OK_200},
  18008. {"/a.c", StatusCode::OK_200},
  18009. };
  18010. for (const auto &x : cases) {
  18011. auto res = cli.Get(x.path);
  18012. ASSERT_TRUE(res) << x.path;
  18013. EXPECT_EQ(x.status, res->status) << x.path;
  18014. }
  18015. }
  18016. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18017. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18018. // from exhausting the stack, so it must only constrain routes that actually
  18019. // run a regular expression. A literal route is matched by comparison and
  18020. // stays usable at any length.
  18021. Server svr;
  18022. const std::string pattern =
  18023. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18024. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18025. res.set_content("hit", "text/plain");
  18026. });
  18027. auto port = svr.bind_to_any_port(HOST);
  18028. std::thread t([&]() { svr.listen_after_bind(); });
  18029. auto se = detail::scope_exit([&] {
  18030. svr.stop();
  18031. t.join();
  18032. ASSERT_FALSE(svr.is_running());
  18033. });
  18034. svr.wait_until_ready();
  18035. Client cli(HOST, port);
  18036. auto res = cli.Get(pattern);
  18037. ASSERT_TRUE(res);
  18038. EXPECT_EQ(StatusCode::OK_200, res->status);
  18039. }
  18040. TEST(ParseUrlTest, VariousPatterns) {
  18041. {
  18042. detail::UrlComponents uc;
  18043. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18044. EXPECT_EQ("http", uc.scheme);
  18045. EXPECT_EQ("example.com", uc.host);
  18046. EXPECT_EQ("8080", uc.port);
  18047. EXPECT_EQ("/path", uc.path);
  18048. EXPECT_EQ("?q=1", uc.query);
  18049. }
  18050. {
  18051. detail::UrlComponents uc;
  18052. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18053. EXPECT_EQ("https", uc.scheme);
  18054. EXPECT_EQ("example.com", uc.host);
  18055. EXPECT_TRUE(uc.port.empty());
  18056. EXPECT_EQ("/path", uc.path);
  18057. }
  18058. {
  18059. detail::UrlComponents uc;
  18060. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18061. EXPECT_EQ("::1", uc.host);
  18062. EXPECT_EQ("8080", uc.port);
  18063. EXPECT_EQ("/path", uc.path);
  18064. }
  18065. {
  18066. detail::UrlComponents uc;
  18067. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18068. }
  18069. {
  18070. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18071. // the path while the connection still targets the bracketed host.
  18072. detail::UrlComponents uc;
  18073. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18074. }
  18075. {
  18076. detail::UrlComponents uc;
  18077. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18078. }
  18079. {
  18080. detail::UrlComponents uc;
  18081. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18082. EXPECT_EQ("::1", uc.host);
  18083. EXPECT_TRUE(uc.port.empty());
  18084. EXPECT_EQ("/path", uc.path);
  18085. }
  18086. {
  18087. detail::UrlComponents uc;
  18088. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18089. EXPECT_TRUE(uc.scheme.empty());
  18090. EXPECT_EQ("example.com", uc.host);
  18091. EXPECT_EQ("/path", uc.path);
  18092. EXPECT_EQ("?q=1", uc.query);
  18093. }
  18094. {
  18095. detail::UrlComponents uc;
  18096. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18097. EXPECT_TRUE(uc.host.empty());
  18098. EXPECT_EQ("/path", uc.path);
  18099. EXPECT_EQ("?q=1", uc.query);
  18100. }
  18101. {
  18102. detail::UrlComponents uc;
  18103. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18104. EXPECT_EQ("example.com", uc.host);
  18105. EXPECT_EQ("8080", uc.port);
  18106. }
  18107. {
  18108. // Unix socket path — must not be parsed as host
  18109. detail::UrlComponents uc;
  18110. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18111. EXPECT_TRUE(uc.host.empty());
  18112. }
  18113. {
  18114. detail::UrlComponents uc;
  18115. ASSERT_TRUE(detail::parse_url("", uc));
  18116. EXPECT_TRUE(uc.host.empty());
  18117. EXPECT_TRUE(uc.path.empty());
  18118. }
  18119. {
  18120. detail::UrlComponents uc;
  18121. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18122. }
  18123. {
  18124. detail::UrlComponents uc;
  18125. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18126. }
  18127. {
  18128. // Accepted by parse_url; callers restrict to http/https
  18129. detail::UrlComponents uc;
  18130. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18131. EXPECT_EQ("ftp", uc.scheme);
  18132. }
  18133. {
  18134. detail::UrlComponents uc;
  18135. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18136. }
  18137. {
  18138. detail::UrlComponents uc;
  18139. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18140. }
  18141. }
  18142. TEST(ParseUrlTest, FragmentHandling) {
  18143. {
  18144. detail::UrlComponents uc;
  18145. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18146. EXPECT_EQ("/path", uc.path);
  18147. EXPECT_TRUE(uc.query.empty());
  18148. }
  18149. {
  18150. detail::UrlComponents uc;
  18151. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18152. EXPECT_TRUE(uc.path.empty());
  18153. EXPECT_TRUE(uc.query.empty());
  18154. }
  18155. }
  18156. TEST(ParseUrlTest, UserinfoHandling) {
  18157. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18158. // parsers would see evil.com as the host.
  18159. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18160. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18161. for (auto url : urls) {
  18162. detail::UrlComponents uc;
  18163. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18164. }
  18165. }
  18166. TEST(ParseUrlTest, IPv6EdgeCases) {
  18167. {
  18168. detail::UrlComponents uc;
  18169. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18170. EXPECT_TRUE(uc.scheme.empty());
  18171. EXPECT_EQ("::1", uc.host);
  18172. EXPECT_EQ("8080", uc.port);
  18173. }
  18174. {
  18175. // Zone ID '%25' is not in [a-fA-F0-9:]
  18176. detail::UrlComponents uc;
  18177. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18178. }
  18179. }
  18180. TEST(ParseUrlTest, SchemeEdgeCases) {
  18181. {
  18182. detail::UrlComponents uc;
  18183. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18184. }
  18185. {
  18186. detail::UrlComponents uc;
  18187. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18188. }
  18189. {
  18190. detail::UrlComponents uc;
  18191. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18192. }
  18193. }
  18194. TEST(ParseUrlTest, PortEdgeCases) {
  18195. {
  18196. detail::UrlComponents uc;
  18197. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18198. EXPECT_TRUE(uc.port.empty());
  18199. EXPECT_EQ("/path", uc.path);
  18200. }
  18201. {
  18202. // parse_url accepts any port string; validation is done by parse_port
  18203. detail::UrlComponents uc;
  18204. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18205. EXPECT_EQ("abc", uc.port);
  18206. }
  18207. }
  18208. TEST(ParseUrlTest, WebSocketPatterns) {
  18209. {
  18210. detail::UrlComponents uc;
  18211. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18212. EXPECT_EQ("ws", uc.scheme);
  18213. EXPECT_EQ("echo.example.com", uc.host);
  18214. EXPECT_EQ("8080", uc.port);
  18215. EXPECT_EQ("/ws", uc.path);
  18216. }
  18217. {
  18218. detail::UrlComponents uc;
  18219. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18220. EXPECT_EQ("wss", uc.scheme);
  18221. EXPECT_EQ("echo.example.com", uc.host);
  18222. EXPECT_TRUE(uc.port.empty());
  18223. EXPECT_EQ("/ws", uc.path);
  18224. }
  18225. }
  18226. TEST(ParseUrlTest, QueryOnly) {
  18227. detail::UrlComponents uc;
  18228. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18229. EXPECT_TRUE(uc.host.empty());
  18230. EXPECT_TRUE(uc.path.empty());
  18231. EXPECT_EQ("?q=1&r=2", uc.query);
  18232. }
  18233. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18234. detail::UrlComponents uc;
  18235. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18236. EXPECT_TRUE(uc.scheme.empty());
  18237. EXPECT_EQ("example.com", uc.host);
  18238. EXPECT_EQ("443", uc.port);
  18239. EXPECT_EQ("/path", uc.path);
  18240. }
  18241. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18242. // If ipv6 regex working, regex match codepath is taken.
  18243. // else port will default to 80 in Client impl
  18244. int clientImplMagicPort = 80;
  18245. int port = 4321;
  18246. // above ports must be different to avoid false negative
  18247. EXPECT_NE(clientImplMagicPort, port);
  18248. std::string ipV6TestURL = "http://[ff06::c3]";
  18249. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18250. CLIENT_PRIVATE_KEY_FILE);
  18251. EXPECT_EQ(cli.port(), port);
  18252. }
  18253. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18254. auto file_path = "./www/dir/index.html";
  18255. auto dir_path = "./www/dir";
  18256. detail::FileStat stat_file(file_path);
  18257. EXPECT_TRUE(stat_file.is_file());
  18258. EXPECT_FALSE(stat_file.is_dir());
  18259. detail::FileStat stat_dir(dir_path);
  18260. EXPECT_FALSE(stat_dir.is_file());
  18261. EXPECT_TRUE(stat_dir.is_dir());
  18262. }
  18263. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18264. // IPv4 with default HTTP port (80)
  18265. EXPECT_EQ("example.com",
  18266. detail::make_host_and_port_string("example.com", 80, false));
  18267. // IPv4 with default HTTPS port (443)
  18268. EXPECT_EQ("example.com",
  18269. detail::make_host_and_port_string("example.com", 443, true));
  18270. // IPv4 with non-default HTTP port
  18271. EXPECT_EQ("example.com:8080",
  18272. detail::make_host_and_port_string("example.com", 8080, false));
  18273. // IPv4 with non-default HTTPS port
  18274. EXPECT_EQ("example.com:8443",
  18275. detail::make_host_and_port_string("example.com", 8443, true));
  18276. // IPv6 with default HTTP port (80)
  18277. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18278. // IPv6 with default HTTPS port (443)
  18279. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18280. // IPv6 with non-default HTTP port
  18281. EXPECT_EQ("[::1]:8080",
  18282. detail::make_host_and_port_string("::1", 8080, false));
  18283. // IPv6 with non-default HTTPS port
  18284. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18285. // IPv6 full address with default port
  18286. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18287. detail::make_host_and_port_string(
  18288. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18289. // IPv6 full address with non-default port
  18290. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18291. detail::make_host_and_port_string(
  18292. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18293. // IPv6 localhost with non-default port
  18294. EXPECT_EQ("[::1]:3000",
  18295. detail::make_host_and_port_string("::1", 3000, false));
  18296. // IPv6 with zone ID (link-local address) with default port
  18297. EXPECT_EQ("[fe80::1%eth0]",
  18298. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18299. // IPv6 with zone ID (link-local address) with non-default port
  18300. EXPECT_EQ("[fe80::1%eth0]:8080",
  18301. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18302. // Edge case: Port 443 with is_ssl=false (should add port)
  18303. EXPECT_EQ("example.com:443",
  18304. detail::make_host_and_port_string("example.com", 443, false));
  18305. // Edge case: Port 80 with is_ssl=true (should add port)
  18306. EXPECT_EQ("example.com:80",
  18307. detail::make_host_and_port_string("example.com", 80, true));
  18308. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18309. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18310. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18311. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18312. // Security fix: Already bracketed IPv6 should not get double brackets
  18313. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18314. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18315. EXPECT_EQ("[::1]:8080",
  18316. detail::make_host_and_port_string("[::1]", 8080, false));
  18317. EXPECT_EQ("[2001:db8::1]:8080",
  18318. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18319. EXPECT_EQ("[fe80::1%eth0]",
  18320. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18321. EXPECT_EQ("[fe80::1%eth0]:8080",
  18322. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18323. // Edge case: Empty host (should return as-is)
  18324. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18325. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18326. // This is a known limitation but shouldn't crash
  18327. EXPECT_EQ("[host:name]",
  18328. detail::make_host_and_port_string("host:name", 80, false));
  18329. // Port number edge cases (no validation, but should not crash)
  18330. EXPECT_EQ("example.com:0",
  18331. detail::make_host_and_port_string("example.com", 0, false));
  18332. EXPECT_EQ("example.com:-1",
  18333. detail::make_host_and_port_string("example.com", -1, false));
  18334. EXPECT_EQ("example.com:65535",
  18335. detail::make_host_and_port_string("example.com", 65535, false));
  18336. EXPECT_EQ("example.com:65536",
  18337. detail::make_host_and_port_string("example.com", 65536, false));
  18338. }
  18339. namespace httplib {
  18340. namespace detail {
  18341. std::string
  18342. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18343. const std::string &host, int port);
  18344. } // namespace detail
  18345. } // namespace httplib
  18346. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18347. std::map<std::string, std::string> addr_map = {
  18348. {"ipv4.example", "192.0.2.10"},
  18349. {"ipv6.example", "2001:db8::1"},
  18350. {"name.example", "internal.example.lan"},
  18351. {"empty.example", ""}};
  18352. EXPECT_EQ("192.0.2.10:443",
  18353. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18354. EXPECT_EQ("[2001:db8::1]:443",
  18355. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18356. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18357. addr_map, "name.example", 8443));
  18358. // An empty or absent mapping keeps the hostname as the target
  18359. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18360. addr_map, "empty.example", 443));
  18361. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18362. addr_map, "other.example", 443));
  18363. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18364. }
  18365. #ifdef CPPHTTPLIB_SSL_ENABLED
  18366. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18367. httplib::SSLClient cli("roblox.com", 443);
  18368. cli.set_follow_location(true);
  18369. auto res = cli.Get("/");
  18370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18371. EXPECT_EQ(StatusCode::OK_200, res->status);
  18372. }
  18373. #endif
  18374. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18375. Server svr;
  18376. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18377. EXPECT_EQ(res.status, 400);
  18378. });
  18379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18380. auto se = detail::scope_exit([&] {
  18381. svr.stop();
  18382. thread.join();
  18383. ASSERT_FALSE(svr.is_running());
  18384. });
  18385. svr.wait_until_ready();
  18386. Client cli(HOST, PORT);
  18387. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18388. }
  18389. TEST(InvalidHeaderCharsTest, is_field_name) {
  18390. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18391. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18392. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18393. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18394. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18395. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18396. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18397. EXPECT_FALSE(detail::fields::is_field_name(""));
  18398. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18399. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18400. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18401. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18402. }
  18403. TEST(InvalidHeaderCharsTest, is_field_value) {
  18404. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18405. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18406. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18407. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18408. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18409. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18410. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18411. EXPECT_TRUE(detail::fields::is_field_value(""));
  18412. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18413. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18414. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18415. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18416. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18417. }
  18418. TEST(InvalidHeaderCharsTest, OnServer) {
  18419. Server svr;
  18420. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18421. std::string header = "Not Set";
  18422. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18423. res.set_header(header, "value");
  18424. res.set_content("Page Content Page Content", "text/plain");
  18425. });
  18426. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18427. std::string header = "Not Set";
  18428. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18429. res.set_header("X-Test", header);
  18430. res.set_content("Page Content Page Content", "text/plain");
  18431. });
  18432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18433. auto se = detail::scope_exit([&] {
  18434. svr.stop();
  18435. thread.join();
  18436. ASSERT_FALSE(svr.is_running());
  18437. });
  18438. svr.wait_until_ready();
  18439. Client cli(HOST, PORT);
  18440. {
  18441. auto res = cli.Get(
  18442. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18444. EXPECT_EQ("Page Content Page Content", res->body);
  18445. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18446. }
  18447. {
  18448. auto res = cli.Get(
  18449. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18451. EXPECT_EQ("Page Content Page Content", res->body);
  18452. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18453. }
  18454. }
  18455. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18456. auto handled = false;
  18457. Server svr;
  18458. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18459. thread t = thread([&] { svr.listen(HOST, PORT); });
  18460. auto se = detail::scope_exit([&] {
  18461. svr.stop();
  18462. t.join();
  18463. ASSERT_FALSE(svr.is_running());
  18464. ASSERT_FALSE(handled);
  18465. });
  18466. svr.wait_until_ready();
  18467. auto req = "POST /test HTTP/1.1\r\n"
  18468. "Content-Length: x\r\n"
  18469. "\r\n";
  18470. std::string response;
  18471. ASSERT_TRUE(send_request(1, req, &response));
  18472. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18473. response.substr(0, response.find("\r\n")));
  18474. }
  18475. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18476. // case-insensitive, and a server that receives a 100-continue expectation in
  18477. // an HTTP/1.0 request MUST ignore it.
  18478. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18479. std::string response;
  18480. ASSERT_TRUE(send_request(1, req, &response, port));
  18481. *got_100 = response.find("100 Continue") != std::string::npos;
  18482. }
  18483. class ExpectTokenTest : public ::testing::Test {
  18484. protected:
  18485. void SetUp() override {
  18486. svr_.Post("/p", [](const Request &, Response &res) {
  18487. res.set_content("ok", "text/plain");
  18488. });
  18489. port_ = svr_.bind_to_any_port(HOST);
  18490. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18491. svr_.wait_until_ready();
  18492. }
  18493. void TearDown() override {
  18494. svr_.stop();
  18495. if (thread_.joinable()) { thread_.join(); }
  18496. }
  18497. std::string request(const char *version, const char *expect_value) const {
  18498. return std::string("POST /p ") + version +
  18499. "\r\n"
  18500. "Host: localhost\r\n"
  18501. "Content-Length: 2\r\n"
  18502. "Connection: close\r\n"
  18503. "Expect: " +
  18504. expect_value +
  18505. "\r\n"
  18506. "\r\n"
  18507. "hi";
  18508. }
  18509. Server svr_;
  18510. int port_ = 0;
  18511. thread thread_;
  18512. };
  18513. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18514. bool got_100 = false;
  18515. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18516. EXPECT_TRUE(got_100);
  18517. }
  18518. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18519. bool got_100 = true;
  18520. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18521. EXPECT_FALSE(got_100);
  18522. }
  18523. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18524. bool got_100 = false;
  18525. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18526. EXPECT_TRUE(got_100);
  18527. }
  18528. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18529. bool got_100 = false;
  18530. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18531. EXPECT_TRUE(got_100);
  18532. }
  18533. // `100 Continue` is sent only when the server starts reading the body, so a
  18534. // request rejected before that never invites the client to send it. The
  18535. // requests below carry the expectation but withhold the body, as a client
  18536. // waiting for `100 Continue` would.
  18537. // A POST that expects `100 Continue` and withholds its two-byte body.
  18538. static std::string expect_headers_only(const std::string &path) {
  18539. return "POST " + path +
  18540. " HTTP/1.1\r\n"
  18541. "Host: localhost\r\n"
  18542. "Content-Length: 2\r\n"
  18543. "Expect: 100-continue\r\n"
  18544. "\r\n";
  18545. }
  18546. class ExpectLazyContinueTest : public ::testing::Test {
  18547. protected:
  18548. void SetUp() override {
  18549. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18550. if (req.path == "/pre-routing") {
  18551. res.status = StatusCode::Unauthorized_401;
  18552. return Server::HandlerResponse::Handled;
  18553. }
  18554. return Server::HandlerResponse::Unhandled;
  18555. });
  18556. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18557. if (req.matched_route == "/pre-request") {
  18558. res.status = StatusCode::Forbidden_403;
  18559. return Server::HandlerResponse::Handled;
  18560. }
  18561. return Server::HandlerResponse::Unhandled;
  18562. });
  18563. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18564. res.set_content("ok", "text/plain");
  18565. });
  18566. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18567. res.set_content("ok", "text/plain");
  18568. });
  18569. svr_.Post("/reader-used", [](const Request &, Response &res,
  18570. const ContentReader &content_reader) {
  18571. std::string body;
  18572. content_reader([&](const char *data, size_t len) {
  18573. body.append(data, len);
  18574. return true;
  18575. });
  18576. res.set_content(body, "text/plain");
  18577. });
  18578. svr_.Post("/reader-unused",
  18579. [](const Request &, Response &res, const ContentReader &) {
  18580. res.set_content("ignored", "text/plain");
  18581. });
  18582. port_ = svr_.bind_to_any_port(HOST);
  18583. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18584. svr_.wait_until_ready();
  18585. }
  18586. void TearDown() override {
  18587. svr_.stop();
  18588. if (thread_.joinable()) { thread_.join(); }
  18589. }
  18590. // Sends `req` and reads until the server closes the connection. Returns
  18591. // false if the read had to wait for the client-side timeout instead.
  18592. bool send_until_closed(const std::string &req, std::string *resp) const {
  18593. auto start = std::chrono::steady_clock::now();
  18594. if (!send_request(3, req, resp, port_)) { return false; }
  18595. auto elapsed = std::chrono::steady_clock::now() - start;
  18596. return elapsed < std::chrono::seconds(2);
  18597. }
  18598. // The final response comes without `100 Continue`, and the server closes
  18599. // the connection since the body may or may not follow.
  18600. void expect_final_without_interim(const std::string &path,
  18601. const char *status_line) const {
  18602. std::string resp;
  18603. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18604. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18605. EXPECT_EQ(0u, resp.find(status_line));
  18606. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18607. }
  18608. Server svr_;
  18609. int port_ = 0;
  18610. thread thread_;
  18611. };
  18612. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18613. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18614. }
  18615. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18616. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18617. }
  18618. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18619. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18620. }
  18621. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18622. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18623. }
  18624. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18625. // The body follows once `100 Continue` has had time to arrive.
  18626. auto req = expect_headers_only("/reader-used");
  18627. req.insert(req.size() - 2, "Connection: close\r\n");
  18628. std::string resp;
  18629. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18630. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18631. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18632. EXPECT_NE(std::string::npos, resp.find("hi"));
  18633. }
  18634. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18635. // Large enough for the client to add `Expect: 100-continue` itself.
  18636. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18637. std::atomic<bool> body_sent{false};
  18638. Client cli(HOST, port_);
  18639. auto res = cli.Post(
  18640. "/pre-request", length,
  18641. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18642. body_sent = true;
  18643. std::string chunk(len, 'x');
  18644. sink.write(chunk.data(), chunk.size());
  18645. return true;
  18646. },
  18647. "application/octet-stream");
  18648. ASSERT_TRUE(res);
  18649. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18650. EXPECT_FALSE(body_sent);
  18651. }
  18652. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18653. Server svr;
  18654. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18655. return StatusCode::ExpectationFailed_417;
  18656. });
  18657. svr.Post("/p", [](const Request &, Response &res) {
  18658. res.set_content("ok", "text/plain");
  18659. });
  18660. auto port = svr.bind_to_any_port(HOST);
  18661. thread t = thread([&] { svr.listen_after_bind(); });
  18662. auto se = detail::scope_exit([&] {
  18663. svr.stop();
  18664. t.join();
  18665. });
  18666. svr.wait_until_ready();
  18667. std::string resp;
  18668. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18669. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18670. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18671. // Exactly one response: the route handler must not run after the 417.
  18672. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18673. }
  18674. #ifndef _WIN32
  18675. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18676. static constexpr char reject[] = "Unauthorized";
  18677. static constexpr char accept[] = "Upload accepted";
  18678. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18679. Server svr;
  18680. svr.set_expect_100_continue_handler(
  18681. [](const Request & /*req*/, Response &res) {
  18682. res.status = StatusCode::Unauthorized_401;
  18683. res.set_content(reject, "text/plain");
  18684. return res.status;
  18685. });
  18686. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18687. res.set_content(accept, "text/plain");
  18688. });
  18689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18690. auto se = detail::scope_exit([&] {
  18691. svr.stop();
  18692. thread.join();
  18693. ASSERT_FALSE(svr.is_running());
  18694. });
  18695. svr.wait_until_ready();
  18696. {
  18697. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18698. curl_easy_init(), &curl_easy_cleanup};
  18699. ASSERT_NE(curl, nullptr);
  18700. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18701. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18702. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18703. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18704. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18705. &curl_slist_free_all};
  18706. ASSERT_NE(list, nullptr);
  18707. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18708. struct read_data {
  18709. uint64_t read_size;
  18710. uint64_t total_size;
  18711. } data = {0, total_size};
  18712. using read_callback_t =
  18713. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18714. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18715. void *userdata) -> size_t {
  18716. read_data *d = (read_data *)userdata;
  18717. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18718. std::fill_n(ptr, size * nmemb, 'A');
  18719. d->read_size += size * nmemb;
  18720. return size * nmemb;
  18721. };
  18722. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18723. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18724. std::vector<char> buffer;
  18725. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18726. using write_callback_t =
  18727. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18728. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18729. void *userdata) -> size_t {
  18730. std::vector<char> *buf = (std::vector<char> *)userdata;
  18731. buf->reserve(buf->size() + size * nmemb + 1);
  18732. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18733. return size * nmemb;
  18734. };
  18735. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18736. {
  18737. const auto res = curl_easy_perform(curl.get());
  18738. ASSERT_EQ(res, CURLE_OK);
  18739. }
  18740. {
  18741. auto response_code = long{};
  18742. const auto res =
  18743. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18744. ASSERT_EQ(res, CURLE_OK);
  18745. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18746. }
  18747. {
  18748. auto dl = curl_off_t{};
  18749. const auto res =
  18750. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18751. ASSERT_EQ(res, CURLE_OK);
  18752. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18753. }
  18754. {
  18755. buffer.push_back('\0');
  18756. ASSERT_STRCASEEQ(buffer.data(), reject);
  18757. }
  18758. }
  18759. }
  18760. #endif
  18761. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18762. // Regression test for #2458.
  18763. //
  18764. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18765. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18766. // ticket can make the client socket spuriously readable during the
  18767. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18768. // the client withholds the body and then blocks reading a response that never
  18769. // comes, failing with `Failed to read connection`.
  18770. //
  18771. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18772. // within the timeout. This raw OpenSSL server deliberately never sends
  18773. // `100 Continue`; the client must still deliver the body and receive 200.
  18774. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18775. signal(SIGPIPE, SIG_IGN);
  18776. const auto port = PORT + 4;
  18777. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18778. ASSERT_NE(srv, INVALID_SOCKET);
  18779. int opt = 1;
  18780. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18781. sockaddr_in addr{};
  18782. addr.sin_family = AF_INET;
  18783. addr.sin_port = htons(static_cast<uint16_t>(port));
  18784. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18785. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18786. ASSERT_EQ(0, ::listen(srv, 1));
  18787. std::atomic<size_t> server_body_bytes{0};
  18788. auto server_thread = std::thread([&] {
  18789. sockaddr_in cli_addr{};
  18790. socklen_t cli_len = sizeof(cli_addr);
  18791. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18792. if (cli == INVALID_SOCKET) { return; }
  18793. // Bound the lifetime of the server side so a buggy client (which never
  18794. // sends the body) cannot make this thread block forever on join.
  18795. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18796. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18797. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18798. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18799. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18800. SSL *ssl = SSL_new(ctx);
  18801. SSL_set_fd(ssl, static_cast<int>(cli));
  18802. if (SSL_accept(ssl) > 0) {
  18803. // Read the request headers. Reading here also flushes the TLS 1.3
  18804. // session tickets to the client. Deliberately do NOT send
  18805. // `100 Continue`.
  18806. std::string buf;
  18807. char tmp[1024];
  18808. while (buf.find("\r\n\r\n") == std::string::npos) {
  18809. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18810. if (n <= 0) { break; }
  18811. buf.append(tmp, static_cast<size_t>(n));
  18812. }
  18813. // A correct client sends the body now; count what arrives.
  18814. auto pos = buf.find("\r\n\r\n");
  18815. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18816. while (body < 4096) {
  18817. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18818. if (n <= 0) { break; }
  18819. body += static_cast<size_t>(n);
  18820. }
  18821. server_body_bytes = body;
  18822. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18823. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18824. SSL_shutdown(ssl);
  18825. }
  18826. SSL_free(ssl);
  18827. detail::close_socket(cli);
  18828. SSL_CTX_free(ctx);
  18829. });
  18830. auto se = detail::scope_exit([&] {
  18831. server_thread.join();
  18832. detail::close_socket(srv);
  18833. });
  18834. SSLClient cli("127.0.0.1", port);
  18835. cli.enable_server_certificate_verification(false);
  18836. cli.set_connection_timeout(5, 0);
  18837. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18838. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18839. std::string body(4096, 'A');
  18840. auto res = cli.Put("/api/test", body, "application/json");
  18841. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18842. EXPECT_EQ(StatusCode::OK_200, res->status);
  18843. EXPECT_EQ(body.size(), server_body_bytes.load());
  18844. }
  18845. #endif
  18846. template <typename S, typename C>
  18847. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18848. svr.Get("/stream", [&](const Request &, Response &res) {
  18849. auto data = new std::string("01234567890123456789");
  18850. res.set_content_provider(
  18851. data->size(), "text/plain",
  18852. [&, data](size_t offset, size_t length, DataSink &sink) {
  18853. const size_t DATA_CHUNK_SIZE = 4;
  18854. const auto &d = *data;
  18855. std::this_thread::sleep_for(std::chrono::seconds(1));
  18856. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18857. return true;
  18858. },
  18859. [data](bool success) {
  18860. EXPECT_FALSE(success);
  18861. delete data;
  18862. });
  18863. });
  18864. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18865. auto i = new size_t(0);
  18866. res.set_content_provider(
  18867. "text/plain",
  18868. [i](size_t, DataSink &sink) {
  18869. if (*i < 5) {
  18870. std::this_thread::sleep_for(std::chrono::seconds(1));
  18871. sink.write("abcd", 4);
  18872. (*i)++;
  18873. } else {
  18874. sink.done();
  18875. }
  18876. return true;
  18877. },
  18878. [i](bool success) {
  18879. EXPECT_FALSE(success);
  18880. delete i;
  18881. });
  18882. });
  18883. svr.Get("/chunked", [&](const Request &, Response &res) {
  18884. auto i = new size_t(0);
  18885. res.set_chunked_content_provider(
  18886. "text/plain",
  18887. [i](size_t, DataSink &sink) {
  18888. if (*i < 5) {
  18889. std::this_thread::sleep_for(std::chrono::seconds(1));
  18890. sink.os << "abcd";
  18891. (*i)++;
  18892. } else {
  18893. sink.done();
  18894. }
  18895. return true;
  18896. },
  18897. [i](bool success) {
  18898. EXPECT_FALSE(success);
  18899. delete i;
  18900. });
  18901. });
  18902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18903. auto se = detail::scope_exit([&] {
  18904. svr.stop();
  18905. listen_thread.join();
  18906. ASSERT_FALSE(svr.is_running());
  18907. });
  18908. svr.wait_until_ready();
  18909. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18910. {
  18911. auto start = std::chrono::steady_clock::now();
  18912. auto res = cli.Get("/stream");
  18913. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18914. std::chrono::steady_clock::now() - start)
  18915. .count();
  18916. ASSERT_FALSE(res);
  18917. EXPECT_EQ(Error::Read, res.error());
  18918. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18919. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18920. }
  18921. {
  18922. auto start = std::chrono::steady_clock::now();
  18923. auto res = cli.Get("/stream_without_length");
  18924. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18925. std::chrono::steady_clock::now() - start)
  18926. .count();
  18927. ASSERT_FALSE(res);
  18928. EXPECT_EQ(Error::Read, res.error());
  18929. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18930. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18931. }
  18932. {
  18933. auto start = std::chrono::steady_clock::now();
  18934. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18935. EXPECT_EQ("abcd", string(data, data_length));
  18936. return true;
  18937. });
  18938. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18939. std::chrono::steady_clock::now() - start)
  18940. .count();
  18941. ASSERT_FALSE(res);
  18942. EXPECT_EQ(Error::Read, res.error());
  18943. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18944. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18945. }
  18946. }
  18947. TEST(MaxTimeoutTest, ContentStream) {
  18948. time_t timeout = 2000;
  18949. time_t threshold = 200;
  18950. Server svr;
  18951. Client cli("localhost", PORT);
  18952. max_timeout_test(svr, cli, timeout, threshold);
  18953. }
  18954. #ifdef CPPHTTPLIB_SSL_ENABLED
  18955. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18956. time_t timeout = 2000;
  18957. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18958. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18959. SSLClient cli("localhost", PORT);
  18960. cli.enable_server_certificate_verification(false);
  18961. max_timeout_test(svr, cli, timeout, threshold);
  18962. }
  18963. #endif
  18964. class EventDispatcher {
  18965. public:
  18966. EventDispatcher() {}
  18967. bool wait_event(DataSink *sink) {
  18968. unique_lock<mutex> lk(m_);
  18969. int id = id_;
  18970. // Wait with timeout to prevent hanging if client disconnects
  18971. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18972. [&] { return cid_ == id; })) {
  18973. return false; // Timeout occurred
  18974. }
  18975. sink->write(message_.data(), message_.size());
  18976. return true;
  18977. }
  18978. void send_event(const string &message) {
  18979. lock_guard<mutex> lk(m_);
  18980. cid_ = id_++;
  18981. message_ = message;
  18982. cv_.notify_all();
  18983. }
  18984. private:
  18985. mutex m_;
  18986. condition_variable cv_;
  18987. atomic_int id_{0};
  18988. atomic_int cid_{-1};
  18989. string message_;
  18990. };
  18991. TEST(ClientInThreadTest, Issue2068) {
  18992. EventDispatcher ed;
  18993. Server svr;
  18994. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18995. res.set_chunked_content_provider("text/event-stream",
  18996. [&](size_t /*offset*/, DataSink &sink) {
  18997. return ed.wait_event(&sink);
  18998. });
  18999. });
  19000. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19001. svr.wait_until_ready();
  19002. thread event_thread([&] {
  19003. int id = 0;
  19004. while (svr.is_running()) {
  19005. this_thread::sleep_for(chrono::milliseconds(500));
  19006. std::stringstream ss;
  19007. ss << "data: " << id << "\n\n";
  19008. ed.send_event(ss.str());
  19009. id++;
  19010. }
  19011. });
  19012. auto se = detail::scope_exit([&] {
  19013. svr.stop();
  19014. listen_thread.join();
  19015. event_thread.join();
  19016. ASSERT_FALSE(svr.is_running());
  19017. });
  19018. {
  19019. auto client = detail::make_unique<Client>(HOST, PORT);
  19020. client->set_read_timeout(std::chrono::minutes(10));
  19021. std::atomic<bool> stop{false};
  19022. std::thread t([&] {
  19023. client->Get("/event1",
  19024. [&](const char *, size_t) -> bool { return !stop; });
  19025. });
  19026. std::this_thread::sleep_for(std::chrono::seconds(2));
  19027. stop = true;
  19028. client->stop();
  19029. t.join();
  19030. // Reset client after thread has finished
  19031. client.reset();
  19032. }
  19033. }
  19034. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19035. auto handled = false;
  19036. Server svr;
  19037. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19038. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19039. auto se = detail::scope_exit([&] {
  19040. svr.stop();
  19041. t.join();
  19042. ASSERT_FALSE(svr.is_running());
  19043. ASSERT_FALSE(handled);
  19044. });
  19045. svr.wait_until_ready();
  19046. // Two Content-Length headers with different values — must be rejected
  19047. auto req = "POST /test HTTP/1.1\r\n"
  19048. "Content-Length: 5\r\n"
  19049. "Content-Length: 10\r\n"
  19050. "\r\n"
  19051. "hello";
  19052. std::string response;
  19053. ASSERT_TRUE(send_request(1, req, &response));
  19054. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19055. response.substr(0, response.find("\r\n")));
  19056. }
  19057. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19058. auto handled = false;
  19059. Server svr;
  19060. svr.Post("/test", [&](const Request &, Response &res) {
  19061. handled = true;
  19062. res.set_content("ok", "text/plain");
  19063. });
  19064. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19065. auto se = detail::scope_exit([&] {
  19066. svr.stop();
  19067. t.join();
  19068. ASSERT_FALSE(svr.is_running());
  19069. ASSERT_TRUE(handled);
  19070. });
  19071. svr.wait_until_ready();
  19072. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19073. auto req = "POST /test HTTP/1.1\r\n"
  19074. "Host: localhost\r\n"
  19075. "Content-Length: 5\r\n"
  19076. "Content-Length: 5\r\n"
  19077. "\r\n"
  19078. "hello";
  19079. std::string response;
  19080. ASSERT_TRUE(send_request(1, req, &response));
  19081. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19082. }
  19083. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19084. Server svr;
  19085. svr.Get("/test", [](const Request &, Response &res) {
  19086. res.set_content("ok", "text/plain");
  19087. });
  19088. auto port = svr.bind_to_any_port(HOST);
  19089. thread t = thread([&] { svr.listen_after_bind(); });
  19090. auto se = detail::scope_exit([&] {
  19091. svr.stop();
  19092. t.join();
  19093. ASSERT_FALSE(svr.is_running());
  19094. });
  19095. svr.wait_until_ready();
  19096. auto status_line = [&](const std::string &host_lines) {
  19097. std::string res;
  19098. send_request(
  19099. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19100. &res, port);
  19101. return res.substr(0, res.find("\r\n"));
  19102. };
  19103. const char *accepted[] = {
  19104. "Host: localhost\r\n",
  19105. "Host: a.example:8080\r\n",
  19106. "Host: my_service\r\n",
  19107. "Host: [::1]:8080\r\n",
  19108. "Host: [fe80::1%25eth0]\r\n",
  19109. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19110. };
  19111. for (auto host_lines : accepted) {
  19112. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19113. }
  19114. const char *rejected[] = {
  19115. "Host: a.example\r\nHost: b.example\r\n",
  19116. "Host: a.example\r\nHost: a.example\r\n",
  19117. "Host: a@b.example\r\n",
  19118. "Host: a.example/b\r\n",
  19119. "Host: a.example\\b\r\n",
  19120. "Host: a.example?b\r\n",
  19121. "Host: a.example#b\r\n",
  19122. "Host: a.example b.example\r\n",
  19123. };
  19124. for (auto host_lines : rejected) {
  19125. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19126. << host_lines;
  19127. }
  19128. }
  19129. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19130. Server svr;
  19131. svr.Get("/", [](const Request &req, Response &res) {
  19132. EXPECT_EQ(2U, req.trailers.size());
  19133. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19134. // Denied
  19135. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19136. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19137. // Accepted
  19138. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19139. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19140. EXPECT_TRUE(req.has_trailer("X-World"));
  19141. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19142. res.set_content("ok", "text/plain");
  19143. });
  19144. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19145. auto se = detail::scope_exit([&] {
  19146. svr.stop();
  19147. t.join();
  19148. ASSERT_FALSE(svr.is_running());
  19149. });
  19150. svr.wait_until_ready();
  19151. const std::string req = "GET / HTTP/1.1\r\n"
  19152. "Transfer-Encoding: chunked\r\n"
  19153. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19154. "\r\n"
  19155. "0\r\n"
  19156. "Content-Length: 10\r\n"
  19157. "Host: internal.local\r\n"
  19158. "Content-Type: malicious/content\r\n"
  19159. "Cookie: any\r\n"
  19160. "Set-Cookie: any\r\n"
  19161. "X-Forwarded-For: attacker.com\r\n"
  19162. "X-Real-Ip: 1.1.1.1\r\n"
  19163. "X-Hello: hello\r\n"
  19164. "X-World: world\r\n"
  19165. "\r\n";
  19166. std::string res;
  19167. ASSERT_TRUE(send_request(1, req, &res));
  19168. }
  19169. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19170. // several field lines, and the combined value is what has to be parsed. A
  19171. // Trailer field split across lines therefore declares every name it lists;
  19172. // reading only the first line silently drops the trailers the later lines
  19173. // declare. The prohibited-trailer filter still applies to every line.
  19174. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19175. Server svr;
  19176. size_t observed_trailer_count = 0;
  19177. std::string observed_hello;
  19178. std::string observed_world;
  19179. bool observed_content_length = true;
  19180. svr.Get("/", [&](const Request &req, Response &res) {
  19181. observed_trailer_count = req.trailers.size();
  19182. observed_hello = req.get_trailer_value("X-Hello");
  19183. observed_world = req.get_trailer_value("X-World");
  19184. observed_content_length = req.has_trailer("Content-Length");
  19185. res.set_content("ok", "text/plain");
  19186. });
  19187. auto port = svr.bind_to_any_port(HOST);
  19188. thread t = thread([&]() { svr.listen_after_bind(); });
  19189. auto se = detail::scope_exit([&] {
  19190. svr.stop();
  19191. t.join();
  19192. ASSERT_FALSE(svr.is_running());
  19193. });
  19194. svr.wait_until_ready();
  19195. const std::string req = "GET / HTTP/1.1\r\n"
  19196. "Host: localhost\r\n"
  19197. "Transfer-Encoding: chunked\r\n"
  19198. "Trailer: X-Hello\r\n"
  19199. "Trailer: X-World, Content-Length\r\n"
  19200. "\r\n"
  19201. "0\r\n"
  19202. "X-Hello: hello\r\n"
  19203. "X-World: world\r\n"
  19204. "Content-Length: 10\r\n"
  19205. "\r\n";
  19206. std::string res;
  19207. ASSERT_TRUE(send_request(1, req, &res, port));
  19208. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19209. // Accepted: both field lines contribute to the declared set
  19210. EXPECT_EQ(2U, observed_trailer_count);
  19211. EXPECT_EQ(observed_hello, "hello");
  19212. EXPECT_EQ(observed_world, "world");
  19213. // Denied: a prohibited name stays prohibited on a later field line
  19214. EXPECT_FALSE(observed_content_length);
  19215. }
  19216. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19217. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19218. // unbounded run of fields that are never declared, because the counter would
  19219. // only advance for declared fields.
  19220. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19221. Server svr;
  19222. bool handler_called = false;
  19223. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19224. handler_called = true;
  19225. res.set_content("ok", "text/plain");
  19226. });
  19227. auto port = svr.bind_to_any_port(HOST);
  19228. thread t = thread([&]() { svr.listen_after_bind(); });
  19229. auto se = detail::scope_exit([&] {
  19230. svr.stop();
  19231. t.join();
  19232. ASSERT_FALSE(svr.is_running());
  19233. });
  19234. svr.wait_until_ready();
  19235. // Declare nothing, then send far more undeclared trailer fields than the
  19236. // header-count limit. Parsing must stop and reject the request rather than
  19237. // read every line.
  19238. std::string req = "GET / HTTP/1.1\r\n"
  19239. "Transfer-Encoding: chunked\r\n"
  19240. "\r\n"
  19241. "0\r\n";
  19242. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19243. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19244. }
  19245. req += "\r\n";
  19246. std::string res;
  19247. ASSERT_TRUE(send_request(1, req, &res, port));
  19248. // The request is rejected before the handler runs.
  19249. EXPECT_FALSE(handler_called);
  19250. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19251. }
  19252. // The set of declared trailer names is capped so a peer cannot grow it without
  19253. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19254. // declared past the cap is not honored, even if the field is actually sent.
  19255. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19256. Server svr;
  19257. // One name inside the cap and one past it, so the test tracks the cap rather
  19258. // than a fixed count.
  19259. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19260. const std::string within_cap_name = "X-T-0";
  19261. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19262. bool observed_within_cap = false;
  19263. bool observed_past_cap = false;
  19264. svr.Get("/", [&](const Request &req, Response &res) {
  19265. observed_within_cap = req.has_trailer(within_cap_name);
  19266. observed_past_cap = req.has_trailer(past_cap_name);
  19267. res.set_content("ok", "text/plain");
  19268. });
  19269. auto port = svr.bind_to_any_port(HOST);
  19270. thread t = thread([&]() { svr.listen_after_bind(); });
  19271. auto se = detail::scope_exit([&] {
  19272. svr.stop();
  19273. t.join();
  19274. ASSERT_FALSE(svr.is_running());
  19275. });
  19276. svr.wait_until_ready();
  19277. // Declare more trailer names than the cap in a single Trailer field, then
  19278. // actually send the first (within the cap) and the last (past it).
  19279. std::string trailer_decl = "Trailer: ";
  19280. for (int i = 0; i < declared_count; i++) {
  19281. if (i != 0) { trailer_decl += ", "; }
  19282. trailer_decl += "X-T-" + std::to_string(i);
  19283. }
  19284. trailer_decl += "\r\n";
  19285. const std::string req = "GET / HTTP/1.1\r\n"
  19286. "Host: localhost\r\n"
  19287. "Transfer-Encoding: chunked\r\n" +
  19288. trailer_decl +
  19289. "\r\n"
  19290. "0\r\n" +
  19291. within_cap_name + ": a\r\n" + past_cap_name +
  19292. ": b\r\n"
  19293. "\r\n";
  19294. std::string res;
  19295. ASSERT_TRUE(send_request(1, req, &res, port));
  19296. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19297. // A name within the cap is honored; one declared past the cap is dropped.
  19298. EXPECT_TRUE(observed_within_cap);
  19299. EXPECT_FALSE(observed_past_cap);
  19300. }
  19301. // A direct client that is not listed in trusted_proxies must not be able to
  19302. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19303. // the peer address on the actual TCP connection determines whether the
  19304. // header is honored.
  19305. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19306. Server svr;
  19307. // Deliberately does NOT include the loopback address the test client
  19308. // actually connects from, so the direct connection is not a trusted proxy.
  19309. svr.set_trusted_proxies({"203.0.113.66"});
  19310. std::string observed_remote_addr;
  19311. svr.Get("/ip", [&](const Request &req, Response &res) {
  19312. observed_remote_addr = req.remote_addr;
  19313. res.set_content("ok", "text/plain");
  19314. });
  19315. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19316. auto se = detail::scope_exit([&] {
  19317. svr.stop();
  19318. t.join();
  19319. ASSERT_FALSE(svr.is_running());
  19320. });
  19321. svr.wait_until_ready();
  19322. Client cli(HOST, PORT);
  19323. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19325. EXPECT_EQ(StatusCode::OK_200, res->status);
  19326. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19327. // ignored entirely and the real connection-level address retained.
  19328. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19329. observed_remote_addr == "127.0.0.1");
  19330. }
  19331. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19332. Server svr;
  19333. std::string observed_remote_addr;
  19334. std::string observed_xff;
  19335. svr.Get("/ip", [&](const Request &req, Response &res) {
  19336. observed_remote_addr = req.remote_addr;
  19337. observed_xff = req.get_header_value("X-Forwarded-For");
  19338. res.set_content("ok", "text/plain");
  19339. });
  19340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19341. auto se = detail::scope_exit([&] {
  19342. svr.stop();
  19343. t.join();
  19344. ASSERT_FALSE(svr.is_running());
  19345. });
  19346. svr.wait_until_ready();
  19347. Client cli(HOST, PORT);
  19348. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19350. EXPECT_EQ(StatusCode::OK_200, res->status);
  19351. EXPECT_EQ(observed_xff, "203.0.113.66");
  19352. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19353. observed_remote_addr == "127.0.0.1");
  19354. }
  19355. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19356. Server svr;
  19357. svr.set_trusted_proxies({"203.0.113.66"});
  19358. std::string observed_remote_addr;
  19359. std::string observed_xff;
  19360. svr.Get("/ip", [&](const Request &req, Response &res) {
  19361. observed_remote_addr = req.remote_addr;
  19362. observed_xff = req.get_header_value("X-Forwarded-For");
  19363. res.set_content("ok", "text/plain");
  19364. });
  19365. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19366. auto se = detail::scope_exit([&] {
  19367. svr.stop();
  19368. t.join();
  19369. ASSERT_FALSE(svr.is_running());
  19370. });
  19371. svr.wait_until_ready();
  19372. Client cli(HOST, PORT);
  19373. auto res = cli.Get("/ip");
  19374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19375. EXPECT_EQ(StatusCode::OK_200, res->status);
  19376. EXPECT_EQ(observed_xff, "");
  19377. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19378. observed_remote_addr == "127.0.0.1");
  19379. }
  19380. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19381. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19382. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19383. Server svr;
  19384. svr.set_trusted_proxies({"127.0.0.1"});
  19385. svr.Get("/ip", [](const Request &req, Response &res) {
  19386. res.set_content(req.remote_addr, "text/plain");
  19387. });
  19388. auto port = svr.bind_to_any_port("::");
  19389. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19390. thread t = thread([&] { svr.listen_after_bind(); });
  19391. auto se = detail::scope_exit([&] {
  19392. svr.stop();
  19393. t.join();
  19394. ASSERT_FALSE(svr.is_running());
  19395. });
  19396. svr.wait_until_ready();
  19397. Client cli("127.0.0.1", port);
  19398. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19400. EXPECT_EQ("198.51.100.23", res->body);
  19401. }
  19402. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19403. Server svr;
  19404. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19405. svr.Get("/ip", [](const Request &req, Response &res) {
  19406. res.set_content(req.remote_addr, "text/plain");
  19407. });
  19408. auto port = svr.bind_to_any_port(HOST);
  19409. ASSERT_GT(port, 0);
  19410. thread t = thread([&] { svr.listen_after_bind(); });
  19411. auto se = detail::scope_exit([&] {
  19412. svr.stop();
  19413. t.join();
  19414. ASSERT_FALSE(svr.is_running());
  19415. });
  19416. svr.wait_until_ready();
  19417. Client cli(HOST, port);
  19418. auto res = cli.Get(
  19419. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19421. EXPECT_EQ("198.51.100.23", res->body);
  19422. }
  19423. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19424. Server svr;
  19425. // Include the loopback address the test client actually connects from, so
  19426. // the direct connection itself is recognized as the trusted proxy hop.
  19427. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19428. std::string observed_remote_addr;
  19429. std::string observed_xff;
  19430. svr.Get("/ip", [&](const Request &req, Response &res) {
  19431. observed_remote_addr = req.remote_addr;
  19432. observed_xff = req.get_header_value("X-Forwarded-For");
  19433. res.set_content("ok", "text/plain");
  19434. });
  19435. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19436. auto se = detail::scope_exit([&] {
  19437. svr.stop();
  19438. t.join();
  19439. ASSERT_FALSE(svr.is_running());
  19440. });
  19441. svr.wait_until_ready();
  19442. Client cli(HOST, PORT);
  19443. auto res = cli.Get(
  19444. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19446. EXPECT_EQ(StatusCode::OK_200, res->status);
  19447. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19448. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19449. }
  19450. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19451. Server svr;
  19452. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19453. std::string observed_remote_addr;
  19454. std::string observed_xff;
  19455. svr.Get("/ip", [&](const Request &req, Response &res) {
  19456. observed_remote_addr = req.remote_addr;
  19457. observed_xff = req.get_header_value("X-Forwarded-For");
  19458. res.set_content("ok", "text/plain");
  19459. });
  19460. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19461. auto se = detail::scope_exit([&] {
  19462. svr.stop();
  19463. t.join();
  19464. ASSERT_FALSE(svr.is_running());
  19465. });
  19466. svr.wait_until_ready();
  19467. Client cli(HOST, PORT);
  19468. auto res = cli.Get(
  19469. "/ip",
  19470. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19472. EXPECT_EQ(StatusCode::OK_200, res->status);
  19473. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19474. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19475. }
  19476. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19477. Server svr;
  19478. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19479. std::string observed_remote_addr;
  19480. std::string observed_xff;
  19481. svr.Get("/ip", [&](const Request &req, Response &res) {
  19482. observed_remote_addr = req.remote_addr;
  19483. observed_xff = req.get_header_value("X-Forwarded-For");
  19484. res.set_content("ok", "text/plain");
  19485. });
  19486. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19487. auto se = detail::scope_exit([&] {
  19488. svr.stop();
  19489. t.join();
  19490. ASSERT_FALSE(svr.is_running());
  19491. });
  19492. svr.wait_until_ready();
  19493. Client cli(HOST, PORT);
  19494. auto res = cli.Get(
  19495. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19497. EXPECT_EQ(StatusCode::OK_200, res->status);
  19498. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19499. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19500. // and must not be selected.
  19501. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19502. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19503. }
  19504. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19505. Server svr;
  19506. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19507. std::string observed_remote_addr;
  19508. svr.Get("/ip", [&](const Request &req, Response &res) {
  19509. observed_remote_addr = req.remote_addr;
  19510. res.set_content("ok", "text/plain");
  19511. });
  19512. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19513. auto se = detail::scope_exit([&] {
  19514. svr.stop();
  19515. t.join();
  19516. ASSERT_FALSE(svr.is_running());
  19517. });
  19518. svr.wait_until_ready();
  19519. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19520. // a forged address and the trusted proxy's own address; the forged value must
  19521. // not win over the address the trusted proxy actually recorded.
  19522. Client cli(HOST, PORT);
  19523. auto res = cli.Get(
  19524. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19526. EXPECT_EQ(StatusCode::OK_200, res->status);
  19527. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19528. }
  19529. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19530. Server svr;
  19531. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19532. std::string observed_remote_addr;
  19533. std::string observed_xff;
  19534. svr.Get("/ip", [&](const Request &req, Response &res) {
  19535. observed_remote_addr = req.remote_addr;
  19536. observed_xff = req.get_header_value("X-Forwarded-For");
  19537. res.set_content("ok", "text/plain");
  19538. });
  19539. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19540. auto se = detail::scope_exit([&] {
  19541. svr.stop();
  19542. t.join();
  19543. ASSERT_FALSE(svr.is_running());
  19544. });
  19545. svr.wait_until_ready();
  19546. Client cli(HOST, PORT);
  19547. auto res = cli.Get(
  19548. "/ip",
  19549. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19551. EXPECT_EQ(StatusCode::OK_200, res->status);
  19552. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19553. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19554. }
  19555. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19556. Server svr;
  19557. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19558. std::string observed_remote_addr;
  19559. std::string observed_xff;
  19560. svr.Get("/ip", [&](const Request &req, Response &res) {
  19561. observed_remote_addr = req.remote_addr;
  19562. observed_xff = req.get_header_value("X-Forwarded-For");
  19563. res.set_content("ok", "text/plain");
  19564. });
  19565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19566. auto se = detail::scope_exit([&] {
  19567. svr.stop();
  19568. t.join();
  19569. ASSERT_FALSE(svr.is_running());
  19570. });
  19571. svr.wait_until_ready();
  19572. std::string raw_req =
  19573. "GET /ip HTTP/1.1\r\n"
  19574. "Host: localhost\r\n"
  19575. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19576. "Connection: close\r\n"
  19577. "\r\n";
  19578. std::string out;
  19579. ASSERT_TRUE(send_request(5, raw_req, &out));
  19580. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19581. // Header parser trims surrounding whitespace of the header value
  19582. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19583. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19584. }
  19585. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19586. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19587. // their own X-Forwarded-For as a separate field line rather than extending the
  19588. // one the client sent, so every occurrence has to be taken into account.
  19589. // Reading only the first one hands back the address the client chose.
  19590. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19591. Server svr;
  19592. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19593. std::string observed_remote_addr;
  19594. size_t observed_xff_count = 0;
  19595. svr.Get("/ip", [&](const Request &req, Response &res) {
  19596. observed_remote_addr = req.remote_addr;
  19597. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19598. res.set_content("ok", "text/plain");
  19599. });
  19600. auto port = svr.bind_to_any_port(HOST);
  19601. thread t = thread([&]() { svr.listen_after_bind(); });
  19602. auto se = detail::scope_exit([&] {
  19603. svr.stop();
  19604. t.join();
  19605. ASSERT_FALSE(svr.is_running());
  19606. });
  19607. svr.wait_until_ready();
  19608. // The client supplies the first field line; the trusted proxy appends the
  19609. // address it observed as a second one.
  19610. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19611. "Host: localhost\r\n"
  19612. "X-Forwarded-For: 1.2.3.4\r\n"
  19613. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19614. "Connection: close\r\n"
  19615. "\r\n";
  19616. std::string out;
  19617. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19618. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19619. EXPECT_EQ(observed_xff_count, 2U);
  19620. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19621. // The same chain spread over one field line per hop derives the same client
  19622. // address, i.e. the split and the comma-joined representations agree.
  19623. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19624. "Host: localhost\r\n"
  19625. "X-Forwarded-For: 1.2.3.4\r\n"
  19626. "X-Forwarded-For: 198.51.100.23\r\n"
  19627. "X-Forwarded-For: 192.0.2.45\r\n"
  19628. "Connection: close\r\n"
  19629. "\r\n";
  19630. out.clear();
  19631. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19632. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19633. EXPECT_EQ(observed_xff_count, 3U);
  19634. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19635. }
  19636. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19637. // crash the server (it used to call front() on an empty vector inside
  19638. // get_client_ip). The connection-level remote address must be retained instead.
  19639. static void run_malformed_xff_test(const std::string &xff_value) {
  19640. Server svr;
  19641. svr.set_trusted_proxies({"192.0.2.45"});
  19642. std::string observed_remote_addr;
  19643. svr.Get("/ip", [&](const Request &req, Response &res) {
  19644. observed_remote_addr = req.remote_addr;
  19645. res.set_content("ok", "text/plain");
  19646. });
  19647. int port = 0;
  19648. thread t = thread([&]() {
  19649. port = svr.bind_to_any_port(HOST);
  19650. svr.listen_after_bind();
  19651. });
  19652. auto se = detail::scope_exit([&] {
  19653. svr.stop();
  19654. t.join();
  19655. ASSERT_FALSE(svr.is_running());
  19656. });
  19657. svr.wait_until_ready();
  19658. Client cli(HOST, port);
  19659. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19661. EXPECT_EQ(StatusCode::OK_200, res->status);
  19662. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19663. observed_remote_addr == "127.0.0.1");
  19664. }
  19665. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19666. run_malformed_xff_test("");
  19667. }
  19668. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19669. run_malformed_xff_test(",");
  19670. }
  19671. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19672. run_malformed_xff_test(", , ,");
  19673. }
  19674. // The same rule applies to Accept: a request whose acceptable types are spread
  19675. // over several field lines must be negotiated against all of them.
  19676. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19677. // case-insensitive connection options. Comparing the whole field value against
  19678. // one option misses a client that sends several of them, and misses every
  19679. // casing but the one written in the comparison.
  19680. //
  19681. // Sends req, reads the response, then reuses the same socket for a second
  19682. // request to find out whether the server kept the connection.
  19683. static void probe_connection_reuse(int port, const std::string &req,
  19684. bool *announced_close, bool *reusable) {
  19685. auto error = Error::Success;
  19686. auto sock = detail::create_client_socket(
  19687. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19688. /*connection_timeout_sec=*/5, 0,
  19689. /*read_timeout_sec=*/1, 0,
  19690. /*write_timeout_sec=*/5, 0, std::string(), error);
  19691. ASSERT_NE(sock, INVALID_SOCKET);
  19692. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19693. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19694. "Host: localhost\r\n"
  19695. "Connection: close\r\n"
  19696. "\r\n";
  19697. std::string first_response;
  19698. std::string second_response;
  19699. detail::process_client_socket(
  19700. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19701. [&](Stream &strm) {
  19702. if (strm.write(req.data(), req.size()) !=
  19703. static_cast<ssize_t>(req.size())) {
  19704. return false;
  19705. }
  19706. char buf[512];
  19707. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19708. // Headers plus the two-byte body of the handler below
  19709. while (reader.getline()) {
  19710. first_response += reader.ptr();
  19711. if (first_response.find("ok") != std::string::npos) { break; }
  19712. }
  19713. if (strm.write(second.data(), second.size()) !=
  19714. static_cast<ssize_t>(second.size())) {
  19715. return true;
  19716. }
  19717. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19718. while (reader2.getline()) {
  19719. second_response += reader2.ptr();
  19720. if (second_response.find("ok") != std::string::npos) { break; }
  19721. }
  19722. return true;
  19723. });
  19724. *announced_close =
  19725. first_response.find("Connection: close") != std::string::npos;
  19726. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19727. }
  19728. class ConnectionTokenTest : public ::testing::Test {
  19729. protected:
  19730. void SetUp() override {
  19731. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19732. res.set_content("ok", "text/plain");
  19733. });
  19734. port_ = svr_.bind_to_any_port(HOST);
  19735. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19736. svr_.wait_until_ready();
  19737. }
  19738. void TearDown() override {
  19739. svr_.stop();
  19740. if (thread_.joinable()) { thread_.join(); }
  19741. }
  19742. Server svr_;
  19743. int port_ = 0;
  19744. thread thread_;
  19745. };
  19746. // "close" alongside another option still closes the connection, and the
  19747. // response says so rather than leaving the peer to discover it.
  19748. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19749. bool announced_close = false;
  19750. bool reusable = true;
  19751. probe_connection_reuse(port_,
  19752. "GET /keepalive HTTP/1.1\r\n"
  19753. "Host: localhost\r\n"
  19754. "Connection: keep-alive, close\r\n"
  19755. "\r\n",
  19756. &announced_close, &reusable);
  19757. EXPECT_TRUE(announced_close);
  19758. EXPECT_FALSE(reusable);
  19759. }
  19760. // "close" split over two field lines is the same list, so it is honored too.
  19761. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19762. bool announced_close = false;
  19763. bool reusable = true;
  19764. probe_connection_reuse(port_,
  19765. "GET /keepalive HTTP/1.1\r\n"
  19766. "Host: localhost\r\n"
  19767. "Connection: keep-alive\r\n"
  19768. "Connection: close\r\n"
  19769. "\r\n",
  19770. &announced_close, &reusable);
  19771. EXPECT_TRUE(announced_close);
  19772. EXPECT_FALSE(reusable);
  19773. }
  19774. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19775. // keep-alive in the spelling everyone actually sends keeps its connection.
  19776. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19777. bool announced_close = false;
  19778. bool reusable = false;
  19779. probe_connection_reuse(port_,
  19780. "GET /keepalive HTTP/1.0\r\n"
  19781. "Host: localhost\r\n"
  19782. "Connection: keep-alive\r\n"
  19783. "\r\n",
  19784. &announced_close, &reusable);
  19785. EXPECT_FALSE(announced_close);
  19786. EXPECT_TRUE(reusable);
  19787. }
  19788. // A token the value merely contains is not the token itself.
  19789. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19790. bool announced_close = false;
  19791. bool reusable = false;
  19792. probe_connection_reuse(port_,
  19793. "GET /keepalive HTTP/1.1\r\n"
  19794. "Host: localhost\r\n"
  19795. "Connection: notclose\r\n"
  19796. "\r\n",
  19797. &announced_close, &reusable);
  19798. EXPECT_FALSE(announced_close);
  19799. EXPECT_TRUE(reusable);
  19800. }
  19801. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19802. Server svr;
  19803. std::vector<std::string> observed_types;
  19804. svr.Get("/", [&](const Request &req, Response &res) {
  19805. observed_types = req.accept_content_types;
  19806. res.set_content("ok", "text/plain");
  19807. });
  19808. auto port = svr.bind_to_any_port(HOST);
  19809. thread t = thread([&]() { svr.listen_after_bind(); });
  19810. auto se = detail::scope_exit([&] {
  19811. svr.stop();
  19812. t.join();
  19813. ASSERT_FALSE(svr.is_running());
  19814. });
  19815. svr.wait_until_ready();
  19816. Client cli(HOST, port);
  19817. Headers headers;
  19818. headers.emplace("Accept", "text/plain;q=0.5");
  19819. headers.emplace("Accept", "application/json");
  19820. auto res = cli.Get("/", headers);
  19821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19822. EXPECT_EQ(StatusCode::OK_200, res->status);
  19823. // Sorted by q-value, so the second field line's type comes first
  19824. ASSERT_EQ(2U, observed_types.size());
  19825. EXPECT_EQ("application/json", observed_types[0]);
  19826. EXPECT_EQ("text/plain", observed_types[1]);
  19827. }
  19828. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19829. // empty field line must not contribute a bare comma to the combined value.
  19830. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19831. Server svr;
  19832. std::vector<std::string> observed_types;
  19833. svr.Get("/", [&](const Request &req, Response &res) {
  19834. observed_types = req.accept_content_types;
  19835. res.set_content("ok", "text/plain");
  19836. });
  19837. auto port = svr.bind_to_any_port(HOST);
  19838. thread t = thread([&]() { svr.listen_after_bind(); });
  19839. auto se = detail::scope_exit([&] {
  19840. svr.stop();
  19841. t.join();
  19842. ASSERT_FALSE(svr.is_running());
  19843. });
  19844. svr.wait_until_ready();
  19845. // Empty first field line, then a real one
  19846. std::string raw_req = "GET / HTTP/1.1\r\n"
  19847. "Host: localhost\r\n"
  19848. "Accept:\r\n"
  19849. "Accept: application/json\r\n"
  19850. "Connection: close\r\n"
  19851. "\r\n";
  19852. std::string out;
  19853. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19854. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19855. ASSERT_EQ(1U, observed_types.size());
  19856. EXPECT_EQ("application/json", observed_types[0]);
  19857. }
  19858. // The skip in get_combined_header_value() is what keeps an empty field line
  19859. // from contributing a bare comma. Only a trailing empty field line exercises
  19860. // it: a leading one is already covered by the "combined is still empty" check,
  19861. // and parse_accept_header() now ignores the empty element either way, so the
  19862. // request-level test above can no longer tell the two apart.
  19863. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19864. Headers headers;
  19865. headers.emplace("Accept", "text/html");
  19866. headers.emplace("Accept", "");
  19867. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19868. headers.clear();
  19869. headers.emplace("Accept", "");
  19870. headers.emplace("Accept", "application/json");
  19871. EXPECT_EQ("application/json",
  19872. detail::get_combined_header_value(headers, "Accept"));
  19873. }
  19874. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19875. // An encoding offered on a later Accept-Encoding field line is still offered.
  19876. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19877. Server svr;
  19878. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19879. res.set_content(std::string(1024, 'x'), "text/plain");
  19880. });
  19881. auto port = svr.bind_to_any_port(HOST);
  19882. thread t = thread([&]() { svr.listen_after_bind(); });
  19883. auto se = detail::scope_exit([&] {
  19884. svr.stop();
  19885. t.join();
  19886. ASSERT_FALSE(svr.is_running());
  19887. });
  19888. svr.wait_until_ready();
  19889. Client cli(HOST, port);
  19890. cli.set_decompress(false);
  19891. Headers headers;
  19892. headers.emplace("Accept-Encoding", "identity");
  19893. headers.emplace("Accept-Encoding", "gzip");
  19894. auto res = cli.Get("/", headers);
  19895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19896. EXPECT_EQ(StatusCode::OK_200, res->status);
  19897. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19898. }
  19899. #endif
  19900. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19901. // Transfer-Encoding is not its body.
  19902. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19903. Server svr;
  19904. svr.set_payload_max_length(8);
  19905. svr.Post("/test", [](const Request &, Response &res) {
  19906. res.set_content("ok", "text/plain");
  19907. });
  19908. auto port = svr.bind_to_any_port(HOST);
  19909. ASSERT_GT(port, 0);
  19910. thread t = thread([&] { svr.listen_after_bind(); });
  19911. auto se = detail::scope_exit([&] {
  19912. svr.stop();
  19913. t.join();
  19914. ASSERT_FALSE(svr.is_running());
  19915. });
  19916. svr.wait_until_ready();
  19917. std::string resp;
  19918. ASSERT_TRUE(send_request(1,
  19919. "POST /test HTTP/1.1\r\n"
  19920. "Host: localhost\r\n"
  19921. "Connection: close\r\n"
  19922. "\r\n" +
  19923. std::string(16, 'X'),
  19924. &resp, port));
  19925. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19926. }
  19927. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19928. Server svr;
  19929. svr.Post("/post", [&](const Request &req, Response &res) {
  19930. res.set_content(req.body, "text/plain");
  19931. });
  19932. svr.Put("/put", [&](const Request &req, Response &res) {
  19933. res.set_content(req.body, "text/plain");
  19934. });
  19935. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19936. res.set_content(req.body, "text/plain");
  19937. });
  19938. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19939. res.set_content(req.body, "text/plain");
  19940. });
  19941. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19942. auto se = detail::scope_exit([&] {
  19943. svr.stop();
  19944. t.join();
  19945. ASSERT_FALSE(svr.is_running());
  19946. });
  19947. svr.wait_until_ready();
  19948. std::string resp;
  19949. // POST without Content-Length
  19950. ASSERT_TRUE(send_request(5,
  19951. "POST /post HTTP/1.1\r\n"
  19952. "Host: localhost\r\n"
  19953. "Connection: close\r\n"
  19954. "\r\n",
  19955. &resp));
  19956. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19957. // PUT without Content-Length
  19958. resp.clear();
  19959. ASSERT_TRUE(send_request(5,
  19960. "PUT /put HTTP/1.1\r\n"
  19961. "Host: localhost\r\n"
  19962. "Connection: close\r\n"
  19963. "\r\n",
  19964. &resp));
  19965. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19966. // PATCH without Content-Length
  19967. resp.clear();
  19968. ASSERT_TRUE(send_request(5,
  19969. "PATCH /patch HTTP/1.1\r\n"
  19970. "Host: localhost\r\n"
  19971. "Connection: close\r\n"
  19972. "\r\n",
  19973. &resp));
  19974. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19975. // DELETE without Content-Length
  19976. resp.clear();
  19977. ASSERT_TRUE(send_request(5,
  19978. "DELETE /delete HTTP/1.1\r\n"
  19979. "Host: localhost\r\n"
  19980. "Connection: close\r\n"
  19981. "\r\n",
  19982. &resp));
  19983. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19984. }
  19985. //==============================================================================
  19986. // open_stream() Tests
  19987. //==============================================================================
  19988. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19989. std::string result;
  19990. char buf[8192];
  19991. ssize_t n;
  19992. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19993. result.append(buf, static_cast<size_t>(n));
  19994. }
  19995. return result;
  19996. }
  19997. // Mock stream for unit tests
  19998. class MockStream : public Stream {
  19999. public:
  20000. std::string data;
  20001. size_t pos = 0;
  20002. ssize_t error_after = -1; // -1 = no error
  20003. explicit MockStream(const std::string &d, ssize_t err = -1)
  20004. : data(d), error_after(err) {}
  20005. bool is_readable() const override { return true; }
  20006. bool wait_readable() const override { return true; }
  20007. bool wait_writable() const override { return true; }
  20008. ssize_t read(char *ptr, size_t size) override {
  20009. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20010. if (pos >= data.size()) return 0;
  20011. size_t limit =
  20012. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20013. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20014. std::memcpy(ptr, data.data() + pos, to_read);
  20015. pos += to_read;
  20016. return static_cast<ssize_t>(to_read);
  20017. }
  20018. ssize_t write(const char *, size_t) override { return -1; }
  20019. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20020. ip = "127.0.0.1";
  20021. port = 0;
  20022. }
  20023. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20024. ip = "127.0.0.1";
  20025. port = 0;
  20026. }
  20027. socket_t socket() const override { return INVALID_SOCKET; }
  20028. time_t duration() const override { return 0; }
  20029. };
  20030. TEST(StreamHandleTest, Basic) {
  20031. ClientImpl::StreamHandle handle;
  20032. EXPECT_FALSE(handle.is_valid());
  20033. handle.response = detail::make_unique<Response>();
  20034. handle.error = Error::Connection;
  20035. EXPECT_FALSE(handle.is_valid());
  20036. handle.error = Error::Success;
  20037. EXPECT_TRUE(handle.is_valid());
  20038. }
  20039. TEST(BodyReaderTest, Basic) {
  20040. MockStream stream("Hello, World!");
  20041. detail::BodyReader reader;
  20042. reader.stream = &stream;
  20043. reader.content_length = 13;
  20044. char buf[32];
  20045. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20046. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20047. EXPECT_TRUE(reader.eof);
  20048. }
  20049. TEST(BodyReaderTest, NoStream) {
  20050. detail::BodyReader reader;
  20051. char buf[32];
  20052. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20053. EXPECT_EQ(Error::Connection, reader.last_error);
  20054. }
  20055. TEST(BodyReaderTest, Error) {
  20056. MockStream stream("Hello, World!", 5);
  20057. detail::BodyReader reader;
  20058. reader.stream = &stream;
  20059. reader.content_length = 13;
  20060. char buf[32];
  20061. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20062. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20063. EXPECT_EQ(Error::Read, reader.last_error);
  20064. }
  20065. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20066. // Mock-based StreamHandle tests relying on private internals are removed.
  20067. class OpenStreamTest : public ::testing::Test {
  20068. protected:
  20069. void SetUp() override {
  20070. svr_.Get("/hello", [](const Request &, Response &res) {
  20071. res.set_content("Hello World!", "text/plain");
  20072. });
  20073. svr_.Get("/large", [](const Request &, Response &res) {
  20074. res.set_content(std::string(10000, 'X'), "text/plain");
  20075. });
  20076. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20077. res.set_content("Hello World!", "image/jpeg");
  20078. res.set_header("Content-Encoding", "UTF-8");
  20079. });
  20080. svr_.Get("/chunked", [](const Request &, Response &res) {
  20081. res.set_chunked_content_provider("text/plain",
  20082. [](size_t offset, DataSink &sink) {
  20083. if (offset < 15) {
  20084. sink.write("chunk", 5);
  20085. return true;
  20086. }
  20087. sink.done();
  20088. return true;
  20089. });
  20090. });
  20091. svr_.Get("/compressible", [](const Request &, Response &res) {
  20092. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20093. DataSink &sink) {
  20094. if (offset < 100 * 1024) {
  20095. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20096. sink.write(chunk.data(), chunk.size());
  20097. return true;
  20098. }
  20099. sink.done();
  20100. return true;
  20101. });
  20102. });
  20103. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20104. [](const Request & /*req*/, Response &res) {
  20105. auto i = new int(0);
  20106. res.set_header("Trailer", "Content-Length, X-Allowed");
  20107. res.set_chunked_content_provider(
  20108. "text/plain",
  20109. [i](size_t /*offset*/, DataSink &sink) {
  20110. switch (*i) {
  20111. case 0: sink.os << "123"; break;
  20112. case 1: sink.os << "456"; break;
  20113. case 2: sink.os << "789"; break;
  20114. case 3: {
  20115. sink.done_with_trailer(
  20116. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20117. } break;
  20118. }
  20119. (*i)++;
  20120. return true;
  20121. },
  20122. [i](bool success) {
  20123. EXPECT_TRUE(success);
  20124. delete i;
  20125. });
  20126. });
  20127. // Echo headers endpoint for header-related tests
  20128. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20129. std::string body;
  20130. for (const auto &h : req.headers) {
  20131. body.append(h.first);
  20132. body.push_back(':');
  20133. body.append(h.second);
  20134. body.push_back('\n');
  20135. }
  20136. res.set_content(body, "text/plain");
  20137. });
  20138. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20139. std::string body;
  20140. for (const auto &h : req.headers) {
  20141. body.append(h.first);
  20142. body.push_back(':');
  20143. body.append(h.second);
  20144. body.push_back('\n');
  20145. }
  20146. res.set_content(body, "text/plain");
  20147. });
  20148. port_ = svr_.bind_to_any_port("127.0.0.1");
  20149. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20150. svr_.wait_until_ready();
  20151. }
  20152. void TearDown() override {
  20153. svr_.stop();
  20154. if (thread_.joinable()) thread_.join();
  20155. }
  20156. Server svr_;
  20157. std::thread thread_;
  20158. int port_ = 0;
  20159. };
  20160. TEST_F(OpenStreamTest, Basic) {
  20161. Client cli("127.0.0.1", port_);
  20162. auto handle = cli.open_stream("GET", "/hello");
  20163. EXPECT_TRUE(handle.is_valid());
  20164. EXPECT_EQ("Hello World!", read_all(handle));
  20165. }
  20166. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20167. Client cli("127.0.0.1", port_);
  20168. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20169. ASSERT_TRUE(handle.is_valid());
  20170. EXPECT_EQ("Hello World!", read_all(handle));
  20171. }
  20172. TEST_F(OpenStreamTest, SmallBuffer) {
  20173. Client cli("127.0.0.1", port_);
  20174. auto handle = cli.open_stream("GET", "/hello");
  20175. std::string result;
  20176. char buf[4];
  20177. ssize_t n;
  20178. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20179. result.append(buf, static_cast<size_t>(n));
  20180. EXPECT_EQ("Hello World!", result);
  20181. }
  20182. TEST_F(OpenStreamTest, DefaultHeaders) {
  20183. Client cli("127.0.0.1", port_);
  20184. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20185. {
  20186. auto handle = cli.open_stream("GET", "/echo-headers");
  20187. ASSERT_TRUE(handle.is_valid());
  20188. auto body = read_all(handle);
  20189. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20190. std::string::npos);
  20191. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20192. std::string::npos);
  20193. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20194. }
  20195. // open_stream POST with body and no explicit content_type should NOT add
  20196. // text/plain Content-Type (behavior differs from non-streaming path), but
  20197. // should include Content-Length
  20198. {
  20199. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20200. ASSERT_TRUE(handle.is_valid());
  20201. auto body = read_all(handle);
  20202. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20203. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20204. }
  20205. // open_stream POST with explicit Content-Type should preserve it
  20206. {
  20207. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20208. {{"Content-Type", "application/custom"}},
  20209. "{}", "application/custom");
  20210. ASSERT_TRUE(handle.is_valid());
  20211. auto body = read_all(handle);
  20212. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20213. }
  20214. // User-specified User-Agent must not be overwritten for stream API
  20215. {
  20216. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20217. {{"User-Agent", "MyAgent/1.2"}});
  20218. ASSERT_TRUE(handle.is_valid());
  20219. auto body = read_all(handle);
  20220. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20221. }
  20222. }
  20223. TEST_F(OpenStreamTest, Large) {
  20224. Client cli("127.0.0.1", port_);
  20225. auto handle = cli.open_stream("GET", "/large");
  20226. EXPECT_EQ(10000u, read_all(handle).size());
  20227. }
  20228. TEST_F(OpenStreamTest, ConnectionError) {
  20229. Client cli("127.0.0.1", 9999);
  20230. auto handle = cli.open_stream("GET", "/hello");
  20231. EXPECT_FALSE(handle.is_valid());
  20232. }
  20233. TEST_F(OpenStreamTest, Chunked) {
  20234. Client cli("127.0.0.1", port_);
  20235. auto handle = cli.open_stream("GET", "/chunked");
  20236. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20237. "Transfer-Encoding") == "chunked");
  20238. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20239. }
  20240. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20241. Client cli("127.0.0.1", port_);
  20242. auto handle =
  20243. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20244. ASSERT_TRUE(handle.is_valid());
  20245. // Consume body to allow trailers to be received/parsed
  20246. auto body = read_all(handle);
  20247. // Explicitly parse trailers (ensure trailers are available for assertion)
  20248. handle.parse_trailers_if_needed();
  20249. EXPECT_EQ(std::string("123456789"), body);
  20250. // The response should include a Trailer header declaring both names
  20251. ASSERT_TRUE(handle.response);
  20252. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20253. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20254. handle.response->get_header_value("Trailer"));
  20255. // Prohibited trailer must not be present
  20256. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20257. // Allowed trailer should be present
  20258. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20259. EXPECT_EQ(std::string("yes"),
  20260. handle.response->get_trailer_value("X-Allowed"));
  20261. // Verify trailers are NOT present as regular headers
  20262. EXPECT_EQ(std::string(""),
  20263. handle.response->get_header_value("Content-Length"));
  20264. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20265. }
  20266. // Accepts one connection on an OS-assigned port, which it hands over through
  20267. // port_promise, reads the request head and sends back response. after_send,
  20268. // if given, runs on the connection before it is closed.
  20269. static std::thread
  20270. serve_single_response(std::promise<int> &port_promise,
  20271. const std::string &response,
  20272. std::function<void(socket_t)> after_send = nullptr) {
  20273. return std::thread([&port_promise, response, after_send] {
  20274. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20275. default_socket_options(srv);
  20276. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20277. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20278. sockaddr_in addr{};
  20279. addr.sin_family = AF_INET;
  20280. addr.sin_port = htons(0); // Let OS assign a free port
  20281. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20282. int opt = 1;
  20283. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20284. #ifdef _WIN32
  20285. reinterpret_cast<const char *>(&opt),
  20286. #else
  20287. &opt,
  20288. #endif
  20289. sizeof(opt));
  20290. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20291. ::listen(srv, 1) != 0) {
  20292. port_promise.set_value(-1);
  20293. detail::close_socket(srv);
  20294. return;
  20295. }
  20296. socklen_t addr_len = sizeof(addr);
  20297. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20298. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20299. sockaddr_in cli_addr{};
  20300. socklen_t cli_len = sizeof(cli_addr);
  20301. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20302. if (cli != INVALID_SOCKET) {
  20303. // Read the complete HTTP request (until the blank line that terminates
  20304. // headers) before sending the response. If the server closes the socket
  20305. // while the client's request data is still unread in the kernel receive
  20306. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20307. // connection on both sides: it discards the client's receive buffer
  20308. // (which already holds our response) and causes any in-progress write on
  20309. // the client to fail with ECONNRESET. Reading all request data first
  20310. // ensures close() emits a graceful FIN.
  20311. {
  20312. char rbuf[256];
  20313. std::string req;
  20314. while (req.find("\r\n\r\n") == std::string::npos) {
  20315. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20316. if (n <= 0) { break; }
  20317. req.append(rbuf, static_cast<size_t>(n));
  20318. }
  20319. }
  20320. ::send(cli,
  20321. #ifdef _WIN32
  20322. static_cast<const char *>(response.c_str()),
  20323. static_cast<int>(response.size()),
  20324. #else
  20325. response.c_str(), response.size(),
  20326. #endif
  20327. 0);
  20328. if (after_send) { after_send(cli); }
  20329. detail::close_socket(cli);
  20330. }
  20331. detail::close_socket(srv);
  20332. });
  20333. }
  20334. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20335. #ifndef _WIN32
  20336. signal(SIGPIPE, SIG_IGN);
  20337. #endif
  20338. std::promise<int> port_promise;
  20339. auto port_future = port_promise.get_future();
  20340. auto server_thread =
  20341. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20342. "Content-Type: text/plain\r\n"
  20343. "Content-Length: not-a-number\r\n"
  20344. "Connection: close\r\n"
  20345. "\r\n"
  20346. "hello");
  20347. auto port = port_future.get();
  20348. ASSERT_GT(port, 0);
  20349. Client cli("127.0.0.1", port);
  20350. auto handle = cli.open_stream("GET", "/");
  20351. EXPECT_FALSE(handle.is_valid());
  20352. server_thread.join();
  20353. }
  20354. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20355. #ifndef _WIN32
  20356. signal(SIGPIPE, SIG_IGN);
  20357. #endif
  20358. std::promise<int> port_promise;
  20359. auto port_future = port_promise.get_future();
  20360. auto server_thread = serve_single_response(
  20361. port_promise, "HTTP/1.1 200 OK\r\n"
  20362. "Content-Type: text/plain\r\n"
  20363. "Content-Length: 99999999999999999999999999\r\n"
  20364. "Connection: close\r\n"
  20365. "\r\n"
  20366. "hello");
  20367. auto port = port_future.get();
  20368. ASSERT_GT(port, 0);
  20369. // Historically std::stoull would throw std::out_of_range here and crash
  20370. // the process, then parsing silently clamped to a bogus framing length and
  20371. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20372. // so the stream fails to open, matching the not-a-number case above. The
  20373. // process still must NOT terminate.
  20374. Client cli("127.0.0.1", port);
  20375. auto handle = cli.open_stream("GET", "/");
  20376. EXPECT_FALSE(handle.is_valid());
  20377. server_thread.join();
  20378. }
  20379. #ifndef _WIN32
  20380. // As above for the body of a streamed request: a send() cut short by the write
  20381. // timeout must not leave the rest of the body unsent.
  20382. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20383. signal(SIGPIPE, SIG_IGN);
  20384. Server svr;
  20385. svr.set_socket_options([](socket_t sock) {
  20386. int size = 8192;
  20387. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20388. reinterpret_cast<const char *>(&size), sizeof(size));
  20389. });
  20390. svr.Post("/size", [](const Request &, Response &res,
  20391. const ContentReader &content_reader) {
  20392. // Outlast the client's write timeout before reading the body.
  20393. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20394. size_t received = 0;
  20395. content_reader([&](const char *, size_t len) {
  20396. received += len;
  20397. return true;
  20398. });
  20399. res.set_content(std::to_string(received), "text/plain");
  20400. });
  20401. auto port = svr.bind_to_any_port(HOST);
  20402. std::thread t([&]() { svr.listen_after_bind(); });
  20403. auto se = detail::scope_exit([&] {
  20404. svr.stop();
  20405. t.join();
  20406. });
  20407. svr.wait_until_ready();
  20408. Client cli(HOST, port);
  20409. cli.set_write_timeout(0, 500000);
  20410. cli.set_socket_options([](socket_t sock) {
  20411. int size = 8192;
  20412. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20413. reinterpret_cast<const char *>(&size), sizeof(size));
  20414. });
  20415. const std::string body(4 * 1024 * 1024, 'A');
  20416. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20417. "application/octet-stream");
  20418. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20419. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20420. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20421. }
  20422. #endif
  20423. // Serves `response` to the single request `fn` makes with a fresh client.
  20424. template <typename Fn>
  20425. static void with_single_response(const std::string &response, Fn fn) {
  20426. #ifndef _WIN32
  20427. signal(SIGPIPE, SIG_IGN);
  20428. #endif
  20429. std::promise<int> port_promise;
  20430. auto port_future = port_promise.get_future();
  20431. auto server_thread = serve_single_response(port_promise, response);
  20432. auto se = detail::scope_exit([&] { server_thread.join(); });
  20433. auto port = port_future.get();
  20434. ASSERT_GT(port, 0);
  20435. Client cli("127.0.0.1", port);
  20436. fn(cli);
  20437. }
  20438. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20439. // too, also in a build without the decoder for the advertised coding.
  20440. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20441. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20442. const auto response = "HTTP/1.1 200 OK\r\n"
  20443. "Content-Encoding: gzip\r\n"
  20444. "Content-Length: " +
  20445. std::to_string(gzipped.size()) +
  20446. "\r\n"
  20447. "Connection: close\r\n\r\n" +
  20448. gzipped;
  20449. with_single_response(response, [&](Client &cli) {
  20450. cli.set_decompress(false);
  20451. auto handle = cli.open_stream("GET", "/");
  20452. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20453. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20454. EXPECT_EQ(gzipped, read_all(handle));
  20455. EXPECT_FALSE(handle.has_read_error());
  20456. });
  20457. with_single_response(response, [&](Client &cli) {
  20458. cli.set_decompress(false);
  20459. auto res = stream::Get(cli, "/", 7);
  20460. ASSERT_TRUE(res) << to_string(res.error());
  20461. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20462. EXPECT_EQ(gzipped, res.read_all());
  20463. EXPECT_FALSE(res.has_read_error());
  20464. });
  20465. }
  20466. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20467. // Neither Content-Length nor chunked: the body ends at the close
  20468. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20469. "Connection: close\r\n"
  20470. "\r\n"
  20471. "hello";
  20472. with_single_response(close_delimited, [](Client &cli) {
  20473. auto handle = cli.open_stream("GET", "/");
  20474. ASSERT_TRUE(handle.is_valid());
  20475. EXPECT_EQ("hello", read_all(handle));
  20476. EXPECT_FALSE(handle.has_read_error());
  20477. });
  20478. // A close before the end of the Content-Length is still an error
  20479. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20480. "Content-Length: 10\r\n"
  20481. "\r\n"
  20482. "hello";
  20483. with_single_response(short_content_length, [](Client &cli) {
  20484. auto handle = cli.open_stream("GET", "/");
  20485. ASSERT_TRUE(handle.is_valid());
  20486. read_all(handle);
  20487. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20488. });
  20489. // So is a close before the last chunk
  20490. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20491. "Transfer-Encoding: chunked\r\n"
  20492. "\r\n"
  20493. "5\r\nhello\r\n";
  20494. with_single_response(short_chunked, [](Client &cli) {
  20495. auto handle = cli.open_stream("GET", "/");
  20496. ASSERT_TRUE(handle.is_valid());
  20497. read_all(handle);
  20498. EXPECT_TRUE(handle.has_read_error());
  20499. });
  20500. }
  20501. #ifdef CPPHTTPLIB_SSL_ENABLED
  20502. // Serves `response` to one request, then closes with or without a close_notify
  20503. template <typename Fn>
  20504. static void with_single_tls_response(const std::string &response,
  20505. bool close_notify, Fn fn) {
  20506. #ifndef _WIN32
  20507. signal(SIGPIPE, SIG_IGN);
  20508. #endif
  20509. std::promise<int> port_promise;
  20510. auto port_future = port_promise.get_future();
  20511. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20512. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20513. default_socket_options(srv);
  20514. sockaddr_in addr{};
  20515. addr.sin_family = AF_INET;
  20516. addr.sin_port = htons(0);
  20517. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20518. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20519. ::listen(srv, 1) != 0) {
  20520. port_promise.set_value(-1);
  20521. detail::close_socket(srv);
  20522. return;
  20523. }
  20524. socklen_t addr_len = sizeof(addr);
  20525. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20526. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20527. auto cli = ::accept(srv, nullptr, nullptr);
  20528. if (cli != INVALID_SOCKET) {
  20529. auto ctx = tls::create_server_context();
  20530. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20531. nullptr);
  20532. auto session = tls::create_session(ctx, cli);
  20533. tls::TlsError err;
  20534. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20535. // The request head first, so that closing the socket sends a FIN
  20536. // rather than an RST for the unread bytes.
  20537. std::string req;
  20538. char buf[256];
  20539. while (req.find("\r\n\r\n") == std::string::npos) {
  20540. auto n = tls::read(session, buf, sizeof(buf), err);
  20541. if (n <= 0) { break; }
  20542. req.append(buf, static_cast<size_t>(n));
  20543. }
  20544. size_t sent = 0;
  20545. while (sent < response.size()) {
  20546. auto n = tls::write(session, response.data() + sent,
  20547. response.size() - sent, err);
  20548. if (n <= 0) { break; }
  20549. sent += static_cast<size_t>(n);
  20550. }
  20551. if (close_notify) { tls::shutdown(session, true); }
  20552. }
  20553. tls::free_session(session);
  20554. detail::close_socket(cli);
  20555. tls::free_context(ctx);
  20556. }
  20557. detail::close_socket(srv);
  20558. });
  20559. auto se = detail::scope_exit([&] { server_thread.join(); });
  20560. auto port = port_future.get();
  20561. ASSERT_GT(port, 0);
  20562. SSLClient cli("127.0.0.1", port);
  20563. cli.enable_server_certificate_verification(false);
  20564. fn(cli);
  20565. }
  20566. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20567. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20568. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20569. "Connection: close\r\n"
  20570. "\r\n"
  20571. "hello";
  20572. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20573. auto res = cli.Get("/");
  20574. ASSERT_TRUE(res) << to_string(res.error());
  20575. EXPECT_EQ("hello", res->body);
  20576. });
  20577. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20578. auto res = cli.Get("/");
  20579. ASSERT_FALSE(res);
  20580. EXPECT_EQ(Error::Read, res.error());
  20581. });
  20582. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20583. auto handle = cli.open_stream("GET", "/");
  20584. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20585. read_all(handle);
  20586. EXPECT_TRUE(handle.has_read_error());
  20587. });
  20588. // A framed body ends where its framing says, with or without the alert
  20589. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20590. "Content-Length: 5\r\n"
  20591. "Connection: close\r\n"
  20592. "\r\n"
  20593. "hello";
  20594. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20595. auto res = cli.Get("/");
  20596. ASSERT_TRUE(res) << to_string(res.error());
  20597. EXPECT_EQ("hello", res->body);
  20598. });
  20599. }
  20600. #endif
  20601. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20602. const char *responses[] = {
  20603. "HTTP/1.1 103 Early Hints\r\n"
  20604. "Link: </style.css>; rel=preload\r\n"
  20605. "\r\n"
  20606. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20607. "HTTP/1.1 100 Continue\r\n"
  20608. "X-Note: interim\r\n"
  20609. "\r\n"
  20610. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20611. };
  20612. for (auto response : responses) {
  20613. with_single_response(response, [](Client &cli) {
  20614. auto res = cli.Get("/");
  20615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20616. EXPECT_EQ(StatusCode::OK_200, res->status);
  20617. EXPECT_EQ("ok", res->body);
  20618. });
  20619. }
  20620. }
  20621. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20622. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20623. const std::string final_response =
  20624. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20625. std::string interims;
  20626. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20627. interims += interim;
  20628. }
  20629. with_single_response(interims + final_response, [](Client &cli) {
  20630. auto res = cli.Get("/");
  20631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20632. EXPECT_EQ("ok", res->body);
  20633. });
  20634. with_single_response(interims + interim + final_response, [](Client &cli) {
  20635. auto res = cli.Get("/");
  20636. ASSERT_FALSE(res);
  20637. EXPECT_EQ(Error::Read, res.error());
  20638. });
  20639. }
  20640. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20641. #ifndef _WIN32
  20642. signal(SIGPIPE, SIG_IGN);
  20643. #endif
  20644. // The server answers the head without asking for the body. Bytes it then
  20645. // reads on the connection would be taken for the body the request declared.
  20646. auto closed_by_client = false;
  20647. std::promise<int> port_promise;
  20648. auto server_thread = serve_single_response(
  20649. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20650. [&](socket_t sock) {
  20651. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20652. char buf[256];
  20653. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20654. });
  20655. Client cli("127.0.0.1", port_promise.get_future().get());
  20656. cli.set_keep_alive(true);
  20657. cli.set_read_timeout(1, 0);
  20658. // Long enough for the client to send Expect: 100-continue.
  20659. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20661. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20662. cli.Get("/second");
  20663. server_thread.join();
  20664. EXPECT_TRUE(closed_by_client);
  20665. }
  20666. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20667. // Long enough for the client to send Expect: 100-continue
  20668. with_single_response(
  20669. "HTTP/1.1 103 Early Hints\r\n"
  20670. "Link: </style.css>; rel=preload\r\n"
  20671. "\r\n"
  20672. "HTTP/1.1 401 Unauthorized\r\n"
  20673. "Content-Length: 0\r\n\r\n",
  20674. [](Client &cli) {
  20675. cli.set_read_timeout(2, 0);
  20676. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20678. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20679. });
  20680. }
  20681. #ifdef CPPHTTPLIB_SSL_ENABLED
  20682. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20683. #ifndef _WIN32
  20684. signal(SIGPIPE, SIG_IGN);
  20685. #endif
  20686. auto reused = false;
  20687. std::promise<int> port_promise;
  20688. auto server_thread = serve_single_response(
  20689. port_promise,
  20690. "HTTP/1.1 401 Unauthorized\r\n"
  20691. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20692. "Content-Length: 0\r\n\r\n",
  20693. [&](socket_t sock) {
  20694. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20695. char buf[256];
  20696. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20697. });
  20698. Client cli("127.0.0.1", port_promise.get_future().get());
  20699. cli.set_keep_alive(true);
  20700. cli.set_digest_auth("user", "pass");
  20701. cli.set_read_timeout(1, 0);
  20702. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20703. server_thread.join();
  20704. EXPECT_FALSE(reused);
  20705. }
  20706. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20707. // Any other answer to CONNECT would read as the origin's response.
  20708. struct {
  20709. const char *response;
  20710. bool passed_on;
  20711. } cases[] = {
  20712. {"HTTP/1.1 201 Created\r\n"
  20713. "Set-Cookie: session=from-proxy\r\n"
  20714. "Content-Length: 0\r\n\r\n",
  20715. false},
  20716. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20717. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20718. "Content-Length: 0\r\n\r\n",
  20719. true},
  20720. };
  20721. for (const auto &c : cases) {
  20722. std::promise<int> port_promise;
  20723. auto server_thread = serve_single_response(port_promise, c.response);
  20724. SSLClient cli("example.com", 443);
  20725. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20726. auto res = cli.Get("/");
  20727. server_thread.join();
  20728. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20729. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20730. if (res) {
  20731. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20732. }
  20733. }
  20734. }
  20735. #endif
  20736. // Records the client's error logger calls as "error METHOD path", or
  20737. // "error null" for a call without a request
  20738. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20739. return [&log](const Error &err, const Request *req) {
  20740. log.push_back(to_string(err) + " " +
  20741. (req ? req->method + " " + req->path : "null"));
  20742. };
  20743. }
  20744. // A failed request is reported once, with the request the caller made
  20745. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20746. Server svr;
  20747. svr.Get("/big", [](const Request &, Response &res) {
  20748. res.set_content(std::string(100000, 'b'), "text/plain");
  20749. });
  20750. auto port = svr.bind_to_any_port(HOST);
  20751. std::thread t([&]() { svr.listen_after_bind(); });
  20752. auto se = detail::scope_exit([&] {
  20753. svr.stop();
  20754. t.join();
  20755. });
  20756. svr.wait_until_ready();
  20757. Client cli(HOST, port);
  20758. std::vector<std::string> log;
  20759. cli.set_error_logger(record_errors(log));
  20760. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20761. cli.Get("/big", [](const char *, size_t) { return false; });
  20762. EXPECT_EQ(expected, log);
  20763. log.clear();
  20764. cli.Get("/big", [](size_t, size_t) { return false; });
  20765. EXPECT_EQ(expected, log);
  20766. }
  20767. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20768. // Fails while the body is read
  20769. auto broken = [](const Request &, Response &res) {
  20770. res.set_content_provider(10, "text/plain",
  20771. [](size_t, size_t, DataSink &) { return false; });
  20772. };
  20773. Server other;
  20774. other.Get("/broken", broken);
  20775. auto other_port = other.bind_to_any_port(HOST);
  20776. std::thread other_t([&]() { other.listen_after_bind(); });
  20777. auto other_se = detail::scope_exit([&] {
  20778. other.stop();
  20779. other_t.join();
  20780. });
  20781. other.wait_until_ready();
  20782. Server svr;
  20783. svr.Get("/broken", broken);
  20784. svr.Get("/same-origin",
  20785. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20786. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20787. res.set_redirect("http://" + std::string(HOST) + ":" +
  20788. std::to_string(other_port) + "/broken");
  20789. });
  20790. auto port = svr.bind_to_any_port(HOST);
  20791. std::thread t([&]() { svr.listen_after_bind(); });
  20792. auto se = detail::scope_exit([&] {
  20793. svr.stop();
  20794. t.join();
  20795. });
  20796. svr.wait_until_ready();
  20797. Client cli(HOST, port);
  20798. cli.set_follow_location(true);
  20799. std::vector<std::string> log;
  20800. cli.set_error_logger(record_errors(log));
  20801. for (auto path : {"/same-origin", "/cross-origin"}) {
  20802. log.clear();
  20803. auto res = cli.Get(path);
  20804. ASSERT_FALSE(res);
  20805. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20806. log);
  20807. }
  20808. }
  20809. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20810. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20811. std::vector<std::string> log;
  20812. cli.set_error_logger(record_errors(log));
  20813. auto handle = cli.open_stream("GET", "/x");
  20814. EXPECT_FALSE(handle.is_valid());
  20815. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20816. log);
  20817. });
  20818. }
  20819. #ifdef CPPHTTPLIB_SSL_ENABLED
  20820. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20821. // Not a TLS server, so the handshake fails. It waits for a request line in
  20822. // the handshake bytes, so a short read timeout lets it close quickly.
  20823. Server svr;
  20824. svr.set_read_timeout(0, 100000);
  20825. svr.Get("/x", [](const Request &, Response &res) {
  20826. res.set_content("x", "text/plain");
  20827. });
  20828. auto port = svr.bind_to_any_port(HOST);
  20829. std::thread t([&]() { svr.listen_after_bind(); });
  20830. auto se = detail::scope_exit([&] {
  20831. svr.stop();
  20832. t.join();
  20833. });
  20834. svr.wait_until_ready();
  20835. std::vector<std::string> log;
  20836. SSLClient cli(HOST, port);
  20837. cli.enable_server_certificate_verification(false);
  20838. cli.set_error_logger(record_errors(log));
  20839. auto res = cli.Get("/x");
  20840. ASSERT_FALSE(res);
  20841. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20842. log.clear();
  20843. auto handle = cli.open_stream("GET", "/x");
  20844. EXPECT_FALSE(handle.is_valid());
  20845. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20846. log.clear();
  20847. SSLClient no_ca(HOST, port);
  20848. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20849. no_ca.set_error_logger(record_errors(log));
  20850. res = no_ca.Get("/x");
  20851. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20852. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20853. }
  20854. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20855. #ifndef _WIN32
  20856. signal(SIGPIPE, SIG_IGN);
  20857. #endif
  20858. // Refused, answered with a challenge, or closed without an answer
  20859. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20860. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20861. "Content-Length: 0\r\n\r\n",
  20862. ""}) {
  20863. std::promise<int> port_promise;
  20864. auto server_thread = serve_single_response(port_promise, response);
  20865. SSLClient cli("example.com", 443);
  20866. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20867. std::vector<std::string> log;
  20868. cli.set_error_logger(record_errors(log));
  20869. auto res = cli.Get("/");
  20870. server_thread.join();
  20871. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20872. << response;
  20873. }
  20874. }
  20875. #endif
  20876. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20877. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20878. // the chunked coding and drop Content-Length, so a front-end that trusts
  20879. // Content-Length would disagree about where the body ends (response
  20880. // smuggling). The client must reject such a response.
  20881. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20882. for (const char *te : {"chunked", "gzip, chunked"}) {
  20883. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20884. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20885. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20886. "5\r\nhello\r\n0\r\n\r\n";
  20887. with_single_response(response, [&](Client &cli) {
  20888. auto res = cli.Get("/");
  20889. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20890. EXPECT_EQ(Error::Read, res.error()) << te;
  20891. });
  20892. with_single_response(response, [&](Client &cli) {
  20893. auto handle = cli.open_stream("GET", "/");
  20894. EXPECT_FALSE(handle.is_valid()) << te;
  20895. EXPECT_EQ(Error::Read, handle.error) << te;
  20896. });
  20897. }
  20898. }
  20899. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20900. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20901. // closing the connection (unlike a request, which must be rejected).
  20902. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20903. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20904. "Transfer-Encoding: chunked\r\n"
  20905. "Connection: close\r\n"
  20906. "\r\n"
  20907. "5\r\nhello\r\n0\r\n\r\n",
  20908. "HTTP/1.1 200 OK\r\n"
  20909. "Transfer-Encoding: gzip\r\n"
  20910. "Connection: close\r\n"
  20911. "\r\n"
  20912. "hello"}) {
  20913. with_single_response(response, [&](Client &cli) {
  20914. auto res = cli.Get("/");
  20915. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20916. EXPECT_EQ("hello", res->body);
  20917. });
  20918. with_single_response(response, [&](Client &cli) {
  20919. auto handle = cli.open_stream("GET", "/");
  20920. ASSERT_TRUE(handle.is_valid()) << response;
  20921. EXPECT_EQ("hello", read_all(handle));
  20922. });
  20923. }
  20924. }
  20925. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20926. // framing headers describe nothing to read and must not be rejected.
  20927. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20928. const std::string framing = "Content-Length: 5\r\n"
  20929. "Transfer-Encoding: chunked\r\n"
  20930. "Connection: close\r\n"
  20931. "\r\n";
  20932. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20933. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20934. });
  20935. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20936. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20937. });
  20938. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20939. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20940. with_single_response(response, [&](Client &cli) {
  20941. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20942. });
  20943. with_single_response(response, [&](Client &cli) {
  20944. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20945. });
  20946. }
  20947. }
  20948. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20949. // header section, so a stream opened on one has nothing to read, whatever
  20950. // framing or coding headers it carries.
  20951. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20952. struct Case {
  20953. const char *method;
  20954. const char *status;
  20955. };
  20956. // A reader of the declared body reports an early close when nothing
  20957. // follows, and hands back what does.
  20958. struct Framing {
  20959. const char *headers;
  20960. const char *after;
  20961. };
  20962. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20963. Case{"GET", "304 Not Modified"}}) {
  20964. for (const auto &f :
  20965. {Framing{"Content-Length: 5\r\n", ""},
  20966. Framing{"Content-Length: 5\r\n", "hello"},
  20967. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20968. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20969. // Not decoded, so a build without Brotli opens it too
  20970. Framing{"Content-Encoding: br\r\n", ""}}) {
  20971. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20972. "Connection: close\r\n"
  20973. "\r\n" +
  20974. f.after;
  20975. with_single_response(response, [&](Client &cli) {
  20976. auto handle = cli.open_stream(c.method, "/");
  20977. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20978. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20979. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20980. });
  20981. }
  20982. }
  20983. }
  20984. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20985. // response, is faulty framing, so the connection is not reused after it.
  20986. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20987. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20988. "Content-Length: 0\r\n"
  20989. "Transfer-Encoding: chunked\r\n"
  20990. "\r\n"
  20991. "5\r\nhello\r\n0\r\n\r\n",
  20992. "HTTP/1.0 200 Connection established\r\n"
  20993. "Connection: keep-alive\r\n"
  20994. "Transfer-Encoding: chunked\r\n"
  20995. "\r\n"
  20996. "5\r\nhello\r\n0\r\n\r\n"}) {
  20997. with_single_response(response, [&](Client &cli) {
  20998. cli.set_keep_alive(true);
  20999. auto res = cli.Get("/");
  21000. ASSERT_TRUE(res) << response;
  21001. EXPECT_EQ("hello", res->body);
  21002. EXPECT_FALSE(cli.is_socket_open()) << response;
  21003. });
  21004. }
  21005. }
  21006. // A payload max length of 0 means no limit, however the body is framed.
  21007. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21008. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21009. "Transfer-Encoding: chunked\r\n"
  21010. "\r\n"
  21011. "5\r\nhello\r\n0\r\n\r\n",
  21012. "HTTP/1.1 200 OK\r\n"
  21013. "Connection: close\r\n"
  21014. "\r\n"
  21015. "hello"}) {
  21016. with_single_response(response, [&](Client &cli) {
  21017. cli.set_payload_max_length(0);
  21018. auto res = cli.Get("/");
  21019. ASSERT_TRUE(res) << response;
  21020. EXPECT_EQ("hello", res->body) << response;
  21021. });
  21022. }
  21023. }
  21024. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21025. Server svr;
  21026. svr.set_payload_max_length(0);
  21027. svr.Post("/echo", [](const Request &req, Response &res) {
  21028. res.set_content(req.body, "text/plain");
  21029. });
  21030. auto port = svr.bind_to_any_port(HOST);
  21031. thread t = thread([&] { svr.listen_after_bind(); });
  21032. auto se = detail::scope_exit([&] {
  21033. svr.stop();
  21034. t.join();
  21035. ASSERT_FALSE(svr.is_running());
  21036. });
  21037. svr.wait_until_ready();
  21038. Client cli(HOST, port);
  21039. auto res = cli.Post(
  21040. "/echo",
  21041. [](size_t /*offset*/, DataSink &sink) {
  21042. sink.write("hello", 5);
  21043. sink.done();
  21044. return true;
  21045. },
  21046. "text/plain");
  21047. ASSERT_TRUE(res);
  21048. EXPECT_EQ(StatusCode::OK_200, res->status);
  21049. EXPECT_EQ("hello", res->body);
  21050. }
  21051. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21052. TEST_F(OpenStreamTest, Gzip) {
  21053. Client cli("127.0.0.1", port_);
  21054. auto handle = cli.open_stream("GET", "/compressible", {},
  21055. {{"Accept-Encoding", "gzip"}});
  21056. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21057. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21058. }
  21059. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21060. Client cli("127.0.0.1", port_);
  21061. auto handle =
  21062. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21063. {{"Accept-Encoding", "gzip"}});
  21064. ASSERT_TRUE(handle.is_valid());
  21065. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21066. EXPECT_EQ("123456789", read_all(handle));
  21067. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21068. }
  21069. #endif
  21070. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21071. TEST_F(OpenStreamTest, Brotli) {
  21072. Client cli("127.0.0.1", port_);
  21073. auto handle =
  21074. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21075. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21076. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21077. }
  21078. #endif
  21079. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21080. TEST_F(OpenStreamTest, Zstd) {
  21081. Client cli("127.0.0.1", port_);
  21082. auto handle = cli.open_stream("GET", "/compressible", {},
  21083. {{"Accept-Encoding", "zstd"}});
  21084. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21085. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21086. }
  21087. #endif
  21088. #ifdef CPPHTTPLIB_SSL_ENABLED
  21089. class SSLOpenStreamTest : public ::testing::Test {
  21090. protected:
  21091. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21092. void SetUp() override {
  21093. svr_.Get("/hello", [](const Request &, Response &res) {
  21094. res.set_content("Hello SSL World!", "text/plain");
  21095. });
  21096. svr_.Get("/chunked", [](const Request &, Response &res) {
  21097. res.set_chunked_content_provider("text/plain",
  21098. [](size_t offset, DataSink &sink) {
  21099. if (offset < 15) {
  21100. sink.write("chunk", 5);
  21101. return true;
  21102. }
  21103. sink.done();
  21104. return true;
  21105. });
  21106. });
  21107. svr_.Post("/echo", [](const Request &req, Response &res) {
  21108. res.set_content(req.body, req.get_header_value("Content-Type"));
  21109. });
  21110. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21111. std::string body = req.body;
  21112. res.set_chunked_content_provider(
  21113. "text/plain", [body](size_t offset, DataSink &sink) {
  21114. if (offset < body.size()) {
  21115. sink.write(body.data() + offset, body.size() - offset);
  21116. }
  21117. sink.done();
  21118. return true;
  21119. });
  21120. });
  21121. port_ = svr_.bind_to_any_port("127.0.0.1");
  21122. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21123. svr_.wait_until_ready();
  21124. }
  21125. void TearDown() override {
  21126. svr_.stop();
  21127. if (thread_.joinable()) thread_.join();
  21128. }
  21129. SSLServer svr_;
  21130. std::thread thread_;
  21131. int port_ = 0;
  21132. };
  21133. TEST_F(SSLOpenStreamTest, Basic) {
  21134. SSLClient cli("127.0.0.1", port_);
  21135. cli.enable_server_certificate_verification(false);
  21136. auto handle = cli.open_stream("GET", "/hello");
  21137. ASSERT_TRUE(handle.is_valid());
  21138. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21139. }
  21140. TEST_F(SSLOpenStreamTest, Chunked) {
  21141. SSLClient cli("127.0.0.1", port_);
  21142. cli.enable_server_certificate_verification(false);
  21143. auto handle = cli.open_stream("GET", "/chunked");
  21144. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21145. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21146. "Transfer-Encoding") == "chunked");
  21147. auto body = read_all(handle);
  21148. EXPECT_EQ("chunkchunkchunk", body);
  21149. }
  21150. TEST_F(SSLOpenStreamTest, Post) {
  21151. SSLClient cli("127.0.0.1", port_);
  21152. cli.enable_server_certificate_verification(false);
  21153. auto handle =
  21154. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21155. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21156. EXPECT_EQ(200, handle.response->status);
  21157. auto body = read_all(handle);
  21158. EXPECT_EQ("Hello SSL POST", body);
  21159. }
  21160. TEST_F(SSLOpenStreamTest, PostChunked) {
  21161. SSLClient cli("127.0.0.1", port_);
  21162. cli.enable_server_certificate_verification(false);
  21163. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21164. "Chunked SSL Data", "text/plain");
  21165. ASSERT_TRUE(handle.is_valid());
  21166. EXPECT_EQ(200, handle.response->status);
  21167. auto body = read_all(handle);
  21168. EXPECT_EQ("Chunked SSL Data", body);
  21169. }
  21170. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21171. // Content-Length is terminated by the server closing the connection. When the
  21172. // SSL peer sends a close_notify after the body, the client must treat it as a
  21173. // clean EOF and return a successful response rather than an error.
  21174. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21176. ASSERT_TRUE(svr.is_valid());
  21177. svr.set_keep_alive_max_count(1);
  21178. const std::string expected_body = "Hello from connection-close response!";
  21179. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21180. res.set_content_provider("text/plain",
  21181. [&](size_t offset, DataSink &sink) -> bool {
  21182. if (offset < expected_body.size()) {
  21183. sink.write(expected_body.data() + offset,
  21184. expected_body.size() - offset);
  21185. }
  21186. sink.done();
  21187. return true;
  21188. });
  21189. });
  21190. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21191. auto se = detail::scope_exit([&] {
  21192. svr.stop();
  21193. listen_thread.join();
  21194. ASSERT_FALSE(svr.is_running());
  21195. });
  21196. svr.wait_until_ready();
  21197. SSLClient cli(HOST, PORT);
  21198. cli.enable_server_certificate_verification(false);
  21199. auto res = cli.Get("/no-content-length");
  21200. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21201. EXPECT_EQ(StatusCode::OK_200, res->status);
  21202. EXPECT_EQ(expected_body, res->body);
  21203. }
  21204. // Without Content-Length, the full buffer size reaches tls::read().
  21205. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21206. if (sizeof(size_t) <= sizeof(int)) {
  21207. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21208. }
  21209. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21210. ASSERT_TRUE(svr.is_valid());
  21211. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21212. res.set_content_provider("text/plain",
  21213. [&](size_t offset, DataSink &sink) -> bool {
  21214. if (offset == 0) { sink.write("Hello", 5); }
  21215. sink.done();
  21216. return true;
  21217. });
  21218. });
  21219. auto port = svr.bind_to_any_port(HOST);
  21220. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21221. auto se = detail::scope_exit([&] {
  21222. svr.stop();
  21223. listen_thread.join();
  21224. });
  21225. svr.wait_until_ready();
  21226. SSLClient cli(HOST, port);
  21227. cli.enable_server_certificate_verification(false);
  21228. auto handle = cli.open_stream("GET", "/no-content-length");
  21229. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21230. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21231. std::unique_ptr<char[]> buf(new char[len]);
  21232. std::string body;
  21233. ssize_t n;
  21234. while ((n = handle.read(buf.get(), len)) > 0) {
  21235. body.append(buf.get(), static_cast<size_t>(n));
  21236. }
  21237. EXPECT_EQ(0, n);
  21238. EXPECT_EQ("Hello", body);
  21239. }
  21240. #endif // CPPHTTPLIB_SSL_ENABLED
  21241. //==============================================================================
  21242. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21243. // results for various scenarios.
  21244. //==============================================================================
  21245. TEST(ParityTest, GetVsOpenStream) {
  21246. Server svr;
  21247. const std::string path = "/parity";
  21248. const std::string content = "Parity test content: hello world";
  21249. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21250. res.set_content(content, "text/plain");
  21251. });
  21252. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21253. auto se = detail::scope_exit([&] {
  21254. svr.stop();
  21255. t.join();
  21256. ASSERT_FALSE(svr.is_running());
  21257. });
  21258. svr.wait_until_ready();
  21259. Client cli(HOST, PORT);
  21260. // Non-stream path
  21261. auto r1 = cli.Get(path);
  21262. ASSERT_TRUE(r1);
  21263. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21264. // Stream path
  21265. auto h = cli.open_stream("GET", path);
  21266. ASSERT_TRUE(h.is_valid());
  21267. EXPECT_EQ(r1->body, read_all(h));
  21268. }
  21269. // Helper to compress data with provided compressor type T
  21270. template <typename Compressor>
  21271. static std::string compress_payload_for_parity(const std::string &in) {
  21272. std::string out;
  21273. Compressor compressor;
  21274. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21275. [&](const char *data, size_t n) {
  21276. out.append(data, n);
  21277. return true;
  21278. });
  21279. EXPECT_TRUE(ok);
  21280. return out;
  21281. }
  21282. // Helper function for compression parity tests
  21283. template <typename Compressor>
  21284. static void test_compression_parity(const std::string &original,
  21285. const std::string &path,
  21286. const std::string &encoding) {
  21287. const std::string compressed =
  21288. compress_payload_for_parity<Compressor>(original);
  21289. Server svr;
  21290. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21291. res.set_content(compressed, "application/octet-stream");
  21292. res.set_header("Content-Encoding", encoding);
  21293. });
  21294. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21295. auto se = detail::scope_exit([&] {
  21296. svr.stop();
  21297. t.join();
  21298. ASSERT_FALSE(svr.is_running());
  21299. });
  21300. svr.wait_until_ready();
  21301. Client cli(HOST, PORT);
  21302. // Non-streaming
  21303. {
  21304. auto res = cli.Get(path);
  21305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21306. EXPECT_EQ(StatusCode::OK_200, res->status);
  21307. EXPECT_EQ(original, res->body);
  21308. }
  21309. // Streaming
  21310. {
  21311. auto h = cli.open_stream("GET", path);
  21312. ASSERT_TRUE(h.is_valid());
  21313. EXPECT_EQ(original, read_all(h));
  21314. }
  21315. }
  21316. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21317. TEST(ParityTest, Gzip) {
  21318. test_compression_parity<detail::gzip_compressor>(
  21319. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21320. }
  21321. #endif
  21322. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21323. TEST(ParityTest, Brotli) {
  21324. test_compression_parity<detail::brotli_compressor>(
  21325. "Hello, brotli parity test payload", "/parity-br", "br");
  21326. }
  21327. #endif
  21328. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21329. TEST(ParityTest, Zstd) {
  21330. test_compression_parity<detail::zstd_compressor>(
  21331. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21332. }
  21333. #endif
  21334. //==============================================================================
  21335. // New Stream API Tests
  21336. //==============================================================================
  21337. inline std::string read_body(httplib::stream::Result &result) {
  21338. std::string body;
  21339. while (result.next()) {
  21340. body.append(result.data(), result.size());
  21341. }
  21342. return body;
  21343. }
  21344. TEST(ClientConnectionTest, Basic) {
  21345. httplib::ClientConnection conn;
  21346. EXPECT_FALSE(conn.is_open());
  21347. conn.sock = 1;
  21348. EXPECT_TRUE(conn.is_open());
  21349. httplib::ClientConnection conn2(std::move(conn));
  21350. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21351. conn2.sock = INVALID_SOCKET;
  21352. }
  21353. // Unified test server for all stream::* tests
  21354. class StreamApiTest : public ::testing::Test {
  21355. protected:
  21356. void SetUp() override {
  21357. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21358. res.set_content("Hello World!", "text/plain");
  21359. });
  21360. svr_.Get("/echo-params",
  21361. [](const httplib::Request &req, httplib::Response &res) {
  21362. std::string r;
  21363. for (const auto &p : req.params) {
  21364. if (!r.empty()) r += "&";
  21365. r += p.first + "=" + p.second;
  21366. }
  21367. res.set_content(r, "text/plain");
  21368. });
  21369. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21370. res.set_content(req.body, req.get_header_value("Content-Type"));
  21371. });
  21372. svr_.Post("/echo-headers",
  21373. [](const httplib::Request &req, httplib::Response &res) {
  21374. std::string r;
  21375. for (const auto &h : req.headers)
  21376. r += h.first + ": " + h.second + "\n";
  21377. res.set_content(r, "text/plain");
  21378. });
  21379. svr_.Post("/echo-params",
  21380. [](const httplib::Request &req, httplib::Response &res) {
  21381. std::string r = "params:";
  21382. for (const auto &p : req.params)
  21383. r += p.first + "=" + p.second + ";";
  21384. res.set_content(r + " body:" + req.body, "text/plain");
  21385. });
  21386. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21387. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21388. });
  21389. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21390. res.set_content("PUT:" + req.body, "text/plain");
  21391. });
  21392. svr_.Patch("/echo",
  21393. [](const httplib::Request &req, httplib::Response &res) {
  21394. res.set_content("PATCH:" + req.body, "text/plain");
  21395. });
  21396. svr_.Delete(
  21397. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21398. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21399. "text/plain");
  21400. });
  21401. svr_.Get("/head-test",
  21402. [](const httplib::Request &, httplib::Response &res) {
  21403. res.set_content("body for HEAD", "text/plain");
  21404. });
  21405. svr_.Options("/options",
  21406. [](const httplib::Request &, httplib::Response &res) {
  21407. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21408. });
  21409. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21410. svr_.wait_until_ready();
  21411. }
  21412. void TearDown() override {
  21413. svr_.stop();
  21414. if (thread_.joinable()) thread_.join();
  21415. }
  21416. httplib::Server svr_;
  21417. std::thread thread_;
  21418. };
  21419. // stream::Get tests
  21420. TEST_F(StreamApiTest, GetBasic) {
  21421. httplib::Client cli(HOST, PORT);
  21422. auto result = httplib::stream::Get(cli, "/hello");
  21423. ASSERT_TRUE(result.is_valid());
  21424. EXPECT_EQ(200, result.status());
  21425. EXPECT_EQ("Hello World!", read_body(result));
  21426. }
  21427. TEST_F(StreamApiTest, GetWithParams) {
  21428. httplib::Client cli(HOST, PORT);
  21429. httplib::Params params{{"foo", "bar"}};
  21430. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21431. ASSERT_TRUE(result.is_valid());
  21432. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21433. }
  21434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21435. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21436. httplib::Client cli(HOST, PORT);
  21437. cli.set_payload_max_length(0);
  21438. auto result = httplib::stream::Get(cli, "/hello");
  21439. ASSERT_TRUE(result.is_valid());
  21440. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21441. EXPECT_EQ("Hello World!", read_body(result));
  21442. }
  21443. #endif
  21444. TEST_F(StreamApiTest, GetConnectionError) {
  21445. httplib::Client cli(HOST, 9999);
  21446. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21447. }
  21448. TEST_F(StreamApiTest, Get404) {
  21449. httplib::Client cli(HOST, PORT);
  21450. auto result = httplib::stream::Get(cli, "/nonexistent");
  21451. EXPECT_TRUE(result.is_valid());
  21452. EXPECT_EQ(404, result.status());
  21453. }
  21454. // stream::Post tests
  21455. TEST_F(StreamApiTest, PostBasic) {
  21456. httplib::Client cli(HOST, PORT);
  21457. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21458. "application/json");
  21459. ASSERT_TRUE(result.is_valid());
  21460. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21461. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21462. }
  21463. TEST_F(StreamApiTest, PostWithHeaders) {
  21464. httplib::Client cli(HOST, PORT);
  21465. httplib::Headers headers{{"X-Custom", "value"}};
  21466. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21467. "text/plain");
  21468. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21469. }
  21470. TEST_F(StreamApiTest, PostWithParams) {
  21471. httplib::Client cli(HOST, PORT);
  21472. httplib::Params params{{"k", "v"}};
  21473. auto result =
  21474. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21475. auto body = read_body(result);
  21476. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21477. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21478. }
  21479. TEST_F(StreamApiTest, PostLarge) {
  21480. httplib::Client cli(HOST, PORT);
  21481. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21482. size_t total = 0;
  21483. while (result.next()) {
  21484. total += result.size();
  21485. }
  21486. EXPECT_EQ(100u * 1024u, total);
  21487. }
  21488. // stream::Put/Patch tests
  21489. TEST_F(StreamApiTest, PutAndPatch) {
  21490. httplib::Client cli(HOST, PORT);
  21491. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21492. EXPECT_EQ("PUT:test", read_body(put));
  21493. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21494. EXPECT_EQ("PATCH:test", read_body(patch));
  21495. }
  21496. // stream::Delete tests
  21497. TEST_F(StreamApiTest, Delete) {
  21498. httplib::Client cli(HOST, PORT);
  21499. auto del1 = httplib::stream::Delete(cli, "/resource");
  21500. EXPECT_EQ("Deleted", read_body(del1));
  21501. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21502. EXPECT_EQ("Deleted:data", read_body(del2));
  21503. }
  21504. // stream::Head/Options tests
  21505. TEST_F(StreamApiTest, HeadAndOptions) {
  21506. httplib::Client cli(HOST, PORT);
  21507. auto head = httplib::stream::Head(cli, "/head-test");
  21508. EXPECT_TRUE(head.is_valid());
  21509. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21510. auto opts = httplib::stream::Options(cli, "/options");
  21511. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21512. }
  21513. // SSL stream::* tests
  21514. #ifdef CPPHTTPLIB_SSL_ENABLED
  21515. class SSLStreamApiTest : public ::testing::Test {
  21516. protected:
  21517. void SetUp() override {
  21518. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21519. res.set_content("Hello SSL!", "text/plain");
  21520. });
  21521. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21522. res.set_content(req.body, "text/plain");
  21523. });
  21524. port_ = svr_.bind_to_any_port("127.0.0.1");
  21525. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21526. svr_.wait_until_ready();
  21527. }
  21528. void TearDown() override {
  21529. svr_.stop();
  21530. if (thread_.joinable()) thread_.join();
  21531. }
  21532. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21533. std::thread thread_;
  21534. int port_ = 0;
  21535. };
  21536. TEST_F(SSLStreamApiTest, GetAndPost) {
  21537. httplib::SSLClient cli("127.0.0.1", port_);
  21538. cli.enable_server_certificate_verification(false);
  21539. auto get = httplib::stream::Get(cli, "/hello");
  21540. EXPECT_EQ("Hello SSL!", read_body(get));
  21541. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21542. EXPECT_EQ("test", read_body(post));
  21543. }
  21544. #endif
  21545. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21546. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21547. // BodyReader
  21548. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21549. // Test that read timeout during streaming is detected
  21550. // Use a large content-length response where server delays mid-stream
  21551. Server svr;
  21552. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21553. // Send a large response with delay in the middle
  21554. res.set_content_provider(
  21555. 1000, // content_length
  21556. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21557. if (offset < 100) {
  21558. // Send first 100 bytes immediately
  21559. std::string data(100, 'A');
  21560. sink.write(data.c_str(), data.size());
  21561. return true;
  21562. }
  21563. // Then delay longer than client timeout
  21564. std::this_thread::sleep_for(std::chrono::seconds(3));
  21565. std::string data(900, 'B');
  21566. sink.write(data.c_str(), data.size());
  21567. return true;
  21568. });
  21569. });
  21570. auto port = 8091;
  21571. std::thread t([&]() { svr.listen("localhost", port); });
  21572. svr.wait_until_ready();
  21573. Client cli("localhost", port);
  21574. cli.set_read_timeout(1, 0); // 1 second timeout
  21575. auto handle = cli.open_stream("GET", "/slow-stream");
  21576. ASSERT_TRUE(handle.is_valid());
  21577. char buf[256];
  21578. ssize_t total = 0;
  21579. ssize_t n;
  21580. bool got_error = false;
  21581. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21582. total += n;
  21583. }
  21584. if (n < 0) {
  21585. got_error = true;
  21586. // Should be timeout or read error
  21587. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21588. handle.get_read_error() == Error::Read)
  21589. << "Actual error: " << to_string(handle.get_read_error());
  21590. }
  21591. // Either we got an error, or we got less data than expected
  21592. EXPECT_TRUE(got_error || total < 1000)
  21593. << "Expected timeout but got all " << total << " bytes";
  21594. svr.stop();
  21595. t.join();
  21596. }
  21597. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21598. // Test connection closed detection via BodyReader
  21599. Server svr;
  21600. std::atomic<bool> close_now{false};
  21601. svr.Get("/will-close", [&](const Request &, Response &res) {
  21602. res.set_content_provider(
  21603. 10000, // Large content_length that we won't fully send
  21604. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21605. if (offset < 100) {
  21606. std::string data(100, 'X');
  21607. sink.write(data.c_str(), data.size());
  21608. return true;
  21609. }
  21610. // Wait for signal then abort
  21611. while (!close_now) {
  21612. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21613. }
  21614. return false; // Abort - server will close connection
  21615. });
  21616. });
  21617. auto port = 8092;
  21618. std::thread t([&]() { svr.listen("localhost", port); });
  21619. svr.wait_until_ready();
  21620. Client cli("localhost", port);
  21621. auto handle = cli.open_stream("GET", "/will-close");
  21622. ASSERT_TRUE(handle.is_valid());
  21623. char buf[256];
  21624. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21625. EXPECT_GT(n, 0) << "First read should succeed";
  21626. // Signal server to close
  21627. close_now = true;
  21628. // Keep reading until error or EOF
  21629. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21630. // Keep reading
  21631. }
  21632. // Should get an error since content_length wasn't satisfied
  21633. if (n < 0) {
  21634. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21635. handle.get_read_error() == Error::Read)
  21636. << "Actual error: " << to_string(handle.get_read_error());
  21637. }
  21638. svr.stop();
  21639. t.join();
  21640. }
  21641. #ifdef CPPHTTPLIB_SSL_ENABLED
  21642. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21643. // Test that read timeout during SSL streaming is detected
  21644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21645. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21646. res.set_content_provider(
  21647. 1000, "text/plain",
  21648. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21649. if (offset < 100) {
  21650. std::string data(100, 'A');
  21651. sink.write(data.c_str(), data.size());
  21652. return true;
  21653. }
  21654. std::this_thread::sleep_for(std::chrono::seconds(3));
  21655. std::string data(900, 'B');
  21656. sink.write(data.c_str(), data.size());
  21657. return true;
  21658. });
  21659. });
  21660. auto port = 8093;
  21661. std::thread t([&]() { svr.listen("localhost", port); });
  21662. svr.wait_until_ready();
  21663. SSLClient cli("localhost", port);
  21664. cli.enable_server_certificate_verification(false);
  21665. cli.set_read_timeout(1, 0); // 1 second timeout
  21666. auto handle = cli.open_stream("GET", "/slow-stream");
  21667. ASSERT_TRUE(handle.is_valid());
  21668. char buf[256];
  21669. ssize_t total = 0;
  21670. ssize_t n;
  21671. bool got_error = false;
  21672. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21673. total += n;
  21674. }
  21675. if (n < 0) {
  21676. got_error = true;
  21677. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21678. handle.get_read_error() == Error::Read)
  21679. << "Actual error: " << to_string(handle.get_read_error());
  21680. }
  21681. EXPECT_TRUE(got_error || total < 1000)
  21682. << "Expected timeout but got all " << total << " bytes";
  21683. svr.stop();
  21684. t.join();
  21685. }
  21686. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21687. // Test SSL connection closed detection
  21688. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21689. std::atomic<bool> close_now{false};
  21690. svr.Get("/will-close", [&](const Request &, Response &res) {
  21691. res.set_content_provider(
  21692. 10000, "text/plain",
  21693. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21694. if (offset < 100) {
  21695. std::string data(100, 'X');
  21696. sink.write(data.c_str(), data.size());
  21697. return true;
  21698. }
  21699. while (!close_now) {
  21700. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21701. }
  21702. return false;
  21703. });
  21704. });
  21705. auto port = 8094;
  21706. std::thread t([&]() { svr.listen("localhost", port); });
  21707. svr.wait_until_ready();
  21708. SSLClient cli("localhost", port);
  21709. cli.enable_server_certificate_verification(false);
  21710. auto handle = cli.open_stream("GET", "/will-close");
  21711. ASSERT_TRUE(handle.is_valid());
  21712. char buf[256];
  21713. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21714. EXPECT_GT(n, 0);
  21715. // Signal server to close
  21716. close_now = true;
  21717. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21718. // Keep reading
  21719. }
  21720. if (n < 0) {
  21721. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21722. handle.get_read_error() == Error::Read)
  21723. << "Actual error: " << to_string(handle.get_read_error());
  21724. }
  21725. svr.stop();
  21726. t.join();
  21727. }
  21728. #endif
  21729. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21730. using namespace httplib;
  21731. // Create a test file
  21732. const char *fname = "etag_testfile.txt";
  21733. const char *content = "etag-content";
  21734. {
  21735. std::ofstream ofs(fname);
  21736. ofs << content;
  21737. ASSERT_TRUE(ofs.good());
  21738. }
  21739. Server svr;
  21740. svr.set_mount_point("/static", ".");
  21741. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21742. svr.wait_until_ready();
  21743. Client cli(HOST, PORT);
  21744. // First request: should get 200 with ETag header
  21745. auto res1 = cli.Get("/static/etag_testfile.txt");
  21746. ASSERT_TRUE(res1);
  21747. ASSERT_EQ(200, res1->status);
  21748. ASSERT_TRUE(res1->has_header("ETag"));
  21749. std::string etag = res1->get_header_value("ETag");
  21750. EXPECT_FALSE(etag.empty());
  21751. // Verify ETag format: W/"hex-hex"
  21752. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21753. EXPECT_EQ('W', etag[0]);
  21754. EXPECT_EQ('/', etag[1]);
  21755. EXPECT_EQ('"', etag[2]);
  21756. EXPECT_EQ('"', etag.back());
  21757. // Exact match: expect 304 Not Modified
  21758. Headers h2 = {{"If-None-Match", etag}};
  21759. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21760. ASSERT_TRUE(res2);
  21761. EXPECT_EQ(304, res2->status);
  21762. // Wildcard match: expect 304 Not Modified
  21763. Headers h3 = {{"If-None-Match", "*"}};
  21764. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21765. ASSERT_TRUE(res3);
  21766. EXPECT_EQ(304, res3->status);
  21767. // Non-matching ETag: expect 200
  21768. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21769. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21770. ASSERT_TRUE(res4);
  21771. EXPECT_EQ(200, res4->status);
  21772. // Multiple ETags with one matching: expect 304
  21773. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21774. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21775. ASSERT_TRUE(res5);
  21776. EXPECT_EQ(304, res5->status);
  21777. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21778. // that equivalent to the single comma-separated list above, so the match on
  21779. // the second line must still be found.
  21780. Headers h6;
  21781. h6.emplace("If-None-Match", "W/\"other\"");
  21782. h6.emplace("If-None-Match", etag);
  21783. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21784. ASSERT_TRUE(res6);
  21785. EXPECT_EQ(304, res6->status);
  21786. svr.stop();
  21787. t.join();
  21788. std::remove(fname);
  21789. }
  21790. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21791. using namespace httplib;
  21792. Server svr;
  21793. svr.set_mount_point("/static", ".");
  21794. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21795. svr.wait_until_ready();
  21796. Client cli(HOST, PORT);
  21797. // Send If-None-Match: * to a non-existent file
  21798. Headers h = {{"If-None-Match", "*"}};
  21799. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21801. EXPECT_EQ(404, res->status);
  21802. svr.stop();
  21803. t.join();
  21804. }
  21805. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21806. using namespace httplib;
  21807. // Create a test file
  21808. const char *fname = "etag_boundary_testfile.txt";
  21809. const char *content = "boundary-test";
  21810. {
  21811. std::ofstream ofs(fname);
  21812. ofs << content;
  21813. ASSERT_TRUE(ofs.good());
  21814. }
  21815. Server svr;
  21816. svr.set_mount_point("/static", ".");
  21817. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21818. svr.wait_until_ready();
  21819. Client cli(HOST, PORT);
  21820. // Get the actual ETag
  21821. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21822. ASSERT_TRUE(res1);
  21823. ASSERT_EQ(200, res1->status);
  21824. ASSERT_TRUE(res1->has_header("ETag"));
  21825. std::string etag = res1->get_header_value("ETag");
  21826. // Test 1: Very long ETag value (longer than actual ETag)
  21827. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21828. Headers h1 = {{"If-None-Match", "W/"
  21829. "\"very-long-etag-value-that-is-much-longer-"
  21830. "than-the-actual-etag-value\""}};
  21831. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21832. ASSERT_TRUE(res2);
  21833. EXPECT_EQ(200, res2->status); // Should not match
  21834. // Test 2: Long string followed by wildcard
  21835. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21836. // string)
  21837. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21838. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21839. ASSERT_TRUE(res3);
  21840. EXPECT_EQ(304, res3->status); // Should match on "*"
  21841. // Test 3: Wildcard followed by long string
  21842. // Should match on "*" immediately and return 304
  21843. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21844. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21845. ASSERT_TRUE(res4);
  21846. EXPECT_EQ(304, res4->status); // Should match on "*"
  21847. // Test 4: Multiple long non-matching values
  21848. // Should NOT match and return 200 (test that all comparisons are safe)
  21849. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21850. "W/\"second-long-non-matching-value\", "
  21851. "W/\"third-long-non-matching-value\""}};
  21852. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21853. ASSERT_TRUE(res5);
  21854. EXPECT_EQ(200, res5->status); // Should not match
  21855. // Test 5: Single character that is not "*" (edge case)
  21856. Headers h5 = {{"If-None-Match", "X"}};
  21857. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21858. ASSERT_TRUE(res6);
  21859. EXPECT_EQ(200, res6->status); // Should not match
  21860. svr.stop();
  21861. t.join();
  21862. std::remove(fname);
  21863. }
  21864. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21865. using namespace httplib;
  21866. // Create a test file
  21867. const char *fname = "ims_testfile.txt";
  21868. const char *content = "if-modified-since-test";
  21869. {
  21870. std::ofstream ofs(fname);
  21871. ofs << content;
  21872. ASSERT_TRUE(ofs.good());
  21873. }
  21874. Server svr;
  21875. svr.set_mount_point("/static", ".");
  21876. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21877. svr.wait_until_ready();
  21878. Client cli(HOST, PORT);
  21879. // First request: should get 200 with Last-Modified header
  21880. auto res1 = cli.Get("/static/ims_testfile.txt");
  21881. ASSERT_TRUE(res1);
  21882. ASSERT_EQ(200, res1->status);
  21883. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21884. std::string last_modified = res1->get_header_value("Last-Modified");
  21885. EXPECT_FALSE(last_modified.empty());
  21886. // If-Modified-Since with same time: expect 304
  21887. Headers h2 = {{"If-Modified-Since", last_modified}};
  21888. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21889. ASSERT_TRUE(res2);
  21890. EXPECT_EQ(304, res2->status);
  21891. // If-Modified-Since with future time: expect 304
  21892. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21893. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21894. ASSERT_TRUE(res3);
  21895. EXPECT_EQ(304, res3->status);
  21896. // If-Modified-Since with past time: expect 200
  21897. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21898. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21899. ASSERT_TRUE(res4);
  21900. EXPECT_EQ(200, res4->status);
  21901. // If-None-Match takes precedence over If-Modified-Since
  21902. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21903. ASSERT_TRUE(res1->has_header("ETag"));
  21904. std::string etag = res1->get_header_value("ETag");
  21905. Headers h5 = {{"If-None-Match", etag},
  21906. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21907. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21908. ASSERT_TRUE(res5);
  21909. EXPECT_EQ(304, res5->status);
  21910. svr.stop();
  21911. t.join();
  21912. std::remove(fname);
  21913. }
  21914. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21915. using namespace httplib;
  21916. Server svr;
  21917. // Endpoint that returns compressible content
  21918. svr.Get("/compressible", [](const Request &, Response &res) {
  21919. // Return a large enough body to trigger compression
  21920. std::string body(1000, 'a');
  21921. res.set_content(body, "text/plain");
  21922. });
  21923. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21924. svr.wait_until_ready();
  21925. Client cli(HOST, PORT);
  21926. // Request with gzip support: should get Vary header when compressed
  21927. cli.set_compress(true);
  21928. auto res1 = cli.Get("/compressible");
  21929. ASSERT_TRUE(res1);
  21930. EXPECT_EQ(200, res1->status);
  21931. // If Content-Encoding is set, Vary should also be set
  21932. if (res1->has_header("Content-Encoding")) {
  21933. EXPECT_TRUE(res1->has_header("Vary"));
  21934. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21935. }
  21936. // Request without Accept-Encoding header: should not have compression
  21937. Headers h_no_compress;
  21938. auto res2 = cli.Get("/compressible", h_no_compress);
  21939. ASSERT_TRUE(res2);
  21940. EXPECT_EQ(200, res2->status);
  21941. // Verify Vary header is present when compression is applied
  21942. // (the exact behavior depends on server configuration)
  21943. svr.stop();
  21944. t.join();
  21945. }
  21946. TEST(ETagTest, IfRangeWithETag) {
  21947. using namespace httplib;
  21948. // Create a test file with known content
  21949. const char *fname = "if_range_testfile.txt";
  21950. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21951. {
  21952. std::ofstream ofs(fname);
  21953. ofs << content;
  21954. ASSERT_TRUE(ofs.good());
  21955. }
  21956. Server svr;
  21957. svr.set_mount_point("/static", ".");
  21958. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21959. svr.wait_until_ready();
  21960. Client cli(HOST, PORT);
  21961. // First request: get ETag
  21962. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21963. ASSERT_TRUE(res1);
  21964. ASSERT_EQ(200, res1->status);
  21965. ASSERT_TRUE(res1->has_header("ETag"));
  21966. std::string etag = res1->get_header_value("ETag");
  21967. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21968. // Since our server generates weak ETags (W/"..."), If-Range with our
  21969. // ETag should NOT result in partial content - it should return full content.
  21970. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21971. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21972. ASSERT_TRUE(res2);
  21973. // Weak ETag in If-Range -> full content (200), not partial (206)
  21974. EXPECT_EQ(200, res2->status);
  21975. EXPECT_EQ(content, res2->body);
  21976. EXPECT_FALSE(res2->has_header("Content-Range"));
  21977. // Range request with non-matching If-Range (ETag): should get 200 (full
  21978. // content)
  21979. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21980. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21981. ASSERT_TRUE(res3);
  21982. EXPECT_EQ(200, res3->status);
  21983. EXPECT_EQ(content, res3->body);
  21984. EXPECT_FALSE(res3->has_header("Content-Range"));
  21985. // Range request with strong ETag (hypothetical - our server doesn't generate
  21986. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21987. // should return full content)
  21988. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21989. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21990. ASSERT_TRUE(res4);
  21991. EXPECT_EQ(200, res4->status);
  21992. EXPECT_EQ(content, res4->body);
  21993. EXPECT_FALSE(res4->has_header("Content-Range"));
  21994. svr.stop();
  21995. t.join();
  21996. std::remove(fname);
  21997. }
  21998. TEST(ETagTest, IfRangeWithDate) {
  21999. using namespace httplib;
  22000. // Create a test file
  22001. const char *fname = "if_range_date_testfile.txt";
  22002. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22003. {
  22004. std::ofstream ofs(fname);
  22005. ofs << content;
  22006. ASSERT_TRUE(ofs.good());
  22007. }
  22008. Server svr;
  22009. svr.set_mount_point("/static", ".");
  22010. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22011. svr.wait_until_ready();
  22012. Client cli(HOST, PORT);
  22013. // First request: get Last-Modified
  22014. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22015. ASSERT_TRUE(res1);
  22016. ASSERT_EQ(200, res1->status);
  22017. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22018. std::string last_modified = res1->get_header_value("Last-Modified");
  22019. // Range request with matching If-Range (date): should get 206
  22020. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22021. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22022. ASSERT_TRUE(res2);
  22023. EXPECT_EQ(206, res2->status);
  22024. EXPECT_EQ("FGHIJ", res2->body);
  22025. // Range request with old If-Range date: should get 200 (full content)
  22026. Headers h3 = {{"Range", "bytes=5-9"},
  22027. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22028. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22029. ASSERT_TRUE(res3);
  22030. EXPECT_EQ(200, res3->status);
  22031. EXPECT_EQ(content, res3->body);
  22032. // Range request with future If-Range date: should get 206
  22033. Headers h4 = {{"Range", "bytes=0-4"},
  22034. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22035. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22036. ASSERT_TRUE(res4);
  22037. EXPECT_EQ(206, res4->status);
  22038. EXPECT_EQ("ABCDE", res4->body);
  22039. svr.stop();
  22040. t.join();
  22041. std::remove(fname);
  22042. }
  22043. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22044. using namespace httplib;
  22045. const char *fname = "etag_malformed.txt";
  22046. const char *content = "malformed-etag";
  22047. {
  22048. std::ofstream ofs(fname);
  22049. ofs << content;
  22050. ASSERT_TRUE(ofs.good());
  22051. }
  22052. Server svr;
  22053. svr.set_mount_point("/static", ".");
  22054. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22055. svr.wait_until_ready();
  22056. Client cli(HOST, PORT);
  22057. // baseline: should get 200 and an ETag
  22058. auto res1 = cli.Get("/static/etag_malformed.txt");
  22059. ASSERT_TRUE(res1);
  22060. ASSERT_EQ(200, res1->status);
  22061. ASSERT_TRUE(res1->has_header("ETag"));
  22062. // Malformed ETag value (missing quotes) should be treated as non-matching
  22063. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22064. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22065. ASSERT_TRUE(res_bad);
  22066. EXPECT_EQ(200, res_bad->status);
  22067. // Whitespace-only header value should be considered invalid / non-matching
  22068. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22069. "Host: localhost\r\n"
  22070. "If-None-Match: \r\n"
  22071. "Connection: close\r\n"
  22072. "\r\n";
  22073. std::string out;
  22074. ASSERT_TRUE(send_request(5, raw_req, &out));
  22075. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22076. svr.stop();
  22077. t.join();
  22078. std::remove(fname);
  22079. }
  22080. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22081. using namespace httplib;
  22082. const char *fname = "ims_invalid_format.txt";
  22083. const char *content = "ims-bad-format";
  22084. {
  22085. std::ofstream ofs(fname);
  22086. ofs << content;
  22087. ASSERT_TRUE(ofs.good());
  22088. }
  22089. Server svr;
  22090. svr.set_mount_point("/static", ".");
  22091. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22092. svr.wait_until_ready();
  22093. Client cli(HOST, PORT);
  22094. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22095. ASSERT_TRUE(res1);
  22096. ASSERT_EQ(200, res1->status);
  22097. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22098. // If-Modified-Since with invalid format should not result in 304
  22099. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22100. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22101. ASSERT_TRUE(res_bad);
  22102. EXPECT_EQ(200, res_bad->status);
  22103. // If-Range with invalid date format should be treated as mismatch -> full
  22104. // content (200)
  22105. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22106. {"If-Range", "invalid-date"}};
  22107. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22108. ASSERT_TRUE(res_ifrange);
  22109. EXPECT_EQ(200, res_ifrange->status);
  22110. svr.stop();
  22111. t.join();
  22112. std::remove(fname);
  22113. }
  22114. TEST(ETagTest, IfRangeWithMalformedETag) {
  22115. using namespace httplib;
  22116. const char *fname = "ifrange_malformed.txt";
  22117. const std::string content = "0123456789";
  22118. {
  22119. std::ofstream ofs(fname);
  22120. ofs << content;
  22121. ASSERT_TRUE(ofs.good());
  22122. }
  22123. Server svr;
  22124. svr.set_mount_point("/static", ".");
  22125. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22126. svr.wait_until_ready();
  22127. Client cli(HOST, PORT);
  22128. // First request: get ETag
  22129. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22130. ASSERT_TRUE(res1);
  22131. ASSERT_EQ(200, res1->status);
  22132. ASSERT_TRUE(res1->has_header("ETag"));
  22133. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22134. // full content (200)
  22135. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22136. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22137. ASSERT_TRUE(res2);
  22138. EXPECT_EQ(200, res2->status);
  22139. EXPECT_EQ(content, res2->body);
  22140. svr.stop();
  22141. t.join();
  22142. std::remove(fname);
  22143. }
  22144. TEST(ETagTest, ExtremeLargeDateValues) {
  22145. using namespace httplib;
  22146. const char *fname = "ims_extreme_date.txt";
  22147. const char *content = "ims-extreme-date";
  22148. {
  22149. std::ofstream ofs(fname);
  22150. ofs << content;
  22151. ASSERT_TRUE(ofs.good());
  22152. }
  22153. Server svr;
  22154. svr.set_mount_point("/static", ".");
  22155. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22156. svr.wait_until_ready();
  22157. Client cli(HOST, PORT);
  22158. auto res1 = cli.Get(std::string("/static/") + fname);
  22159. ASSERT_TRUE(res1);
  22160. ASSERT_EQ(200, res1->status);
  22161. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22162. // Extremely large year that may overflow date parsing routines.
  22163. Headers h_large_date = {
  22164. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22165. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22166. ASSERT_TRUE(res_bad);
  22167. // Expect server to treat this as invalid/mismatch and return full content
  22168. EXPECT_EQ(200, res_bad->status);
  22169. // If-Range with extremely large date should be treated as mismatch -> full
  22170. // content (200)
  22171. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22172. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22173. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22174. ASSERT_TRUE(res_ifrange);
  22175. EXPECT_EQ(200, res_ifrange->status);
  22176. svr.stop();
  22177. t.join();
  22178. std::remove(fname);
  22179. }
  22180. TEST(ETagTest, NegativeFileModificationTime) {
  22181. using namespace httplib;
  22182. const char *fname = "ims_negative_mtime.txt";
  22183. const std::string content = "negative-mtime";
  22184. {
  22185. std::ofstream ofs(fname);
  22186. ofs << content;
  22187. ASSERT_TRUE(ofs.good());
  22188. }
  22189. // Try to set file mtime to a negative value. This may fail on some
  22190. // platforms/filesystems; if it fails, the test will still verify server
  22191. // behaves safely by performing a regular conditional request.
  22192. #if defined(__APPLE__) || defined(__linux__)
  22193. bool set_negative = false;
  22194. do {
  22195. struct timeval times[2];
  22196. // access time: now
  22197. times[0].tv_sec = time(nullptr);
  22198. times[0].tv_usec = 0;
  22199. // modification time: negative (e.g., -1)
  22200. times[1].tv_sec = -1;
  22201. times[1].tv_usec = 0;
  22202. if (utimes(fname, times) == 0) { set_negative = true; }
  22203. } while (0);
  22204. #else
  22205. bool set_negative = false;
  22206. #endif
  22207. Server svr;
  22208. svr.set_mount_point("/static", ".");
  22209. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22210. svr.wait_until_ready();
  22211. Client cli(HOST, PORT);
  22212. auto res1 = cli.Get(std::string("/static/") + fname);
  22213. ASSERT_TRUE(res1);
  22214. ASSERT_EQ(200, res1->status);
  22215. bool has_last_modified = res1->has_header("Last-Modified");
  22216. std::string last_modified;
  22217. if (has_last_modified) {
  22218. last_modified = res1->get_header_value("Last-Modified");
  22219. }
  22220. if (set_negative) {
  22221. // If we successfully set a negative mtime, ensure server returns a
  22222. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22223. // with an old date and ensure server handles it without crash.
  22224. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22225. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22226. ASSERT_TRUE(res2);
  22227. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22228. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22229. } else {
  22230. // Could not set negative mtime on this platform; fall back to verifying
  22231. // that normal invalid/malformed dates are treated safely (non-304).
  22232. Headers h_bad_date = {
  22233. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22234. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22235. ASSERT_TRUE(res_bad);
  22236. EXPECT_EQ(200, res_bad->status);
  22237. }
  22238. svr.stop();
  22239. t.join();
  22240. std::remove(fname);
  22241. }
  22242. //==============================================================================
  22243. // Integration Tests with Server
  22244. //==============================================================================
  22245. class SSEIntegrationTest : public ::testing::Test {
  22246. protected:
  22247. void SetUp() override {
  22248. stop_server_.store(false);
  22249. events_.clear();
  22250. server_ = httplib::detail::make_unique<Server>();
  22251. setup_server();
  22252. start_server();
  22253. }
  22254. void TearDown() override {
  22255. stop_server_.store(true);
  22256. event_cv_.notify_all();
  22257. server_->stop();
  22258. if (server_thread_.joinable()) { server_thread_.join(); }
  22259. }
  22260. void setup_server() {
  22261. // Simple SSE endpoint
  22262. server_->Get("/events", [this](const Request &req, Response &res) {
  22263. auto last_id = req.get_header_value("Last-Event-ID");
  22264. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22265. res.set_chunked_content_provider(
  22266. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22267. std::unique_lock<std::mutex> lock(event_mutex_);
  22268. if (event_cv_.wait_for(
  22269. lock, std::chrono::milliseconds(200), [this] {
  22270. return !events_.empty() || stop_server_.load();
  22271. })) {
  22272. if (stop_server_.load()) { return false; }
  22273. if (!events_.empty()) {
  22274. std::string event = events_.front();
  22275. events_.erase(events_.begin());
  22276. sink.write(event.data(), event.size());
  22277. return true;
  22278. }
  22279. }
  22280. return !stop_server_.load();
  22281. });
  22282. });
  22283. // Endpoint that returns error
  22284. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22285. res.status = 500;
  22286. res.set_content("Internal Server Error", "text/plain");
  22287. });
  22288. // Endpoint for custom event types
  22289. server_->Get("/custom-events", [](const Request &, Response &res) {
  22290. res.set_chunked_content_provider(
  22291. "text/event-stream", [](size_t offset, DataSink &sink) {
  22292. if (offset == 0) {
  22293. std::string event = "event: update\ndata: updated\n\n"
  22294. "event: delete\ndata: deleted\n\n";
  22295. sink.write(event.data(), event.size());
  22296. }
  22297. return false; // End stream after sending
  22298. });
  22299. });
  22300. }
  22301. void start_server() {
  22302. port_ = server_->bind_to_any_port(HOST);
  22303. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22304. // Wait for server to start
  22305. while (!server_->is_running()) {
  22306. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22307. }
  22308. }
  22309. int get_port() const { return port_; }
  22310. void send_event(const std::string &event) {
  22311. std::lock_guard<std::mutex> lock(event_mutex_);
  22312. events_.push_back(event);
  22313. event_cv_.notify_all();
  22314. }
  22315. std::unique_ptr<Server> server_;
  22316. std::thread server_thread_;
  22317. std::mutex event_mutex_;
  22318. std::condition_variable event_cv_;
  22319. std::vector<std::string> events_;
  22320. std::atomic<bool> stop_server_{false};
  22321. std::string last_received_event_id_;
  22322. int port_ = 0;
  22323. };
  22324. //==============================================================================
  22325. // SSE Parsing Tests
  22326. //==============================================================================
  22327. class SSEParsingTest : public SSEIntegrationTest {
  22328. protected:
  22329. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22330. // A trailing sentinel event tells when the whole stream has been parsed.
  22331. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22332. auto body = stream + "event: end\ndata: end\n\n";
  22333. server_->Get("/parse", [body](const Request &, Response &res) {
  22334. res.set_content(body, "text/event-stream");
  22335. });
  22336. return collect("/parse");
  22337. }
  22338. // Runs SSEClient against path until an "end" event arrives and returns the
  22339. // messages dispatched before it
  22340. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22341. Client client(HOST, get_port());
  22342. sse::SSEClient sse(client, path);
  22343. std::mutex mutex;
  22344. std::condition_variable cv;
  22345. std::vector<sse::SSEMessage> messages;
  22346. auto done = false;
  22347. sse.on_message([&](const sse::SSEMessage &msg) {
  22348. std::lock_guard<std::mutex> lock(mutex);
  22349. // Ignore a replay from a reconnect that races with stop()
  22350. if (!done) { messages.push_back(msg); }
  22351. });
  22352. sse.on_event("end", [&](const sse::SSEMessage &) {
  22353. std::lock_guard<std::mutex> lock(mutex);
  22354. done = true;
  22355. cv.notify_all();
  22356. });
  22357. sse.set_reconnect_interval(100);
  22358. sse.start_async();
  22359. {
  22360. std::unique_lock<std::mutex> lock(mutex);
  22361. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22362. }
  22363. sse.stop();
  22364. EXPECT_TRUE(done);
  22365. return messages;
  22366. }
  22367. };
  22368. TEST_F(SSEParsingTest, SingleLineData) {
  22369. auto msgs = parse("data: hello\n\n");
  22370. ASSERT_EQ(msgs.size(), 1u);
  22371. EXPECT_EQ(msgs[0].data, "hello");
  22372. EXPECT_EQ(msgs[0].event, "message");
  22373. }
  22374. TEST_F(SSEParsingTest, MultiLineData) {
  22375. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22376. ASSERT_EQ(msgs.size(), 1u);
  22377. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22378. }
  22379. TEST_F(SSEParsingTest, CustomEventType) {
  22380. auto msgs = parse("event: update\ndata: payload\n\n");
  22381. ASSERT_EQ(msgs.size(), 1u);
  22382. EXPECT_EQ(msgs[0].event, "update");
  22383. EXPECT_EQ(msgs[0].data, "payload");
  22384. }
  22385. TEST_F(SSEParsingTest, EventIdHandling) {
  22386. auto msgs = parse("id: 12345\ndata: test\n\n");
  22387. ASSERT_EQ(msgs.size(), 1u);
  22388. EXPECT_EQ(msgs[0].id, "12345");
  22389. }
  22390. TEST_F(SSEParsingTest, EmptyEventId) {
  22391. auto msgs = parse("id:\ndata: test\n\n");
  22392. ASSERT_EQ(msgs.size(), 1u);
  22393. EXPECT_EQ(msgs[0].id, "");
  22394. }
  22395. TEST_F(SSEParsingTest, CommentsIgnored) {
  22396. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22397. ASSERT_EQ(msgs.size(), 1u);
  22398. EXPECT_EQ(msgs[0].data, "hello");
  22399. EXPECT_EQ(msgs[0].event, "message");
  22400. }
  22401. TEST_F(SSEParsingTest, ColonInValue) {
  22402. auto msgs = parse("data: hello:world:test\n\n");
  22403. ASSERT_EQ(msgs.size(), 1u);
  22404. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22405. }
  22406. TEST_F(SSEParsingTest, FieldNameOnly) {
  22407. // A line without a colon is a field name with an empty value
  22408. auto msgs = parse("data\n\n");
  22409. ASSERT_EQ(msgs.size(), 1u);
  22410. EXPECT_EQ(msgs[0].data, "");
  22411. }
  22412. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22413. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22414. ASSERT_EQ(msgs.size(), 1u);
  22415. EXPECT_EQ(msgs[0].event, "update");
  22416. EXPECT_EQ(msgs[0].data, "hello");
  22417. }
  22418. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22419. auto msgs = parse("data\r\n\r\n");
  22420. ASSERT_EQ(msgs.size(), 1u);
  22421. EXPECT_EQ(msgs[0].data, "");
  22422. }
  22423. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22424. auto msgs = parse("event: update\rdata: hello\r\r");
  22425. ASSERT_EQ(msgs.size(), 1u);
  22426. EXPECT_EQ(msgs[0].event, "update");
  22427. EXPECT_EQ(msgs[0].data, "hello");
  22428. }
  22429. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22430. // Chunk boundaries fall inside every \r\n and right before the first one
  22431. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22432. "\n\r", "\nevent: end\ndata: end\n\n"};
  22433. server_->Get("/split", [chunks](const Request &, Response &res) {
  22434. auto i = std::make_shared<size_t>(0);
  22435. res.set_chunked_content_provider(
  22436. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22437. if (*i == chunks.size()) {
  22438. sink.done();
  22439. } else {
  22440. sink.write(chunks[*i].data(), chunks[*i].size());
  22441. (*i)++;
  22442. }
  22443. return true;
  22444. });
  22445. });
  22446. auto msgs = collect("/split");
  22447. ASSERT_EQ(msgs.size(), 1u);
  22448. EXPECT_EQ(msgs[0].event, "update");
  22449. EXPECT_EQ(msgs[0].data, "hello");
  22450. }
  22451. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22452. // Only a BOM at the start of the stream is ignored
  22453. auto msgs = parse("\xEF\xBB\xBF"
  22454. "data: first\n\n"
  22455. "\xEF\xBB\xBF"
  22456. "data: second\n\n");
  22457. ASSERT_EQ(msgs.size(), 1u);
  22458. EXPECT_EQ(msgs[0].data, "first");
  22459. }
  22460. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22461. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22462. ASSERT_EQ(msgs.size(), 1u);
  22463. EXPECT_EQ(msgs[0].data, "hello");
  22464. EXPECT_EQ(msgs[0].event, "message");
  22465. }
  22466. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22467. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22468. ASSERT_EQ(msgs.size(), 2u);
  22469. EXPECT_EQ(msgs[0].data, "hello");
  22470. EXPECT_EQ(msgs[1].data, "hello");
  22471. }
  22472. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22473. // An event without data is not dispatched, and its type must not leak
  22474. // into the next event
  22475. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22476. ASSERT_EQ(msgs.size(), 1u);
  22477. EXPECT_EQ(msgs[0].event, "message");
  22478. EXPECT_EQ(msgs[0].data, "hello");
  22479. }
  22480. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22481. // Also when the empty field replaces an earlier type
  22482. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22483. ASSERT_EQ(msgs.size(), 2u);
  22484. EXPECT_EQ(msgs[0].event, "message");
  22485. EXPECT_EQ(msgs[1].event, "message");
  22486. }
  22487. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22488. // The first connection sends only an id; the second echoes back the
  22489. // Last-Event-ID it was reconnected with
  22490. std::atomic<int> connection_count{0};
  22491. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22492. if (connection_count++ == 0) {
  22493. res.set_content("id: 42\n\n", "text/event-stream");
  22494. } else {
  22495. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22496. "\n\nevent: end\ndata: end\n\n",
  22497. "text/event-stream");
  22498. }
  22499. });
  22500. auto msgs = collect("/id-only");
  22501. ASSERT_EQ(msgs.size(), 1u);
  22502. EXPECT_EQ(msgs[0].data, "42");
  22503. }
  22504. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22505. // The first connection sets an id and then clears it with an empty one; the
  22506. // second reports whether it was reconnected with a Last-Event-ID
  22507. std::atomic<int> connection_count{0};
  22508. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22509. if (connection_count++ == 0) {
  22510. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22511. "text/event-stream");
  22512. } else {
  22513. res.set_content(
  22514. std::string("data: ") +
  22515. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22516. "\n\nevent: end\ndata: end\n\n",
  22517. "text/event-stream");
  22518. }
  22519. });
  22520. auto msgs = collect("/id-clear");
  22521. ASSERT_EQ(msgs.size(), 3u);
  22522. EXPECT_EQ(msgs[0].id, "1");
  22523. EXPECT_EQ(msgs[1].id, "");
  22524. EXPECT_EQ(msgs[2].data, "not sent");
  22525. }
  22526. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22527. // The first connection sets an id and then sends ids that cannot be carried
  22528. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22529. // with
  22530. std::atomic<int> connection_count{0};
  22531. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22532. if (connection_count++ == 0) {
  22533. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22534. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22535. "text/event-stream");
  22536. } else {
  22537. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22538. "\n\nevent: end\ndata: end\n\n",
  22539. "text/event-stream");
  22540. }
  22541. });
  22542. auto msgs = collect("/id-unsendable");
  22543. ASSERT_EQ(msgs.size(), 1u);
  22544. EXPECT_EQ(msgs[0].data, "42");
  22545. }
  22546. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22547. auto msgs = parse("event: notification\nid: evt-42\n"
  22548. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22549. ASSERT_EQ(msgs.size(), 1u);
  22550. EXPECT_EQ(msgs[0].event, "notification");
  22551. EXPECT_EQ(msgs[0].id, "evt-42");
  22552. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22553. }
  22554. TEST(SSEMessageTest, Clear) {
  22555. sse::SSEMessage msg;
  22556. msg.event = "custom";
  22557. msg.data = "some data";
  22558. msg.id = "123";
  22559. msg.clear();
  22560. EXPECT_EQ(msg.event, "message");
  22561. EXPECT_EQ(msg.data, "");
  22562. EXPECT_EQ(msg.id, "");
  22563. }
  22564. //==============================================================================
  22565. // SSE Integration Tests
  22566. //==============================================================================
  22567. // Test: Successful connection and on_open callback
  22568. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22569. // Add a simple endpoint that sends one event and closes
  22570. server_->Get("/simple-event", [](const Request &, Response &res) {
  22571. res.set_chunked_content_provider(
  22572. "text/event-stream", [](size_t offset, DataSink &sink) {
  22573. if (offset == 0) {
  22574. std::string event = "data: hello\n\n";
  22575. sink.write(event.data(), event.size());
  22576. }
  22577. return false; // Close stream after sending
  22578. });
  22579. });
  22580. Client client("localhost", get_port());
  22581. sse::SSEClient sse(client, "/simple-event");
  22582. std::atomic<bool> open_called{false};
  22583. std::atomic<bool> message_received{false};
  22584. sse.on_open([&open_called]() { open_called.store(true); });
  22585. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22586. if (msg.data == "hello") { message_received.store(true); }
  22587. });
  22588. sse.set_reconnect_interval(100);
  22589. sse.set_max_reconnect_attempts(1);
  22590. // Start async
  22591. sse.start_async();
  22592. // Wait for message to be processed
  22593. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22594. sse.stop();
  22595. EXPECT_TRUE(open_called.load());
  22596. EXPECT_TRUE(message_received.load());
  22597. }
  22598. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22599. // A data line that never ends.
  22600. server_->Get("/endless-line", [](const Request &, Response &res) {
  22601. res.set_chunked_content_provider(
  22602. "text/event-stream", [](size_t offset, DataSink &sink) {
  22603. if (offset == 0) { sink.write("data: ", 6); }
  22604. std::string chunk(64 * 1024, 'A');
  22605. return sink.write(chunk.data(), chunk.size());
  22606. });
  22607. });
  22608. Client client("localhost", get_port());
  22609. sse::SSEClient sse(client, "/endless-line");
  22610. std::atomic<bool> too_long{false};
  22611. sse.on_error([&](Error err) {
  22612. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22613. });
  22614. sse.set_max_reconnect_attempts(1);
  22615. sse.start_async();
  22616. for (int i = 0; i < 500 && !too_long; i++) {
  22617. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22618. }
  22619. sse.stop();
  22620. EXPECT_TRUE(too_long);
  22621. }
  22622. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22623. // Far more in all than the client's payload limit below.
  22624. server_->Get("/many-events", [](const Request &, Response &res) {
  22625. res.set_chunked_content_provider(
  22626. "text/event-stream", [](size_t offset, DataSink &sink) {
  22627. if (offset == 0) {
  22628. std::string events;
  22629. for (int i = 0; i < 1000; i++) {
  22630. events += "data: message\n\n";
  22631. }
  22632. sink.write(events.data(), events.size());
  22633. }
  22634. return false;
  22635. });
  22636. });
  22637. Client client("localhost", get_port());
  22638. client.set_payload_max_length(1024);
  22639. sse::SSEClient sse(client, "/many-events");
  22640. std::atomic<int> messages{0};
  22641. std::atomic<bool> too_large{false};
  22642. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22643. sse.on_error([&](Error err) {
  22644. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22645. });
  22646. sse.set_max_reconnect_attempts(1);
  22647. sse.start_async();
  22648. for (int i = 0; i < 500 && messages < 1000; i++) {
  22649. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22650. }
  22651. sse.stop();
  22652. EXPECT_GE(messages.load(), 1000);
  22653. EXPECT_FALSE(too_large);
  22654. }
  22655. // Test: on_message callback
  22656. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22657. // Endpoint that sends multiple events then closes
  22658. server_->Get("/multi-event", [](const Request &, Response &res) {
  22659. res.set_chunked_content_provider(
  22660. "text/event-stream", [](size_t offset, DataSink &sink) {
  22661. if (offset == 0) {
  22662. std::string events = "data: message1\n\ndata: message2\n\n";
  22663. sink.write(events.data(), events.size());
  22664. }
  22665. return false;
  22666. });
  22667. });
  22668. Client client("localhost", get_port());
  22669. sse::SSEClient sse(client, "/multi-event");
  22670. std::vector<std::string> received_messages;
  22671. std::mutex messages_mutex;
  22672. sse.on_message([&](const sse::SSEMessage &msg) {
  22673. std::lock_guard<std::mutex> lock(messages_mutex);
  22674. received_messages.push_back(msg.data);
  22675. });
  22676. sse.set_reconnect_interval(100);
  22677. sse.set_max_reconnect_attempts(1);
  22678. sse.start_async();
  22679. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22680. sse.stop();
  22681. std::lock_guard<std::mutex> lock(messages_mutex);
  22682. EXPECT_GE(received_messages.size(), 2u);
  22683. if (received_messages.size() >= 2) {
  22684. EXPECT_EQ(received_messages[0], "message1");
  22685. EXPECT_EQ(received_messages[1], "message2");
  22686. }
  22687. }
  22688. // Test: on_event for specific types
  22689. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22690. Client client("localhost", get_port());
  22691. sse::SSEClient sse(client, "/custom-events");
  22692. std::atomic<bool> update_received{false};
  22693. std::atomic<bool> delete_received{false};
  22694. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22695. if (msg.data == "updated") { update_received.store(true); }
  22696. });
  22697. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22698. if (msg.data == "deleted") { delete_received.store(true); }
  22699. });
  22700. sse.set_max_reconnect_attempts(1);
  22701. sse.start_async();
  22702. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22703. sse.stop();
  22704. EXPECT_TRUE(update_received.load());
  22705. EXPECT_TRUE(delete_received.load());
  22706. }
  22707. // Test: on_error callback on connection failure
  22708. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22709. // Connect to a non-existent port
  22710. Client client("localhost", 59999);
  22711. sse::SSEClient sse(client, "/events");
  22712. std::atomic<bool> error_called{false};
  22713. Error received_error = Error::Success;
  22714. sse.on_error([&](Error err) {
  22715. error_called.store(true);
  22716. received_error = err;
  22717. });
  22718. sse.set_reconnect_interval(50);
  22719. sse.set_max_reconnect_attempts(1);
  22720. sse.start_async();
  22721. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22722. sse.stop();
  22723. EXPECT_TRUE(error_called.load());
  22724. EXPECT_NE(received_error, Error::Success);
  22725. }
  22726. // Test: Last-Event-ID header sent on reconnect
  22727. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22728. // Endpoint that sends event with ID
  22729. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22730. res.set_chunked_content_provider(
  22731. "text/event-stream", [](size_t offset, DataSink &sink) {
  22732. if (offset == 0) {
  22733. std::string event = "id: evt-123\ndata: test\n\n";
  22734. sink.write(event.data(), event.size());
  22735. }
  22736. return false;
  22737. });
  22738. });
  22739. Client client("localhost", get_port());
  22740. sse::SSEClient sse(client, "/event-with-id");
  22741. std::atomic<bool> id_received{false};
  22742. sse.on_message([&](const sse::SSEMessage &msg) {
  22743. if (!msg.id.empty()) { id_received.store(true); }
  22744. });
  22745. sse.set_reconnect_interval(100);
  22746. sse.set_max_reconnect_attempts(1);
  22747. sse.start_async();
  22748. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22749. sse.stop();
  22750. EXPECT_TRUE(id_received.load());
  22751. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22752. }
  22753. // Test: last_event_id() read from another thread while start_async() runs
  22754. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22755. // Ids of every length up to 200, so the stored id keeps changing size
  22756. server_->Get("/many-ids", [](const Request &, Response &res) {
  22757. res.set_chunked_content_provider(
  22758. "text/event-stream", [](size_t offset, DataSink &sink) {
  22759. if (offset == 0) {
  22760. std::string events;
  22761. for (size_t i = 0; i < 2000; i++) {
  22762. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22763. events += "data: x\n\n";
  22764. }
  22765. events += "id: end\ndata: x\n\n";
  22766. sink.write(events.data(), events.size());
  22767. }
  22768. return false;
  22769. });
  22770. });
  22771. Client client("localhost", get_port());
  22772. sse::SSEClient sse(client, "/many-ids");
  22773. // Wait out the rest of the test rather than replay the stream
  22774. sse.set_reconnect_interval(10000);
  22775. sse.set_max_reconnect_attempts(1);
  22776. sse.start_async();
  22777. auto well_formed = true;
  22778. std::string id;
  22779. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22780. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22781. id = sse.last_event_id();
  22782. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22783. well_formed = false;
  22784. }
  22785. }
  22786. sse.stop();
  22787. EXPECT_TRUE(well_formed);
  22788. EXPECT_EQ(sse.last_event_id(), "end");
  22789. }
  22790. // Test: Manual stop
  22791. TEST_F(SSEIntegrationTest, ManualStop) {
  22792. // Endpoint that sends one event and stays open briefly. The server outlives
  22793. // this test body, so the provider uses the fixture's flag, not a local.
  22794. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22795. res.set_chunked_content_provider(
  22796. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22797. if (offset == 0) {
  22798. std::string event = "data: connected\n\n";
  22799. sink.write(event.data(), event.size());
  22800. }
  22801. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22802. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22803. }
  22804. return false;
  22805. });
  22806. });
  22807. Client client("localhost", get_port());
  22808. sse::SSEClient sse(client, "/stay-open");
  22809. std::atomic<bool> connected{false};
  22810. sse.on_open([&connected]() { connected.store(true); });
  22811. sse.set_reconnect_interval(100);
  22812. sse.set_max_reconnect_attempts(1);
  22813. sse.start_async();
  22814. // Wait for connection to establish
  22815. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22816. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22817. }
  22818. EXPECT_TRUE(connected.load());
  22819. EXPECT_TRUE(sse.is_connected());
  22820. // Signal handler to stop
  22821. stop_server_.store(true);
  22822. // Stop SSE client
  22823. sse.stop();
  22824. EXPECT_FALSE(sse.is_connected());
  22825. }
  22826. // Sends one event, then nothing until stop is set
  22827. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22828. return [&stop](const Request &, Response &res) {
  22829. res.set_chunked_content_provider(
  22830. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22831. if (offset == 0) {
  22832. std::string event = "data: hello\n\n";
  22833. sink.write(event.data(), event.size());
  22834. }
  22835. while (!stop.load()) {
  22836. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22837. }
  22838. return false;
  22839. });
  22840. };
  22841. }
  22842. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22843. static void check_stop_interrupts_blocked_read(Client &client) {
  22844. client.set_read_timeout(30, 0);
  22845. for (auto by_destructor : {false, true}) {
  22846. std::atomic<bool> received{false};
  22847. std::chrono::steady_clock::time_point start;
  22848. {
  22849. sse::SSEClient sse(client, "/idle-stream");
  22850. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22851. sse.start_async();
  22852. for (int i = 0; i < 500 && !received.load(); ++i) {
  22853. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22854. }
  22855. ASSERT_TRUE(received.load());
  22856. // Let the client block in the next read
  22857. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22858. start = std::chrono::steady_clock::now();
  22859. if (!by_destructor) { sse.stop(); }
  22860. }
  22861. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22862. std::chrono::seconds(2));
  22863. }
  22864. }
  22865. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22866. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22867. Client client("localhost", get_port());
  22868. check_stop_interrupts_blocked_read(client);
  22869. }
  22870. #ifdef CPPHTTPLIB_SSL_ENABLED
  22871. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22873. std::atomic<bool> done{false};
  22874. svr.Get("/idle-stream", idle_event_stream(done));
  22875. auto port = svr.bind_to_any_port(HOST);
  22876. std::thread t([&] { svr.listen_after_bind(); });
  22877. auto se = detail::scope_exit([&] {
  22878. done.store(true);
  22879. svr.stop();
  22880. t.join();
  22881. });
  22882. svr.wait_until_ready();
  22883. Client client("https://localhost:" + std::to_string(port));
  22884. client.enable_server_certificate_verification(false);
  22885. check_stop_interrupts_blocked_read(client);
  22886. }
  22887. #endif
  22888. // Test: SSEClient with custom headers
  22889. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22890. // Setup a server endpoint that checks for custom header
  22891. std::atomic<bool> header_received{false};
  22892. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22893. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22894. header_received.store(true);
  22895. }
  22896. res.set_chunked_content_provider("text/event-stream",
  22897. [](size_t, DataSink &) { return false; });
  22898. });
  22899. Client client("localhost", get_port());
  22900. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22901. sse::SSEClient sse(client, "/header-check", headers);
  22902. sse.set_max_reconnect_attempts(1);
  22903. sse.start_async();
  22904. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22905. sse.stop();
  22906. EXPECT_TRUE(header_received.load());
  22907. }
  22908. // Test: Reconnect interval configuration
  22909. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22910. Client client("localhost", get_port());
  22911. sse::SSEClient sse(client, "/events");
  22912. auto &result = sse.set_reconnect_interval(500);
  22913. // Builder pattern should return reference to self
  22914. EXPECT_EQ(&result, &sse);
  22915. }
  22916. // Test: Max reconnect attempts
  22917. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22918. // Connect to non-existent port to force reconnects
  22919. Client client("localhost", 59998);
  22920. sse::SSEClient sse(client, "/events");
  22921. std::atomic<int> error_count{0};
  22922. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22923. sse.set_reconnect_interval(50);
  22924. sse.set_max_reconnect_attempts(2);
  22925. auto start = std::chrono::steady_clock::now();
  22926. sse.start(); // Blocking call
  22927. auto end = std::chrono::steady_clock::now();
  22928. // Should have stopped after 2 failed attempts
  22929. EXPECT_GE(error_count.load(), 2);
  22930. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22931. auto duration =
  22932. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22933. #ifdef _WIN32
  22934. // Windows is much slower for socket connection failures
  22935. EXPECT_LT(duration.count(), 7000);
  22936. #else
  22937. EXPECT_LT(duration.count(), 1000);
  22938. #endif
  22939. }
  22940. // Test: Multi-line data in integration
  22941. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22942. // Endpoint with multi-line data
  22943. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22944. res.set_chunked_content_provider(
  22945. "text/event-stream", [](size_t offset, DataSink &sink) {
  22946. if (offset == 0) {
  22947. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22948. sink.write(event.data(), event.size());
  22949. }
  22950. return false;
  22951. });
  22952. });
  22953. Client client("localhost", get_port());
  22954. sse::SSEClient sse(client, "/multiline-data");
  22955. std::string received_data;
  22956. std::mutex data_mutex;
  22957. sse.on_message([&](const sse::SSEMessage &msg) {
  22958. std::lock_guard<std::mutex> lock(data_mutex);
  22959. received_data = msg.data;
  22960. });
  22961. sse.set_reconnect_interval(100);
  22962. sse.set_max_reconnect_attempts(1);
  22963. sse.start_async();
  22964. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22965. sse.stop();
  22966. std::lock_guard<std::mutex> lock(data_mutex);
  22967. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22968. }
  22969. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22970. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22971. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22972. DataSink &sink) {
  22973. if (offset == 0) {
  22974. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22975. sink.write(events.data(), events.size());
  22976. }
  22977. return false;
  22978. });
  22979. });
  22980. Client client("localhost", get_port());
  22981. sse::SSEClient sse(client, "/empty-data-lines");
  22982. std::mutex mutex;
  22983. std::condition_variable cv;
  22984. std::vector<std::string> received;
  22985. sse.on_message([&](const sse::SSEMessage &msg) {
  22986. std::lock_guard<std::mutex> lock(mutex);
  22987. received.push_back(msg.data);
  22988. cv.notify_all();
  22989. });
  22990. sse.set_max_reconnect_attempts(1);
  22991. sse.start_async();
  22992. {
  22993. std::unique_lock<std::mutex> lock(mutex);
  22994. cv.wait_for(lock, std::chrono::seconds(2),
  22995. [&] { return received.size() >= 3; });
  22996. }
  22997. sse.stop();
  22998. ASSERT_GE(received.size(), 3u);
  22999. EXPECT_EQ(received[0], "");
  23000. EXPECT_EQ(received[1], "\nhello");
  23001. EXPECT_EQ(received[2], "");
  23002. }
  23003. // Test: Auto-reconnect after server disconnection
  23004. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23005. std::atomic<int> connection_count{0};
  23006. std::atomic<int> message_count{0};
  23007. // Endpoint that sends one event and closes, forcing reconnect
  23008. server_->Get("/reconnect-test",
  23009. [&connection_count](const Request &, Response &res) {
  23010. connection_count.fetch_add(1);
  23011. res.set_chunked_content_provider(
  23012. "text/event-stream", [](size_t offset, DataSink &sink) {
  23013. if (offset == 0) {
  23014. std::string event = "data: hello\n\n";
  23015. sink.write(event.data(), event.size());
  23016. }
  23017. return false; // Close connection after sending
  23018. });
  23019. });
  23020. Client client("localhost", get_port());
  23021. sse::SSEClient sse(client, "/reconnect-test");
  23022. sse.on_message([&message_count](const sse::SSEMessage &) {
  23023. message_count.fetch_add(1);
  23024. });
  23025. sse.set_reconnect_interval(100);
  23026. sse.set_max_reconnect_attempts(3);
  23027. sse.start_async();
  23028. // Wait long enough for multiple reconnects
  23029. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23030. sse.stop();
  23031. // Should have connected multiple times (initial + reconnects)
  23032. EXPECT_GE(connection_count.load(), 2);
  23033. // Should have received messages from multiple connections
  23034. EXPECT_GE(message_count.load(), 2);
  23035. }
  23036. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23037. std::atomic<int> connection_count{0};
  23038. // Neither Content-Length nor chunked: the close ends the stream
  23039. server_->Get("/close-delimited",
  23040. [&connection_count](const Request &, Response &res) {
  23041. connection_count.fetch_add(1);
  23042. res.set_content_provider(
  23043. "text/event-stream", [](size_t offset, DataSink &sink) {
  23044. if (offset == 0) {
  23045. std::string event = "data: hello\n\n";
  23046. sink.write(event.data(), event.size());
  23047. } else {
  23048. sink.done();
  23049. }
  23050. return true;
  23051. });
  23052. });
  23053. Client client("localhost", get_port());
  23054. sse::SSEClient sse(client, "/close-delimited");
  23055. std::atomic<int> error_count{0};
  23056. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23057. sse.set_reconnect_interval(100);
  23058. sse.start_async();
  23059. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23061. }
  23062. sse.stop();
  23063. // Reconnects as after any end of the stream, but reports no error
  23064. EXPECT_GE(connection_count.load(), 2);
  23065. EXPECT_EQ(0, error_count.load());
  23066. }
  23067. // Test: A retry field that is not all ASCII digits is ignored
  23068. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  23069. std::atomic<int> connection_count{0};
  23070. server_->Get("/bad-retry",
  23071. [&connection_count](const Request &, Response &res) {
  23072. connection_count.fetch_add(1);
  23073. res.set_chunked_content_provider(
  23074. "text/event-stream", [](size_t offset, DataSink &sink) {
  23075. if (offset == 0) {
  23076. std::string event = "retry: -1\ndata: hello\n\n";
  23077. sink.write(event.data(), event.size());
  23078. }
  23079. return false;
  23080. });
  23081. });
  23082. Client client("localhost", get_port());
  23083. sse::SSEClient sse(client, "/bad-retry");
  23084. sse.set_reconnect_interval(10000);
  23085. sse.start_async();
  23086. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23087. sse.stop();
  23088. EXPECT_EQ(connection_count.load(), 1);
  23089. }
  23090. // Test: A retry field of all ASCII digits sets the reconnection time
  23091. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23092. std::mutex mutex;
  23093. std::condition_variable cv;
  23094. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23095. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23096. {
  23097. std::lock_guard<std::mutex> lock(mutex);
  23098. connected_at.push_back(std::chrono::steady_clock::now());
  23099. cv.notify_all();
  23100. }
  23101. res.set_chunked_content_provider(
  23102. "text/event-stream", [](size_t offset, DataSink &sink) {
  23103. if (offset == 0) {
  23104. std::string event = "retry: 0\ndata: hello\n\n";
  23105. sink.write(event.data(), event.size());
  23106. }
  23107. return false;
  23108. });
  23109. });
  23110. Client client("localhost", get_port());
  23111. sse::SSEClient sse(client, "/zero-retry");
  23112. sse.set_reconnect_interval(10000);
  23113. sse.start_async();
  23114. {
  23115. std::unique_lock<std::mutex> lock(mutex);
  23116. cv.wait_for(lock, std::chrono::seconds(5),
  23117. [&] { return connected_at.size() >= 2; });
  23118. }
  23119. sse.stop();
  23120. // The server-supplied interval is applied, but never below 100ms, so
  23121. // "retry: 0" does not cause a busy reconnect loop
  23122. std::lock_guard<std::mutex> lock(mutex);
  23123. ASSERT_GE(connected_at.size(), 2u);
  23124. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23125. connected_at[1] - connected_at[0])
  23126. .count();
  23127. EXPECT_GE(interval_ms, 100);
  23128. }
  23129. // Test: Last-Event-ID sent on reconnect
  23130. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23131. std::atomic<int> connection_count{0};
  23132. std::vector<std::string> received_last_event_ids;
  23133. std::mutex id_mutex;
  23134. // Endpoint that checks Last-Event-ID header and sends event with ID
  23135. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23136. int conn = connection_count.fetch_add(1);
  23137. // Capture the Last-Event-ID header from each connection
  23138. {
  23139. std::lock_guard<std::mutex> lock(id_mutex);
  23140. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23141. }
  23142. res.set_chunked_content_provider(
  23143. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23144. if (offset == 0) {
  23145. std::string event =
  23146. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23147. sink.write(event.data(), event.size());
  23148. }
  23149. return false;
  23150. });
  23151. });
  23152. Client client("localhost", get_port());
  23153. sse::SSEClient sse(client, "/reconnect-with-id");
  23154. sse.set_reconnect_interval(100);
  23155. sse.set_max_reconnect_attempts(3);
  23156. sse.start_async();
  23157. // Wait for at least 2 connections
  23158. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23159. sse.stop();
  23160. // Verify behavior
  23161. std::lock_guard<std::mutex> lock(id_mutex);
  23162. EXPECT_GE(received_last_event_ids.size(), 2u);
  23163. // First connection should have no Last-Event-ID
  23164. if (!received_last_event_ids.empty()) {
  23165. EXPECT_EQ(received_last_event_ids[0], "");
  23166. }
  23167. // Second connection should have Last-Event-ID from first connection
  23168. if (received_last_event_ids.size() >= 2) {
  23169. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23170. }
  23171. }
  23172. // Test: set_headers updates headers used on reconnect
  23173. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23174. std::vector<std::string> received_tokens;
  23175. std::mutex token_mutex;
  23176. // Endpoint that captures Authorization header
  23177. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23178. {
  23179. std::lock_guard<std::mutex> lock(token_mutex);
  23180. received_tokens.push_back(req.get_header_value("Authorization"));
  23181. }
  23182. res.set_chunked_content_provider(
  23183. "text/event-stream", [](size_t offset, DataSink &sink) {
  23184. if (offset == 0) {
  23185. std::string event = "data: hello\n\n";
  23186. sink.write(event.data(), event.size());
  23187. }
  23188. return false; // Close connection to trigger reconnect
  23189. });
  23190. });
  23191. Client client("localhost", get_port());
  23192. Headers headers = {{"Authorization", "Bearer old-token"}};
  23193. sse::SSEClient sse(client, "/auth-check", headers);
  23194. // Update headers on each successful connection
  23195. sse.on_open(
  23196. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23197. sse.set_reconnect_interval(100);
  23198. sse.set_max_reconnect_attempts(3);
  23199. sse.start_async();
  23200. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23201. sse.stop();
  23202. std::lock_guard<std::mutex> lock(token_mutex);
  23203. ASSERT_GE(received_tokens.size(), 2u);
  23204. // First connection uses original header
  23205. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23206. // Second connection uses updated header from set_headers
  23207. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23208. }
  23209. // Test: 401 allows reconnection (so on_error can refresh headers)
  23210. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23211. std::atomic<int> connection_count{0};
  23212. // Endpoint: returns 401 on first attempt, 200 on second
  23213. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23214. int conn = connection_count.fetch_add(1);
  23215. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23216. res.status = StatusCode::Unauthorized_401;
  23217. res.set_content("Unauthorized", "text/plain");
  23218. return;
  23219. }
  23220. res.set_chunked_content_provider(
  23221. "text/event-stream", [](size_t offset, DataSink &sink) {
  23222. if (offset == 0) {
  23223. std::string event = "data: authenticated\n\n";
  23224. sink.write(event.data(), event.size());
  23225. }
  23226. return false;
  23227. });
  23228. });
  23229. Client client("localhost", get_port());
  23230. Headers headers = {{"Authorization", "Bearer expired"}};
  23231. sse::SSEClient sse(client, "/auth-retry", headers);
  23232. std::atomic<bool> message_received{false};
  23233. // Refresh token on error
  23234. sse.on_error(
  23235. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23236. sse.on_message([&](const sse::SSEMessage &msg) {
  23237. if (msg.data == "authenticated") { message_received.store(true); }
  23238. });
  23239. sse.set_reconnect_interval(100);
  23240. sse.set_max_reconnect_attempts(3);
  23241. sse.start_async();
  23242. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23243. sse.stop();
  23244. // Should have reconnected after 401 and succeeded with new token
  23245. EXPECT_GE(connection_count.load(), 2);
  23246. EXPECT_TRUE(message_received.load());
  23247. }
  23248. TEST(Issue2318Test, EmptyHostString) {
  23249. {
  23250. httplib::Client cli_empty("", PORT);
  23251. auto res = cli_empty.Get("/");
  23252. ASSERT_FALSE(res);
  23253. EXPECT_EQ(httplib::Error::Connection, res.error());
  23254. }
  23255. {
  23256. httplib::Client cli(" ", PORT);
  23257. auto res = cli.Get("/");
  23258. ASSERT_FALSE(res);
  23259. EXPECT_EQ(httplib::Error::Connection, res.error());
  23260. }
  23261. }
  23262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23263. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23264. Server svr;
  23265. // Set a small payload limit (1KB)
  23266. svr.set_payload_max_length(1024);
  23267. svr.Post("/test", [&](const Request &req, Response &res) {
  23268. res.set_content("Body size: " + std::to_string(req.body.size()),
  23269. "text/plain");
  23270. });
  23271. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23272. auto se = detail::scope_exit([&] {
  23273. svr.stop();
  23274. listen_thread.join();
  23275. });
  23276. svr.wait_until_ready();
  23277. // Create data that compresses well but exceeds limit when decompressed
  23278. // 8KB of repeated null bytes compresses to a very small size
  23279. std::string original_data(8 * 1024, '\0');
  23280. // Compress the data using gzip
  23281. std::string compressed_data;
  23282. detail::gzip_compressor compressor;
  23283. compressor.compress(original_data.data(), original_data.size(), true,
  23284. [&](const char *data, size_t size) {
  23285. compressed_data.append(data, size);
  23286. return true;
  23287. });
  23288. // Verify compression worked (compressed should be much smaller)
  23289. ASSERT_LT(compressed_data.size(), original_data.size());
  23290. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23291. // Send compressed data with Content-Encoding: gzip
  23292. Client cli(HOST, PORT);
  23293. Headers headers = {{"Content-Encoding", "gzip"}};
  23294. auto res =
  23295. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23296. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23298. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23299. }
  23300. #endif
  23301. // ============================================================================
  23302. // OpenSSL-Specific Tests
  23303. // ============================================================================
  23304. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23305. X509 *readCertificate(const std::string &strFileName) {
  23306. std::ifstream inStream(strFileName);
  23307. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23308. std::istreambuf_iterator<char>());
  23309. if (strCertPEM.empty()) return (nullptr);
  23310. BIO *pbCert = BIO_new(BIO_s_mem());
  23311. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23312. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23313. BIO_free(pbCert);
  23314. return (pCert);
  23315. }
  23316. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23317. std::ifstream inStream(strFileName);
  23318. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23319. std::istreambuf_iterator<char>());
  23320. if (strPrivateKeyPEM.empty()) return (nullptr);
  23321. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23322. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23323. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23324. BIO_free(pbPrivKey);
  23325. return (pPrivateKey);
  23326. }
  23327. TEST(BindServerTest, UpdateCerts) {
  23328. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23329. int port = svr.bind_to_any_port("0.0.0.0");
  23330. ASSERT_TRUE(svr.is_valid());
  23331. ASSERT_TRUE(port > 0);
  23332. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23333. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23334. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23335. ASSERT_TRUE(cert != nullptr);
  23336. ASSERT_TRUE(ca_cert != nullptr);
  23337. ASSERT_TRUE(key != nullptr);
  23338. X509_STORE *cert_store = X509_STORE_new();
  23339. X509_STORE_add_cert(cert_store, ca_cert);
  23340. // svr.update_certs(cert, key, cert_store); // deprecated
  23341. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23342. CLIENT_CA_CERT_FILE);
  23343. ASSERT_TRUE(svr.is_valid());
  23344. svr.stop();
  23345. X509_STORE_free(cert_store);
  23346. X509_free(cert);
  23347. X509_free(ca_cert);
  23348. EVP_PKEY_free(key);
  23349. }
  23350. // Test that update_certs() updates client CA list correctly
  23351. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23352. // Start with file-based constructor
  23353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23354. ASSERT_TRUE(svr.is_valid());
  23355. // Initially no client CA list should be set
  23356. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23357. ASSERT_TRUE(ssl_ctx != nullptr);
  23358. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23359. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23360. // Now update with client CA (PEM string)
  23361. std::string cert_pem, key_pem, ca_pem;
  23362. read_file(SERVER_CERT_FILE, cert_pem);
  23363. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23364. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23365. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23366. ASSERT_TRUE(svr.is_valid());
  23367. // Now client CA list should be set
  23368. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23369. ASSERT_TRUE(ca_list_after != nullptr);
  23370. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23371. }
  23372. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23373. // Test that the file-path SSLServer constructor properly sets the client CA
  23374. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23376. ASSERT_TRUE(svr.is_valid());
  23377. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23378. ASSERT_TRUE(ssl_ctx != nullptr);
  23379. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23380. ASSERT_TRUE(ca_list != nullptr);
  23381. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23382. }
  23383. #endif
  23384. // ============================================================================
  23385. // MbedTLS-Specific Tests
  23386. // ============================================================================
  23387. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23388. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23389. using namespace httplib::tls;
  23390. // Track if callback was invoked
  23391. bool callback_invoked = false;
  23392. // The callback receives void* ctx which is actually MbedTlsContext*
  23393. // We can access the mbedtls_ssl_config via the context
  23394. auto setup_callback = [&callback_invoked](void *ctx) {
  23395. callback_invoked = true;
  23396. // Cast to MbedTlsContext* to access the ssl config
  23397. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23398. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23399. // Use static variables to hold certificate data (simplified for test)
  23400. static mbedtls_x509_crt own_cert;
  23401. static mbedtls_pk_context own_key;
  23402. static mbedtls_x509_crt ca_chain;
  23403. static bool initialized = false;
  23404. if (!initialized) {
  23405. mbedtls_x509_crt_init(&own_cert);
  23406. mbedtls_pk_init(&own_key);
  23407. mbedtls_x509_crt_init(&ca_chain);
  23408. // Load server certificate
  23409. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23410. return false;
  23411. }
  23412. // Load server private key.
  23413. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23414. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23415. #if MBEDTLS_VERSION_MAJOR == 3
  23416. ,
  23417. mbedtls_ctr_drbg_random, nullptr
  23418. #endif
  23419. ) != 0) {
  23420. return false;
  23421. }
  23422. // Load CA chain for client verification
  23423. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23424. return false;
  23425. }
  23426. initialized = true;
  23427. }
  23428. // Configure the SSL config
  23429. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23430. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23431. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23432. // Set minimum TLS version using mbedTLS native API
  23433. #if MBEDTLS_VERSION_MAJOR >= 3
  23434. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23435. #else
  23436. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23437. MBEDTLS_SSL_MINOR_VERSION_3);
  23438. #endif
  23439. return true;
  23440. };
  23441. SSLServer svr(setup_callback);
  23442. ASSERT_TRUE(svr.is_valid());
  23443. ASSERT_TRUE(callback_invoked);
  23444. svr.Get("/test", [&](const Request &req, Response &res) {
  23445. res.set_content("test", "text/plain");
  23446. auto cert = req.peer_cert();
  23447. ASSERT_TRUE(static_cast<bool>(cert));
  23448. auto common_name = cert.subject_cn();
  23449. EXPECT_EQ("Common Name", common_name);
  23450. });
  23451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23452. auto se = detail::scope_exit([&] {
  23453. svr.stop();
  23454. t.join();
  23455. ASSERT_FALSE(svr.is_running());
  23456. });
  23457. svr.wait_until_ready();
  23458. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23459. cli.enable_server_certificate_verification(false);
  23460. cli.set_connection_timeout(30);
  23461. auto res = cli.Get("/test");
  23462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23463. ASSERT_EQ(StatusCode::OK_200, res->status);
  23464. }
  23465. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23466. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23467. // keep-alive SSL session, which reads through that config in
  23468. // mbedtls_ssl_close_notify.
  23469. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23471. ASSERT_TRUE(svr.is_valid());
  23472. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23473. res.set_content("test", "text/plain");
  23474. });
  23475. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23476. auto se = detail::scope_exit([&] {
  23477. svr.stop();
  23478. t.join();
  23479. ASSERT_FALSE(svr.is_running());
  23480. });
  23481. svr.wait_until_ready();
  23482. {
  23483. SSLClient cli(HOST, PORT);
  23484. cli.enable_server_certificate_verification(false);
  23485. cli.set_keep_alive(true);
  23486. auto res = cli.Get("/test");
  23487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23488. ASSERT_EQ(StatusCode::OK_200, res->status);
  23489. // cli is destructed here with the keep-alive SSL session still open.
  23490. }
  23491. }
  23492. #endif
  23493. // WebSocket Tests
  23494. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23495. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23496. // defining the meaning of these bits has been negotiated.
  23497. auto make_frame = [](uint8_t first_byte) {
  23498. std::string frame;
  23499. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23500. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23501. frame += "Hello";
  23502. return frame;
  23503. };
  23504. // RSV1 set (0x40)
  23505. {
  23506. detail::BufferStream strm;
  23507. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23508. ws::Opcode opcode;
  23509. std::string payload;
  23510. bool fin;
  23511. EXPECT_EQ(
  23512. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23513. ws::impl::FrameRead::Fail);
  23514. }
  23515. // RSV2 set (0x20)
  23516. {
  23517. detail::BufferStream strm;
  23518. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23519. ws::Opcode opcode;
  23520. std::string payload;
  23521. bool fin;
  23522. EXPECT_EQ(
  23523. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23524. ws::impl::FrameRead::Fail);
  23525. }
  23526. // RSV3 set (0x10)
  23527. {
  23528. detail::BufferStream strm;
  23529. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23530. ws::Opcode opcode;
  23531. std::string payload;
  23532. bool fin;
  23533. EXPECT_EQ(
  23534. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23535. ws::impl::FrameRead::Fail);
  23536. }
  23537. // No RSV bits set - should succeed
  23538. {
  23539. detail::BufferStream strm;
  23540. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23541. ws::Opcode opcode;
  23542. std::string payload;
  23543. bool fin;
  23544. EXPECT_EQ(
  23545. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23546. ws::impl::FrameRead::Ok);
  23547. EXPECT_EQ(ws::Opcode::Text, opcode);
  23548. EXPECT_EQ("Hello", payload);
  23549. EXPECT_TRUE(fin);
  23550. }
  23551. }
  23552. TEST(WebSocketTest, ControlFrameValidation) {
  23553. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23554. // payload length <= 125.
  23555. // Ping with FIN=0 - must be rejected
  23556. {
  23557. detail::BufferStream strm;
  23558. std::string frame;
  23559. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23560. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23561. strm.write(frame.data(), frame.size());
  23562. ws::Opcode opcode;
  23563. std::string payload;
  23564. bool fin;
  23565. EXPECT_EQ(
  23566. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23567. ws::impl::FrameRead::Fail);
  23568. }
  23569. // Close with FIN=0 - must be rejected
  23570. {
  23571. detail::BufferStream strm;
  23572. std::string frame;
  23573. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23574. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23575. strm.write(frame.data(), frame.size());
  23576. ws::Opcode opcode;
  23577. std::string payload;
  23578. bool fin;
  23579. EXPECT_EQ(
  23580. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23581. ws::impl::FrameRead::Fail);
  23582. }
  23583. // Ping with payload_len=126 (extended length) - must be rejected
  23584. {
  23585. detail::BufferStream strm;
  23586. std::string frame;
  23587. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23588. frame += static_cast<char>(126); // payload_len=126 (>125)
  23589. frame += static_cast<char>(0x00); // extended length high byte
  23590. frame += static_cast<char>(126); // extended length low byte
  23591. frame += std::string(126, 'x');
  23592. strm.write(frame.data(), frame.size());
  23593. ws::Opcode opcode;
  23594. std::string payload;
  23595. bool fin;
  23596. EXPECT_EQ(
  23597. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23598. ws::impl::FrameRead::Fail);
  23599. }
  23600. // Ping with FIN=1 and payload_len=125 - should succeed
  23601. {
  23602. detail::BufferStream strm;
  23603. std::string frame;
  23604. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23605. frame += static_cast<char>(125); // payload_len=125
  23606. frame += std::string(125, 'x');
  23607. strm.write(frame.data(), frame.size());
  23608. ws::Opcode opcode;
  23609. std::string payload;
  23610. bool fin;
  23611. EXPECT_EQ(
  23612. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23613. ws::impl::FrameRead::Ok);
  23614. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23615. EXPECT_EQ(125u, payload.size());
  23616. EXPECT_TRUE(fin);
  23617. }
  23618. }
  23619. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23620. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23621. // length MUST be 0.
  23622. // MSB set - must be rejected
  23623. {
  23624. detail::BufferStream strm;
  23625. std::string frame;
  23626. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23627. frame += static_cast<char>(127); // 64-bit extended length
  23628. frame += static_cast<char>(0x80); // MSB set (invalid)
  23629. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23630. strm.write(frame.data(), frame.size());
  23631. ws::Opcode opcode;
  23632. std::string payload;
  23633. bool fin;
  23634. EXPECT_EQ(
  23635. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23636. ws::impl::FrameRead::Fail);
  23637. }
  23638. // MSB clear - should pass length parsing (will be rejected by max_len,
  23639. // but that's a different check; use a small length to verify)
  23640. {
  23641. detail::BufferStream strm;
  23642. std::string frame;
  23643. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23644. frame += static_cast<char>(127); // 64-bit extended length
  23645. frame += std::string(7, '\0'); // high bytes = 0
  23646. frame += static_cast<char>(0x03); // length = 3
  23647. frame += "abc";
  23648. strm.write(frame.data(), frame.size());
  23649. ws::Opcode opcode;
  23650. std::string payload;
  23651. bool fin;
  23652. EXPECT_EQ(
  23653. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23654. ws::impl::FrameRead::Ok);
  23655. EXPECT_EQ(ws::Opcode::Text, opcode);
  23656. EXPECT_EQ("abc", payload);
  23657. }
  23658. }
  23659. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23660. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23661. // Valid UTF-8
  23662. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23663. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23664. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23665. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23666. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23667. // Invalid UTF-8
  23668. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23669. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23670. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23671. EXPECT_FALSE(
  23672. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23673. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23674. }
  23675. TEST(WebSocketTest, ConnectAndDisconnect) {
  23676. Server svr;
  23677. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23678. std::string msg;
  23679. while (ws.read(msg)) {}
  23680. });
  23681. auto port = svr.bind_to_any_port(HOST);
  23682. std::thread t([&]() { svr.listen_after_bind(); });
  23683. svr.wait_until_ready();
  23684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23685. auto res = client.connect();
  23686. ASSERT_TRUE(res);
  23687. EXPECT_EQ(Error::Success, res.error());
  23688. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23689. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23690. EXPECT_TRUE(client.is_open());
  23691. client.close();
  23692. EXPECT_FALSE(client.is_open());
  23693. svr.stop();
  23694. t.join();
  23695. }
  23696. TEST(WebSocketTest, ValidURL) {
  23697. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23698. EXPECT_TRUE(ws1.is_valid());
  23699. ws::WebSocketClient ws2("ws://example.com/path");
  23700. EXPECT_TRUE(ws2.is_valid());
  23701. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23702. EXPECT_TRUE(ws3.is_valid());
  23703. #ifdef CPPHTTPLIB_SSL_ENABLED
  23704. ws::WebSocketClient wss1("wss://example.com/path");
  23705. EXPECT_TRUE(wss1.is_valid());
  23706. ws::WebSocketClient wss2("wss://example.com:443/path");
  23707. EXPECT_TRUE(wss2.is_valid());
  23708. #endif
  23709. }
  23710. TEST(WebSocketTest, InvalidURL) {
  23711. // No scheme
  23712. ws::WebSocketClient ws1("localhost:8080/path");
  23713. EXPECT_FALSE(ws1.is_valid());
  23714. // No path
  23715. ws::WebSocketClient ws2("ws://localhost:8080");
  23716. EXPECT_FALSE(ws2.is_valid());
  23717. // Empty string
  23718. ws::WebSocketClient ws3("");
  23719. EXPECT_FALSE(ws3.is_valid());
  23720. // Missing host
  23721. ws::WebSocketClient ws4("ws://:8080/path");
  23722. EXPECT_FALSE(ws4.is_valid());
  23723. // Port number overflow — should not crash
  23724. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23725. EXPECT_FALSE(ws5.is_valid());
  23726. // Port out of range
  23727. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23728. EXPECT_FALSE(ws6.is_valid());
  23729. }
  23730. TEST(WebSocketTest, UnsupportedScheme) {
  23731. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23732. ws::WebSocketClient ws1("http://localhost:8080/path");
  23733. EXPECT_FALSE(ws1.is_valid());
  23734. ws::WebSocketClient ws2("https://localhost:8080/path");
  23735. EXPECT_FALSE(ws2.is_valid());
  23736. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23737. EXPECT_FALSE(ws3.is_valid());
  23738. #else
  23739. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23740. std::invalid_argument);
  23741. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23742. std::invalid_argument);
  23743. #endif
  23744. }
  23745. TEST(WebSocketTest, ConnectWhenInvalid) {
  23746. ws::WebSocketClient ws("not a valid url");
  23747. EXPECT_FALSE(ws.is_valid());
  23748. auto res = ws.connect();
  23749. EXPECT_FALSE(res);
  23750. EXPECT_EQ(Error::Connection, res.error());
  23751. EXPECT_EQ(-1, res.status());
  23752. }
  23753. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23754. // Grab a port that is free, then close it again so nothing listens there
  23755. Server svr;
  23756. auto port = svr.bind_to_any_port(HOST);
  23757. svr.stop();
  23758. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23759. auto res = client.connect();
  23760. ASSERT_FALSE(res);
  23761. EXPECT_EQ(Error::Connection, res.error());
  23762. EXPECT_EQ(-1, res.status());
  23763. }
  23764. TEST(WebSocketTest, DefaultPort) {
  23765. ws::WebSocketClient ws1("ws://example.com/path");
  23766. EXPECT_TRUE(ws1.is_valid());
  23767. // ws:// defaults to port 80 (verified by successful parse)
  23768. #ifdef CPPHTTPLIB_SSL_ENABLED
  23769. ws::WebSocketClient ws2("wss://example.com/path");
  23770. EXPECT_TRUE(ws2.is_valid());
  23771. // wss:// defaults to port 443 (verified by successful parse)
  23772. #endif
  23773. }
  23774. TEST(WebSocketTest, IPv6LiteralAddress) {
  23775. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23776. EXPECT_TRUE(ws1.is_valid());
  23777. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23778. EXPECT_TRUE(ws2.is_valid());
  23779. }
  23780. TEST(WebSocketTest, ComplexPath) {
  23781. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23782. EXPECT_TRUE(ws1.is_valid());
  23783. ws::WebSocketClient ws2("ws://localhost:8080/");
  23784. EXPECT_TRUE(ws2.is_valid());
  23785. }
  23786. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23787. Server svr;
  23788. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23789. std::string msg;
  23790. while (ws.read(msg)) {}
  23791. });
  23792. auto port = svr.bind_to_any_port(HOST);
  23793. std::thread t([&]() { svr.listen_after_bind(); });
  23794. svr.wait_until_ready();
  23795. auto another_host = "example.com";
  23796. auto wrong_ip = "192.0.2.1";
  23797. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23798. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  23799. ASSERT_TRUE(client.connect());
  23800. EXPECT_TRUE(client.is_open());
  23801. client.close();
  23802. svr.stop();
  23803. t.join();
  23804. }
  23805. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23806. Server svr;
  23807. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23808. std::string msg;
  23809. while (ws.read(msg)) {}
  23810. });
  23811. auto port = svr.bind_to_any_port(HOST);
  23812. std::thread t([&]() { svr.listen_after_bind(); });
  23813. svr.wait_until_ready();
  23814. auto wrong_ip = "192.0.2.1";
  23815. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23816. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  23817. client.set_connection_timeout(1);
  23818. client.set_read_timeout(1);
  23819. client.set_write_timeout(1);
  23820. EXPECT_FALSE(client.connect());
  23821. EXPECT_FALSE(client.is_open());
  23822. svr.stop();
  23823. t.join();
  23824. }
  23825. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23826. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23827. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23828. // (RFC 6761) is only a map key and the Host header value.
  23829. auto host = "target.invalid";
  23830. Server svr;
  23831. std::string received_host;
  23832. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23833. received_host = req.get_header_value("Host");
  23834. std::string msg;
  23835. while (ws.read(msg)) {}
  23836. });
  23837. auto port = svr.bind_to_any_port(HOST);
  23838. std::thread t([&]() { svr.listen_after_bind(); });
  23839. // ASSERT_* below returns from the test body, which would leave t joinable
  23840. // and make ~thread call std::terminate.
  23841. auto se = detail::scope_exit([&] {
  23842. svr.stop();
  23843. if (t.joinable()) { t.join(); }
  23844. });
  23845. svr.wait_until_ready();
  23846. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23847. std::to_string(port) + "/ws");
  23848. client.set_direct_hostname_addr_map({{host, HOST}});
  23849. ASSERT_TRUE(client.connect());
  23850. EXPECT_TRUE(client.is_open());
  23851. client.close();
  23852. svr.stop();
  23853. t.join();
  23854. // The mapping only redirects the connection; the identity stays host_.
  23855. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23856. }
  23857. class WebSocketIntegrationTest : public ::testing::Test {
  23858. protected:
  23859. void SetUp() override {
  23860. server_ = httplib::detail::make_unique<Server>();
  23861. setup_server();
  23862. start_server();
  23863. }
  23864. void TearDown() override {
  23865. server_->stop();
  23866. if (server_thread_.joinable()) { server_thread_.join(); }
  23867. }
  23868. void setup_server() {
  23869. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23870. std::string msg;
  23871. ws::ReadResult ret;
  23872. while ((ret = ws.read(msg))) {
  23873. if (ret == ws::Binary) {
  23874. ws.send(msg.data(), msg.size());
  23875. } else {
  23876. ws.send(msg);
  23877. }
  23878. }
  23879. });
  23880. server_->WebSocket("/ws-echo-string",
  23881. [](const Request &, ws::WebSocket &ws) {
  23882. std::string msg;
  23883. while (ws.read(msg)) {
  23884. ws.send("echo: " + msg);
  23885. }
  23886. });
  23887. server_->WebSocket(
  23888. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23889. // Echo back request metadata
  23890. ws.send("path:" + req.path);
  23891. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23892. std::string msg;
  23893. while (ws.read(msg)) {}
  23894. });
  23895. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23896. std::string msg;
  23897. ws.read(msg); // wait for a message
  23898. ws.close();
  23899. });
  23900. server_->WebSocket("/ws-close-status",
  23901. [](const Request &, ws::WebSocket &ws) {
  23902. std::string msg;
  23903. ws.read(msg); // wait for a message
  23904. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23905. });
  23906. server_->WebSocket(
  23907. "/ws-subprotocol",
  23908. [](const Request &, ws::WebSocket &ws) {
  23909. std::string msg;
  23910. while (ws.read(msg)) {
  23911. ws.send(msg);
  23912. }
  23913. },
  23914. [](const std::vector<std::string> &protocols) -> std::string {
  23915. for (const auto &p : protocols) {
  23916. if (p == "graphql-ws") { return p; }
  23917. }
  23918. return "";
  23919. });
  23920. server_->WebSocket(
  23921. "/ws-subprotocol-unoffered",
  23922. [](const Request &, ws::WebSocket &ws) {
  23923. std::string msg;
  23924. while (ws.read(msg)) {
  23925. ws.send(msg);
  23926. }
  23927. },
  23928. [](const std::vector<std::string> &) -> std::string {
  23929. return "admin";
  23930. });
  23931. }
  23932. void start_server() {
  23933. port_ = server_->bind_to_any_port(HOST);
  23934. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23935. server_->wait_until_ready();
  23936. }
  23937. std::unique_ptr<Server> server_;
  23938. std::thread server_thread_;
  23939. int port_ = 0;
  23940. };
  23941. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23942. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23943. "/ws-echo");
  23944. ASSERT_TRUE(client.connect());
  23945. ASSERT_TRUE(client.is_open());
  23946. ASSERT_TRUE(client.send("Hello WebSocket"));
  23947. std::string msg;
  23948. EXPECT_EQ(ws::Text, client.read(msg));
  23949. EXPECT_EQ("Hello WebSocket", msg);
  23950. client.close();
  23951. }
  23952. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23953. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23954. "/ws-echo");
  23955. ASSERT_TRUE(client.connect());
  23956. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23957. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23958. std::string msg;
  23959. EXPECT_EQ(ws::Binary, client.read(msg));
  23960. EXPECT_EQ(binary_data, msg);
  23961. client.close();
  23962. }
  23963. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23965. "/ws-echo");
  23966. ASSERT_TRUE(client.connect());
  23967. for (int i = 0; i < 10; i++) {
  23968. auto text = "message " + std::to_string(i);
  23969. ASSERT_TRUE(client.send(text));
  23970. std::string msg;
  23971. ASSERT_TRUE(client.read(msg));
  23972. EXPECT_EQ(text, msg);
  23973. }
  23974. client.close();
  23975. }
  23976. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23977. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23978. "/ws-close");
  23979. ASSERT_TRUE(client.connect());
  23980. // Send a message to trigger the server to close
  23981. ASSERT_TRUE(client.send("trigger close"));
  23982. // The server will close, so read should return false
  23983. std::string msg;
  23984. EXPECT_FALSE(client.read(msg));
  23985. EXPECT_FALSE(client.is_open());
  23986. }
  23987. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23989. "/ws-echo");
  23990. ASSERT_TRUE(client.connect());
  23991. // 128KB message
  23992. std::string large_data(128 * 1024, 'X');
  23993. ASSERT_TRUE(client.send(large_data));
  23994. std::string msg;
  23995. ASSERT_TRUE(client.read(msg));
  23996. EXPECT_EQ(large_data, msg);
  23997. client.close();
  23998. }
  23999. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24001. "/ws-echo");
  24002. ASSERT_TRUE(client.connect());
  24003. const int num_threads = 4;
  24004. std::vector<std::thread> threads;
  24005. std::atomic<int> send_count{0};
  24006. for (int t = 0; t < num_threads; t++) {
  24007. threads.emplace_back([&client, &send_count, t]() {
  24008. for (int i = 0; i < 5; i++) {
  24009. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24010. if (client.send(text)) { send_count++; }
  24011. }
  24012. });
  24013. }
  24014. for (auto &th : threads) {
  24015. th.join();
  24016. }
  24017. int received = 0;
  24018. std::string msg;
  24019. while (received < send_count.load()) {
  24020. if (!client.read(msg)) { break; }
  24021. received++;
  24022. }
  24023. EXPECT_EQ(send_count.load(), received);
  24024. client.close();
  24025. }
  24026. TEST_F(WebSocketIntegrationTest, ReadString) {
  24027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24028. "/ws-echo-string");
  24029. ASSERT_TRUE(client.connect());
  24030. ASSERT_TRUE(client.send("hello"));
  24031. std::string msg;
  24032. ASSERT_TRUE(client.read(msg));
  24033. EXPECT_EQ("echo: hello", msg);
  24034. ASSERT_TRUE(client.send("world"));
  24035. ASSERT_TRUE(client.read(msg));
  24036. EXPECT_EQ("echo: world", msg);
  24037. client.close();
  24038. }
  24039. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24040. Headers headers = {{"X-Test-Header", "test-value"}};
  24041. ws::WebSocketClient client(
  24042. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24043. ASSERT_TRUE(client.connect());
  24044. std::string msg;
  24045. ASSERT_TRUE(client.read(msg));
  24046. EXPECT_EQ("path:/ws-request-info", msg);
  24047. ASSERT_TRUE(client.read(msg));
  24048. EXPECT_EQ("header:test-value", msg);
  24049. client.close();
  24050. }
  24051. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24052. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24053. "/ws-echo");
  24054. client.set_read_timeout(1, 0); // 1 second
  24055. ASSERT_TRUE(client.connect());
  24056. // Don't send anything — server echo handler waits for a message, so read()
  24057. // should time out. The connection survives it: nothing was consumed.
  24058. std::string msg;
  24059. EXPECT_EQ(client.read(msg), ws::Timeout);
  24060. EXPECT_TRUE(client.is_open());
  24061. // And it is still usable afterwards.
  24062. EXPECT_TRUE(client.send("after timeout"));
  24063. EXPECT_EQ(client.read(msg), ws::Text);
  24064. EXPECT_EQ(msg, "after timeout");
  24065. }
  24066. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24068. "/ws-echo");
  24069. client.set_read_timeout(1, 0);
  24070. ASSERT_TRUE(client.connect());
  24071. ASSERT_TRUE(client.send("first"));
  24072. std::string msg;
  24073. ASSERT_EQ(client.read(msg), ws::Text);
  24074. ASSERT_EQ(msg, "first");
  24075. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24076. // not be used with a read timeout: it would reprocess the previous message.
  24077. EXPECT_EQ(client.read(msg), ws::Timeout);
  24078. EXPECT_EQ(msg, "first");
  24079. }
  24080. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24082. "/ws-echo");
  24083. ASSERT_TRUE(client.connect());
  24084. // Setting it once the connection is open reaches the live stream, not just
  24085. // the seed for the next connect().
  24086. client.set_read_timeout(1, 0);
  24087. std::string msg;
  24088. EXPECT_EQ(client.read(msg), ws::Timeout);
  24089. EXPECT_TRUE(client.is_open());
  24090. }
  24091. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24092. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24093. "/ws-echo");
  24094. client.set_read_timeout(5, 0);
  24095. ASSERT_TRUE(client.connect());
  24096. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24097. // The server should reject it and close the connection.
  24098. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24099. client.send(oversized);
  24100. // The server's read() should have failed due to payload limit,
  24101. // so our read() should return false (connection closed).
  24102. std::string msg;
  24103. EXPECT_FALSE(client.read(msg));
  24104. }
  24105. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24106. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24107. "/ws-echo");
  24108. client.set_read_timeout(10, 0);
  24109. ASSERT_TRUE(client.connect());
  24110. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24111. // This should succeed.
  24112. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24113. ASSERT_TRUE(client.send(at_limit));
  24114. std::string msg;
  24115. ASSERT_TRUE(client.read(msg));
  24116. EXPECT_EQ(at_limit.size(), msg.size());
  24117. client.close();
  24118. }
  24119. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24120. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24121. "/nonexistent");
  24122. auto res = client.connect();
  24123. EXPECT_FALSE(res);
  24124. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24125. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24126. EXPECT_FALSE(client.is_open());
  24127. }
  24128. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24130. "/ws-echo");
  24131. ASSERT_TRUE(client.connect());
  24132. ASSERT_TRUE(client.send(""));
  24133. std::string msg;
  24134. EXPECT_EQ(ws::Text, client.read(msg));
  24135. EXPECT_EQ("", msg);
  24136. client.close();
  24137. }
  24138. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24140. "/ws-echo");
  24141. // First connection
  24142. ASSERT_TRUE(client.connect());
  24143. ASSERT_TRUE(client.send("first"));
  24144. std::string msg;
  24145. ASSERT_TRUE(client.read(msg));
  24146. EXPECT_EQ("first", msg);
  24147. client.close();
  24148. EXPECT_FALSE(client.is_open());
  24149. // Reconnect using the same client object
  24150. ASSERT_TRUE(client.connect());
  24151. ASSERT_TRUE(client.is_open());
  24152. ASSERT_TRUE(client.send("second"));
  24153. ASSERT_TRUE(client.read(msg));
  24154. EXPECT_EQ("second", msg);
  24155. client.close();
  24156. }
  24157. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24158. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24159. "/ws-close-status");
  24160. ASSERT_TRUE(client.connect());
  24161. // Trigger the server to close with GoingAway status
  24162. ASSERT_TRUE(client.send("trigger"));
  24163. // read() should return false after receiving the close frame
  24164. std::string msg;
  24165. EXPECT_FALSE(client.read(msg));
  24166. EXPECT_FALSE(client.is_open());
  24167. }
  24168. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24169. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24170. "/ws-echo");
  24171. ASSERT_TRUE(client.connect());
  24172. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24173. EXPECT_FALSE(client.is_open());
  24174. }
  24175. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24176. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24177. ws::WebSocketClient client(
  24178. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24179. ASSERT_TRUE(client.connect());
  24180. // Server should have selected graphql-ws
  24181. EXPECT_EQ("graphql-ws", client.subprotocol());
  24182. client.close();
  24183. }
  24184. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24185. Headers headers;
  24186. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24187. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24188. ws::WebSocketClient client(
  24189. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24190. ASSERT_TRUE(client.connect());
  24191. // The offer on the second field line counts too, so graphql-ws is selected
  24192. EXPECT_EQ("graphql-ws", client.subprotocol());
  24193. client.close();
  24194. }
  24195. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24196. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24197. ws::WebSocketClient client(
  24198. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24199. ASSERT_TRUE(client.connect());
  24200. // Server should not have selected any subprotocol
  24201. EXPECT_TRUE(client.subprotocol().empty());
  24202. client.close();
  24203. }
  24204. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24205. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24206. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24207. "/ws-subprotocol-unoffered",
  24208. headers);
  24209. ASSERT_TRUE(client.connect());
  24210. EXPECT_TRUE(client.subprotocol().empty());
  24211. client.close();
  24212. }
  24213. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24214. // Connect without requesting any subprotocol
  24215. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24216. "/ws-subprotocol");
  24217. ASSERT_TRUE(client.connect());
  24218. EXPECT_TRUE(client.subprotocol().empty());
  24219. client.close();
  24220. }
  24221. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24222. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24223. "/ws-echo");
  24224. client.set_tcp_nodelay(true);
  24225. client.set_connection_timeout(3, 0);
  24226. bool socket_options_called = false;
  24227. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24228. ASSERT_TRUE(client.connect());
  24229. ASSERT_TRUE(client.is_open());
  24230. EXPECT_TRUE(socket_options_called);
  24231. ASSERT_TRUE(client.send("hello"));
  24232. std::string msg;
  24233. auto result = client.read(msg);
  24234. EXPECT_EQ(result, ws::ReadResult::Text);
  24235. EXPECT_EQ(msg, "hello");
  24236. client.close();
  24237. }
  24238. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24239. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24240. "/ws-echo");
  24241. client.set_connection_timeout(std::chrono::seconds(3));
  24242. client.set_write_timeout(std::chrono::seconds(3));
  24243. // A sub-second remainder exercises the seconds/microseconds split.
  24244. client.set_read_timeout(std::chrono::milliseconds(1500));
  24245. ASSERT_TRUE(client.connect());
  24246. auto start = std::chrono::steady_clock::now();
  24247. std::string msg;
  24248. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24249. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24250. std::chrono::steady_clock::now() - start)
  24251. .count();
  24252. // Above 1s so that dropping the microseconds half of the split fails here.
  24253. // Ignoring the setter altogether would not reach this line at all: a client
  24254. // waits forever by default.
  24255. EXPECT_GE(elapsed, 1400);
  24256. EXPECT_LT(elapsed, 30000);
  24257. }
  24258. #ifndef _WIN32
  24259. // A send() that times out after part of the data went out returns the count
  24260. // written so far. Every byte of the frame must still be sent, or the peer reads
  24261. // the next frame's header and payload as the rest of this one.
  24262. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24263. signal(SIGPIPE, SIG_IGN);
  24264. const std::string large(4 * 1024 * 1024, 'A');
  24265. std::atomic<bool> large_sent{false};
  24266. std::atomic<bool> small_sent{false};
  24267. Server svr;
  24268. svr.set_write_timeout(0, 500000);
  24269. svr.set_socket_options([](socket_t sock) {
  24270. int size = 8192;
  24271. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24272. reinterpret_cast<const char *>(&size), sizeof(size));
  24273. });
  24274. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24275. large_sent = ws.send(large.data(), large.size());
  24276. small_sent = ws.send("after");
  24277. std::string msg;
  24278. while (ws.read(msg)) {}
  24279. });
  24280. auto port = svr.bind_to_any_port(HOST);
  24281. std::thread t([&]() { svr.listen_after_bind(); });
  24282. auto se = detail::scope_exit([&] {
  24283. svr.stop();
  24284. t.join();
  24285. });
  24286. svr.wait_until_ready();
  24287. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24288. std::to_string(port) + "/ws");
  24289. client.set_read_timeout(5);
  24290. client.set_socket_options([](socket_t sock) {
  24291. int size = 8192;
  24292. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24293. reinterpret_cast<const char *>(&size), sizeof(size));
  24294. });
  24295. ASSERT_TRUE(client.connect());
  24296. // Outlast the server's write timeout, then drain.
  24297. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24298. std::string msg;
  24299. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24300. EXPECT_TRUE(msg == large);
  24301. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24302. EXPECT_EQ("after", msg);
  24303. EXPECT_TRUE(large_sent);
  24304. EXPECT_TRUE(small_sent);
  24305. client.close();
  24306. }
  24307. #endif
  24308. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24309. Server svr;
  24310. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24311. if (!req.has_header("Authorization")) {
  24312. res.status = StatusCode::Unauthorized_401;
  24313. res.set_content("Unauthorized", "text/plain");
  24314. return Server::HandlerResponse::Handled;
  24315. }
  24316. return Server::HandlerResponse::Unhandled;
  24317. });
  24318. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24319. std::string msg;
  24320. while (ws.read(msg)) {
  24321. ws.send(msg);
  24322. }
  24323. });
  24324. auto port = svr.bind_to_any_port("localhost");
  24325. std::thread t([&]() { svr.listen_after_bind(); });
  24326. svr.wait_until_ready();
  24327. // Without Authorization header - should be rejected before upgrade
  24328. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24329. EXPECT_FALSE(client1.connect());
  24330. // The rejection is framed like any other HTTP response
  24331. {
  24332. Client cli("localhost", port);
  24333. Headers headers = {{"Upgrade", "websocket"},
  24334. {"Connection", "Upgrade"},
  24335. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24336. {"Sec-WebSocket-Version", "13"}};
  24337. auto res = cli.Get("/ws", headers);
  24338. ASSERT_TRUE(res);
  24339. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24340. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24341. EXPECT_EQ("Unauthorized", res->body);
  24342. }
  24343. // With Authorization header - should succeed
  24344. Headers headers = {{"Authorization", "Bearer token123"}};
  24345. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24346. headers);
  24347. ASSERT_TRUE(client2.connect());
  24348. ASSERT_TRUE(client2.send("hello"));
  24349. std::string msg;
  24350. ASSERT_TRUE(client2.read(msg));
  24351. EXPECT_EQ("hello", msg);
  24352. client2.close();
  24353. svr.stop();
  24354. t.join();
  24355. }
  24356. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24357. Server svr;
  24358. std::atomic<int> pre_routing_calls{0};
  24359. std::atomic<int> pre_request_calls{0};
  24360. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24361. pre_routing_calls++;
  24362. if (req.path == "/handled") {
  24363. res.set_content("handled", "text/plain");
  24364. return Server::HandlerResponse::Handled;
  24365. }
  24366. return Server::HandlerResponse::Unhandled;
  24367. });
  24368. svr.set_pre_request_handler([&](const Request &, Response &) {
  24369. pre_request_calls++;
  24370. return Server::HandlerResponse::Unhandled;
  24371. });
  24372. svr.Get("/http", [](const Request &, Response &res) {
  24373. res.set_content("http", "text/plain");
  24374. });
  24375. svr.WebSocket("/ws",
  24376. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24377. auto port = svr.bind_to_any_port("localhost");
  24378. std::thread t([&]() { svr.listen_after_bind(); });
  24379. auto se = detail::scope_exit([&] {
  24380. svr.stop();
  24381. t.join();
  24382. });
  24383. svr.wait_until_ready();
  24384. Headers upgrade = {{"Upgrade", "websocket"},
  24385. {"Connection", "Upgrade"},
  24386. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24387. {"Sec-WebSocket-Version", "13"}};
  24388. auto get = [&](const char *path) {
  24389. pre_routing_calls = 0;
  24390. return Client("localhost", port).Get(path, upgrade);
  24391. };
  24392. // No WebSocket route, but an HTTP one
  24393. auto res = get("/http");
  24394. ASSERT_TRUE(res);
  24395. EXPECT_EQ(StatusCode::OK_200, res->status);
  24396. EXPECT_EQ("http", res->body);
  24397. EXPECT_EQ(1, pre_routing_calls);
  24398. EXPECT_EQ(1, pre_request_calls);
  24399. // No route at all
  24400. res = get("/none");
  24401. ASSERT_TRUE(res);
  24402. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24403. EXPECT_EQ(1, pre_routing_calls);
  24404. // Answered by the pre-routing handler
  24405. res = get("/handled");
  24406. ASSERT_TRUE(res);
  24407. EXPECT_EQ(StatusCode::OK_200, res->status);
  24408. EXPECT_EQ("handled", res->body);
  24409. EXPECT_EQ(1, pre_routing_calls);
  24410. // A WebSocket route
  24411. pre_routing_calls = 0;
  24412. pre_request_calls = 0;
  24413. {
  24414. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24415. "/ws");
  24416. ASSERT_TRUE(client.connect());
  24417. std::string msg;
  24418. ASSERT_TRUE(client.read(msg));
  24419. EXPECT_EQ("ws", msg);
  24420. client.close();
  24421. }
  24422. EXPECT_EQ(1, pre_routing_calls);
  24423. EXPECT_EQ(1, pre_request_calls);
  24424. }
  24425. // An upgrade request answered by a hook leaves its body unread, so that body
  24426. // must not be served as the next request on the connection.
  24427. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24428. Server svr;
  24429. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24430. if (req.path == "/pre-routing") {
  24431. res.set_content("pre-routing", "text/plain");
  24432. return Server::HandlerResponse::Handled;
  24433. }
  24434. return Server::HandlerResponse::Unhandled;
  24435. });
  24436. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24437. if (req.matched_route == "/pre-request") {
  24438. res.set_content("pre-request", "text/plain");
  24439. return Server::HandlerResponse::Handled;
  24440. }
  24441. return Server::HandlerResponse::Unhandled;
  24442. });
  24443. svr.Get("/smuggled", [](const Request &, Response &res) {
  24444. res.set_content("smuggled", "text/plain");
  24445. });
  24446. svr.WebSocket("/pre-request",
  24447. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24448. auto port = svr.bind_to_any_port(HOST);
  24449. std::thread t([&]() { svr.listen_after_bind(); });
  24450. auto se = detail::scope_exit([&] {
  24451. svr.stop();
  24452. t.join();
  24453. });
  24454. svr.wait_until_ready();
  24455. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24456. for (auto path : {"/pre-routing", "/pre-request"}) {
  24457. std::string req = std::string("GET ") + path +
  24458. " HTTP/1.1\r\n"
  24459. "Host: localhost\r\n"
  24460. "Upgrade: websocket\r\n"
  24461. "Connection: Upgrade\r\n"
  24462. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24463. "Sec-WebSocket-Version: 13\r\n"
  24464. "Content-Length: " +
  24465. std::to_string(body.size()) + "\r\n\r\n" + body;
  24466. std::string res;
  24467. ASSERT_TRUE(send_request(5, req, &res, port));
  24468. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24469. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24470. // Only one response, and the body was not served as a request
  24471. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24472. }
  24473. }
  24474. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24475. Server svr;
  24476. std::atomic<int> pre_request_calls{0};
  24477. std::atomic<bool> route_matched{false};
  24478. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24479. pre_request_calls++;
  24480. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24481. if (req.get_header_value("Authorization") != "Bearer token123") {
  24482. res.status = StatusCode::Unauthorized_401;
  24483. res.set_content("Unauthorized", "text/plain");
  24484. return Server::HandlerResponse::Handled;
  24485. }
  24486. return Server::HandlerResponse::Unhandled;
  24487. });
  24488. std::atomic<bool> handler_called{false};
  24489. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24490. handler_called = true;
  24491. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24492. });
  24493. auto port = svr.bind_to_any_port("localhost");
  24494. std::thread t([&]() { svr.listen_after_bind(); });
  24495. svr.wait_until_ready();
  24496. // Without Authorization header - should be rejected before upgrade
  24497. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24498. "/ws/1");
  24499. EXPECT_FALSE(client1.connect());
  24500. EXPECT_FALSE(handler_called);
  24501. EXPECT_EQ(1, pre_request_calls);
  24502. EXPECT_TRUE(route_matched);
  24503. // The rejection is an ordinary HTTP response, not a protocol switch
  24504. {
  24505. Client cli("localhost", port);
  24506. Headers headers = {{"Upgrade", "websocket"},
  24507. {"Connection", "Upgrade"},
  24508. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24509. {"Sec-WebSocket-Version", "13"}};
  24510. auto res = cli.Get("/ws/1", headers);
  24511. ASSERT_TRUE(res);
  24512. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24513. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24514. EXPECT_EQ("Unauthorized", res->body);
  24515. }
  24516. EXPECT_FALSE(handler_called);
  24517. // With Authorization header - should succeed
  24518. Headers headers = {{"Authorization", "Bearer token123"}};
  24519. ws::WebSocketClient client2(
  24520. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24521. ASSERT_TRUE(client2.connect());
  24522. std::string msg;
  24523. ASSERT_TRUE(client2.read(msg));
  24524. EXPECT_EQ("/ws/:id 2", msg);
  24525. EXPECT_TRUE(handler_called);
  24526. client2.close();
  24527. svr.stop();
  24528. t.join();
  24529. }
  24530. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24531. static Headers websocket_upgrade_headers() {
  24532. return {{"Upgrade", "websocket"},
  24533. {"Connection", "Upgrade"},
  24534. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24535. {"Sec-WebSocket-Version", "13"},
  24536. {"Sec-WebSocket-Protocol", "chat"}};
  24537. }
  24538. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24539. Server svr;
  24540. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24541. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24542. return Server::HandlerResponse::Unhandled;
  24543. });
  24544. svr.set_pre_request_handler([](const Request &req, Response &) {
  24545. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24546. return Server::HandlerResponse::Unhandled;
  24547. });
  24548. svr.set_exception_handler(
  24549. [](const Request &, Response &res, std::exception_ptr ep) {
  24550. try {
  24551. std::rethrow_exception(ep);
  24552. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24553. });
  24554. auto handler = [](const Request &, ws::WebSocket &) {};
  24555. svr.WebSocket("/pre-routing", handler);
  24556. svr.WebSocket("/pre-request", handler);
  24557. svr.WebSocket("/sub-protocol", handler,
  24558. [](const std::vector<std::string> &) -> std::string {
  24559. throw std::runtime_error("/sub-protocol");
  24560. });
  24561. auto port = svr.bind_to_any_port(HOST);
  24562. ASSERT_GT(port, 0);
  24563. thread t = thread([&] { svr.listen_after_bind(); });
  24564. auto se = detail::scope_exit([&] {
  24565. svr.stop();
  24566. t.join();
  24567. ASSERT_FALSE(svr.is_running());
  24568. });
  24569. svr.wait_until_ready();
  24570. Client cli(HOST, port);
  24571. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24572. auto res = cli.Get(path, websocket_upgrade_headers());
  24573. if (!res) {
  24574. ADD_FAILURE() << path << ": " << to_string(res.error());
  24575. continue;
  24576. }
  24577. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24578. EXPECT_EQ(path, res->body);
  24579. }
  24580. }
  24581. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24582. Server svr;
  24583. svr.set_pre_routing_handler(
  24584. [](const Request &, Response &) -> Server::HandlerResponse {
  24585. throw std::runtime_error("pre-routing");
  24586. });
  24587. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24588. auto port = svr.bind_to_any_port(HOST);
  24589. ASSERT_GT(port, 0);
  24590. thread t = thread([&] { svr.listen_after_bind(); });
  24591. auto se = detail::scope_exit([&] {
  24592. svr.stop();
  24593. t.join();
  24594. ASSERT_FALSE(svr.is_running());
  24595. });
  24596. svr.wait_until_ready();
  24597. Client cli(HOST, port);
  24598. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24599. ASSERT_TRUE(res) << to_string(res.error());
  24600. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24601. }
  24602. #endif
  24603. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24604. Server svr;
  24605. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24606. // A read timeout is how a handler gets control back. Without it, a handler
  24607. // parked in read() can never write on the connection it is reading.
  24608. ws.set_read_timeout(std::chrono::milliseconds(100));
  24609. std::string msg;
  24610. while (ws.is_open()) {
  24611. auto r = ws.read(msg);
  24612. if (r == httplib::ws::Timeout) {
  24613. ws.send("tick");
  24614. continue;
  24615. }
  24616. if (r == httplib::ws::Fail) { break; }
  24617. ws.send(msg);
  24618. }
  24619. });
  24620. auto port = svr.bind_to_any_port("localhost");
  24621. std::thread t([&]() { svr.listen_after_bind(); });
  24622. svr.wait_until_ready();
  24623. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24624. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24625. ASSERT_TRUE(client.connect());
  24626. // The client sends nothing, so anything it receives came out of the
  24627. // handler's timeout path.
  24628. std::string msg;
  24629. ASSERT_EQ(client.read(msg), ws::Text);
  24630. EXPECT_EQ("tick", msg);
  24631. client.close();
  24632. svr.stop();
  24633. t.join();
  24634. }
  24635. // Stream::read may return fewer bytes than asked for. This is that contract at
  24636. // its worst -- one byte per call -- which is what a frame header straddling a
  24637. // read buffer's boundary looks like to the frame parser.
  24638. class WsByteAtATimeStream : public Stream {
  24639. public:
  24640. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24641. bool is_readable() const override { return true; }
  24642. bool wait_readable() const override { return true; }
  24643. bool wait_writable() const override { return true; }
  24644. ssize_t read(char *ptr, size_t size) override {
  24645. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24646. *ptr = data_[pos_++];
  24647. return 1;
  24648. }
  24649. ssize_t write(const char *, size_t size) override {
  24650. return static_cast<ssize_t>(size);
  24651. }
  24652. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24653. ip = "127.0.0.1";
  24654. port = 0;
  24655. }
  24656. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24657. ip = "127.0.0.1";
  24658. port = 0;
  24659. }
  24660. socket_t socket() const override { return INVALID_SOCKET; }
  24661. time_t duration() const override { return 0; }
  24662. private:
  24663. std::string data_;
  24664. size_t pos_ = 0;
  24665. };
  24666. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24667. // The payload uses the 16-bit extended length, so the header, the length
  24668. // and the mask key are all multi-byte fields here. Each used to be read
  24669. // with a single read() call, which fails as soon as one is split. The
  24670. // payload is also a little over one read chunk, so it is read in two.
  24671. std::string body;
  24672. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24673. body += static_cast<char>(i % 251);
  24674. }
  24675. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24676. std::string frame;
  24677. frame += static_cast<char>(0x81); // FIN + Text
  24678. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24679. frame += static_cast<char>(body.size() >> 8);
  24680. frame += static_cast<char>(body.size() & 0xff);
  24681. for (size_t i = 0; i < 4; i++) {
  24682. frame += static_cast<char>(mask[i]);
  24683. }
  24684. for (size_t i = 0; i < body.size(); i++) {
  24685. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24686. }
  24687. WsByteAtATimeStream strm(frame);
  24688. ws::Opcode opcode;
  24689. std::string payload;
  24690. bool fin = false;
  24691. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24692. /*expect_masked=*/true, body.size()),
  24693. ws::impl::FrameRead::Ok);
  24694. EXPECT_TRUE(fin);
  24695. EXPECT_EQ(opcode, ws::Opcode::Text);
  24696. EXPECT_EQ(payload, body);
  24697. }
  24698. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24699. std::string body(2000, 'x');
  24700. std::string frame;
  24701. frame += static_cast<char>(0x82); // FIN + Binary
  24702. frame += static_cast<char>(126); // 16-bit length follows
  24703. frame += static_cast<char>(body.size() >> 8);
  24704. frame += static_cast<char>(body.size() & 0xff);
  24705. frame += body;
  24706. detail::BufferStream strm;
  24707. strm.write(frame.data(), frame.size());
  24708. ws::Opcode opcode;
  24709. std::string payload;
  24710. bool fin;
  24711. EXPECT_EQ(
  24712. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24713. ws::impl::FrameRead::Ok);
  24714. EXPECT_EQ(body, payload);
  24715. }
  24716. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24717. // The header announces the largest payload allowed, and only 3 bytes of it
  24718. // ever arrive.
  24719. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24720. std::string frame;
  24721. frame += static_cast<char>(0x82); // FIN + Binary
  24722. frame += static_cast<char>(127); // 64-bit length follows
  24723. for (int shift = 56; shift >= 0; shift -= 8) {
  24724. frame += static_cast<char>((len >> shift) & 0xff);
  24725. }
  24726. frame += "abc";
  24727. detail::BufferStream strm;
  24728. strm.write(frame.data(), frame.size());
  24729. ws::Opcode opcode;
  24730. std::string payload;
  24731. bool fin;
  24732. EXPECT_EQ(
  24733. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24734. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24735. ws::impl::FrameRead::Fail);
  24736. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24737. }
  24738. TEST(WebSocketTest, QueryStringInHandshake) {
  24739. Server svr;
  24740. std::mutex mtx;
  24741. std::string received_target;
  24742. std::string received_token;
  24743. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24744. {
  24745. std::lock_guard<std::mutex> lock(mtx);
  24746. received_target = req.target;
  24747. if (req.has_param("token")) {
  24748. received_token = req.get_param_value("token");
  24749. }
  24750. }
  24751. std::string msg;
  24752. while (ws.read(msg)) {
  24753. ws.send(msg);
  24754. }
  24755. });
  24756. auto port = svr.bind_to_any_port("localhost");
  24757. std::thread t([&]() { svr.listen_after_bind(); });
  24758. svr.wait_until_ready();
  24759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24760. "/ws?token=ABC&session=123");
  24761. ASSERT_TRUE(client.connect());
  24762. // Round-trip ensures the handler has run and captured the request.
  24763. ASSERT_TRUE(client.send("hello"));
  24764. std::string msg;
  24765. ASSERT_TRUE(client.read(msg));
  24766. EXPECT_EQ("hello", msg);
  24767. client.close();
  24768. {
  24769. std::lock_guard<std::mutex> lock(mtx);
  24770. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24771. EXPECT_EQ("ABC", received_token);
  24772. }
  24773. svr.stop();
  24774. t.join();
  24775. }
  24776. // Run a handshake against a throwaway server and hand the request the server
  24777. // received back to the caller, so tests can assert on the headers the client
  24778. // actually put on the wire.
  24779. static void capture_websocket_handshake_request(
  24780. const Headers &client_headers,
  24781. std::function<void(const Request &, int port)> verify) {
  24782. Server svr;
  24783. std::mutex mtx;
  24784. Request received;
  24785. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24786. {
  24787. std::lock_guard<std::mutex> lock(mtx);
  24788. received = req;
  24789. }
  24790. std::string msg;
  24791. while (ws.read(msg)) {
  24792. ws.send(msg);
  24793. }
  24794. });
  24795. auto port = svr.bind_to_any_port("localhost");
  24796. std::thread t([&]() { svr.listen_after_bind(); });
  24797. auto se = detail::scope_exit([&] {
  24798. svr.stop();
  24799. t.join();
  24800. });
  24801. svr.wait_until_ready();
  24802. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24803. client_headers);
  24804. ASSERT_TRUE(client.connect());
  24805. ASSERT_TRUE(client.send("hello"));
  24806. std::string msg;
  24807. ASSERT_TRUE(client.read(msg));
  24808. client.close();
  24809. {
  24810. std::lock_guard<std::mutex> lock(mtx);
  24811. verify(received, port);
  24812. }
  24813. }
  24814. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24815. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24816. // Non-default port must be present in the Host header. Default ports
  24817. // (80/443) are omitted; that logic is covered by
  24818. // MakeHostAndPortStringTest.
  24819. EXPECT_EQ("localhost:" + std::to_string(port),
  24820. req.get_header_value("Host"));
  24821. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24822. req.get_header_value("User-Agent"));
  24823. EXPECT_FALSE(req.has_header("Accept"));
  24824. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24825. EXPECT_FALSE(req.has_header("Content-Length"));
  24826. });
  24827. }
  24828. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24829. capture_websocket_handshake_request(
  24830. {{"Host", "example.com"},
  24831. {"User-Agent", "custom-agent"},
  24832. {"X-Custom", "value"}},
  24833. [](const Request &req, int) {
  24834. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24835. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24836. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24837. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24838. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24839. });
  24840. }
  24841. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24842. capture_websocket_handshake_request(
  24843. {{"Upgrade", "bogus"},
  24844. {"Connection", "close"},
  24845. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24846. {"Sec-WebSocket-Version", "8"}},
  24847. [](const Request &req, int) {
  24848. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24849. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24850. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24851. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24852. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24853. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24854. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24855. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24856. req.get_header_value("Sec-WebSocket-Key"));
  24857. });
  24858. }
  24859. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24860. // A header the client refuses to send must abort the handshake before any
  24861. // part of it reaches the wire; a lone request line would otherwise sit in
  24862. // the peer's buffer as a truncated request.
  24863. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24864. ASSERT_NE(INVALID_SOCKET, srv);
  24865. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24866. sockaddr_in addr{};
  24867. addr.sin_family = AF_INET;
  24868. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24869. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24870. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24871. ASSERT_EQ(0, ::listen(srv, 1));
  24872. sockaddr_in bound{};
  24873. socklen_t bound_len = sizeof(bound);
  24874. ASSERT_EQ(
  24875. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24876. auto port = ntohs(bound.sin_port);
  24877. ssize_t received = -1;
  24878. std::thread t([&] {
  24879. // Bound every blocking call so a regression fails the test with a bad
  24880. // value instead of hanging the suite.
  24881. fd_set rfds;
  24882. FD_ZERO(&rfds);
  24883. FD_SET(srv, &rfds);
  24884. timeval tv{5, 0};
  24885. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24886. 0) {
  24887. return;
  24888. }
  24889. sockaddr_in cli_addr{};
  24890. socklen_t cli_len = sizeof(cli_addr);
  24891. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24892. if (cli == INVALID_SOCKET) { return; }
  24893. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24894. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24895. char buf[4096];
  24896. received = ::recv(cli, buf, sizeof(buf), 0);
  24897. });
  24898. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24899. // connect() has already shut the socket down by the time it returns false,
  24900. // so the peer sees EOF without waiting for the client to be destroyed.
  24901. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24902. {{"X-Bad", "a\r\nInjected: 1"}});
  24903. EXPECT_FALSE(client.connect());
  24904. t.join();
  24905. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24906. EXPECT_EQ(0, received);
  24907. }
  24908. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24909. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24910. // contains "upgrade" as a substring is a different token and must not
  24911. // start a WebSocket handshake.
  24912. auto make_request = [](const std::vector<std::string> &connection_values) {
  24913. Request req;
  24914. req.method = "GET";
  24915. req.headers.emplace("Upgrade", "websocket");
  24916. for (const auto &value : connection_values) {
  24917. req.headers.emplace("Connection", value);
  24918. }
  24919. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24920. req.headers.emplace("Sec-WebSocket-Version", "13");
  24921. return req;
  24922. };
  24923. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24924. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24925. EXPECT_TRUE(
  24926. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24927. EXPECT_TRUE(
  24928. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24929. EXPECT_TRUE(
  24930. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24931. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24932. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24933. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24934. EXPECT_FALSE(
  24935. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24936. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24937. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24938. }
  24939. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24940. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24941. // asks recipients to match each protocol-name case-insensitively, and RFC
  24942. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24943. // client naming websocket alongside another protocol, or on a second field
  24944. // line, is offering websocket; a value that merely contains "websocket" as a
  24945. // substring is a different protocol name and is not.
  24946. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24947. Request req;
  24948. req.method = "GET";
  24949. for (const auto &value : upgrade_values) {
  24950. req.headers.emplace("Upgrade", value);
  24951. }
  24952. req.headers.emplace("Connection", "Upgrade");
  24953. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24954. req.headers.emplace("Sec-WebSocket-Version", "13");
  24955. return req;
  24956. };
  24957. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24958. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24959. EXPECT_TRUE(
  24960. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24961. EXPECT_TRUE(
  24962. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24963. EXPECT_TRUE(
  24964. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24965. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24966. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24967. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24968. EXPECT_FALSE(
  24969. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24970. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24971. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24972. }
  24973. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24974. Server svr;
  24975. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24976. auto port = svr.bind_to_any_port("localhost");
  24977. std::thread t([&]() { svr.listen_after_bind(); });
  24978. auto se = detail::scope_exit([&] {
  24979. svr.stop();
  24980. t.join();
  24981. });
  24982. svr.wait_until_ready();
  24983. Headers headers = {{"Upgrade", "websocket"},
  24984. {"Connection", "notupgrade"},
  24985. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24986. {"Sec-WebSocket-Version", "13"}};
  24987. Client cli("localhost", port);
  24988. auto res = cli.Get("/ws", headers);
  24989. // The route exists only as a WebSocket route, so a request that fails the
  24990. // handshake check falls through to ordinary routing.
  24991. ASSERT_TRUE(res);
  24992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24993. }
  24994. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24995. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24996. // Connection value is the only thing left for the client to reject.
  24997. Server svr;
  24998. svr.Get("/ws", [](const Request &req, Response &res) {
  24999. res.status = StatusCode::SwitchingProtocol_101;
  25000. res.set_header("Upgrade", "websocket");
  25001. res.set_header("Connection", "notupgrade");
  25002. res.set_header("Sec-WebSocket-Accept",
  25003. detail::websocket_accept_key(
  25004. req.get_header_value("Sec-WebSocket-Key")));
  25005. });
  25006. auto port = svr.bind_to_any_port("localhost");
  25007. std::thread t([&]() { svr.listen_after_bind(); });
  25008. auto se = detail::scope_exit([&] {
  25009. svr.stop();
  25010. t.join();
  25011. });
  25012. svr.wait_until_ready();
  25013. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25014. auto res = client.connect();
  25015. EXPECT_FALSE(res);
  25016. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25017. EXPECT_FALSE(client.is_open());
  25018. }
  25019. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25020. Server svr;
  25021. svr.Get("/ws", [](const Request &req, Response &res) {
  25022. res.status = StatusCode::SwitchingProtocol_101;
  25023. res.set_header("Upgrade", "websocket");
  25024. res.set_header("Connection", "Upgrade");
  25025. res.set_header("Sec-WebSocket-Accept",
  25026. detail::websocket_accept_key(
  25027. req.get_header_value("Sec-WebSocket-Key")));
  25028. res.set_header("Sec-WebSocket-Protocol", "admin");
  25029. });
  25030. auto port = svr.bind_to_any_port("localhost");
  25031. std::thread t([&]() { svr.listen_after_bind(); });
  25032. auto se = detail::scope_exit([&] {
  25033. svr.stop();
  25034. t.join();
  25035. });
  25036. svr.wait_until_ready();
  25037. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25038. // Server selects a subprotocol the client never offered
  25039. {
  25040. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25041. ws::WebSocketClient client(url, headers);
  25042. auto res = client.connect();
  25043. EXPECT_FALSE(res);
  25044. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25045. EXPECT_FALSE(client.is_open());
  25046. EXPECT_TRUE(client.subprotocol().empty());
  25047. }
  25048. // Client offered none but the server named one anyway
  25049. {
  25050. ws::WebSocketClient client(url);
  25051. auto res = client.connect();
  25052. EXPECT_FALSE(res);
  25053. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25054. EXPECT_FALSE(client.is_open());
  25055. EXPECT_TRUE(client.subprotocol().empty());
  25056. }
  25057. }
  25058. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25059. // The socket path doubles as the URL host, so it must not contain '/'.
  25060. const char *shard = getenv("GTEST_SHARD_INDEX");
  25061. const std::string sock_path =
  25062. shard ? std::string("httplib-ws-") + shard + ".sock"
  25063. : std::string("httplib-ws.sock");
  25064. std::remove(sock_path.c_str());
  25065. Server svr;
  25066. std::mutex mtx;
  25067. std::string received_host;
  25068. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25069. {
  25070. std::lock_guard<std::mutex> lock(mtx);
  25071. received_host = req.get_header_value("Host");
  25072. }
  25073. std::string msg;
  25074. while (ws.read(msg)) {
  25075. ws.send(msg);
  25076. }
  25077. });
  25078. svr.set_address_family(AF_UNIX);
  25079. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25080. auto se = detail::scope_exit([&] {
  25081. svr.stop();
  25082. t.join();
  25083. std::remove(sock_path.c_str());
  25084. });
  25085. svr.wait_until_ready();
  25086. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25087. client.set_address_family(AF_UNIX);
  25088. ASSERT_TRUE(client.connect());
  25089. ASSERT_TRUE(client.send("hello"));
  25090. std::string msg;
  25091. ASSERT_TRUE(client.read(msg));
  25092. client.close();
  25093. {
  25094. std::lock_guard<std::mutex> lock(mtx);
  25095. // There is no host:port for a Unix socket, so the same "localhost"
  25096. // placeholder the HTTP client uses is expected.
  25097. EXPECT_EQ("localhost", received_host);
  25098. }
  25099. }
  25100. // Two threads must never parse WebSocket frames from the same stream.
  25101. // close() used to read the peer's Close reply with its own frame read, so it
  25102. // raced a reader thread that was in the middle of a payload: the payload loop
  25103. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25104. // so bytes taken by close() were replaced with bytes from further along the
  25105. // stream. The message kept its length and silently changed content.
  25106. //
  25107. // The raw peer below sends a frame header plus part of the payload, waits for
  25108. // the handler to call close(), and only then sends the rest. Whichever thread
  25109. // would win the race for those bytes, the message must arrive intact, because
  25110. // close() must not touch the stream while read() owns it.
  25111. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25112. #ifndef _WIN32
  25113. signal(SIGPIPE, SIG_IGN);
  25114. #endif
  25115. const size_t payload_len = 120; // fits the 7-bit length field
  25116. const size_t prefix_len = 8;
  25117. const int attempts = 8;
  25118. std::string expected(payload_len, '\0');
  25119. for (size_t i = 0; i < payload_len; i++) {
  25120. expected[i] = static_cast<char>('a' + i % 26);
  25121. }
  25122. std::atomic<bool> peer_stalled{false};
  25123. std::atomic<bool> handler_done{false};
  25124. std::mutex received_mutex;
  25125. std::vector<std::string> received;
  25126. // Bound every wait, so a regression fails the test instead of hanging the
  25127. // suite.
  25128. auto wait_for = [](const std::atomic<bool> &flag) {
  25129. for (int i = 0; i < 500 && !flag; i++) {
  25130. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25131. }
  25132. };
  25133. Server svr;
  25134. svr.set_websocket_ping_interval(0);
  25135. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25136. std::thread reader([&]() {
  25137. std::string msg;
  25138. while (ws.read(msg)) {
  25139. std::lock_guard<std::mutex> guard(received_mutex);
  25140. received.push_back(msg);
  25141. }
  25142. });
  25143. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25144. // inside read_websocket_frame() when close() runs.
  25145. wait_for(peer_stalled);
  25146. ws.close();
  25147. reader.join();
  25148. handler_done = true;
  25149. });
  25150. auto port = svr.bind_to_any_port("127.0.0.1");
  25151. std::thread t([&]() { svr.listen_after_bind(); });
  25152. auto se = detail::scope_exit([&] {
  25153. svr.stop();
  25154. t.join();
  25155. });
  25156. svr.wait_until_ready();
  25157. auto send_bytes = [](socket_t s, const std::string &data) {
  25158. #ifdef _WIN32
  25159. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25160. #else
  25161. auto n = ::send(s, data.data(), data.size(), 0);
  25162. #endif
  25163. return n == static_cast<decltype(n)>(data.size());
  25164. };
  25165. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25166. // Every length used here fits the 7-bit length field.
  25167. auto masked_header = [](uint8_t first_byte, size_t len) {
  25168. std::string h;
  25169. h += static_cast<char>(first_byte);
  25170. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25171. h.append(4, '\0'); // mask key
  25172. return h;
  25173. };
  25174. for (int attempt = 0; attempt < attempts; attempt++) {
  25175. peer_stalled = false;
  25176. handler_done = false;
  25177. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25178. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25179. auto se_sock = detail::scope_exit([&] {
  25180. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25181. });
  25182. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25183. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25184. sockaddr_in addr{};
  25185. addr.sin_family = AF_INET;
  25186. addr.sin_port = htons(static_cast<uint16_t>(port));
  25187. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25188. ASSERT_EQ(
  25189. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25190. << "attempt " << attempt;
  25191. ASSERT_TRUE(send_bytes(sock,
  25192. "GET /ws HTTP/1.1\r\n"
  25193. "Host: 127.0.0.1\r\n"
  25194. "Upgrade: websocket\r\n"
  25195. "Connection: Upgrade\r\n"
  25196. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25197. "Sec-WebSocket-Version: 13\r\n"
  25198. "\r\n"))
  25199. << "attempt " << attempt;
  25200. std::string response;
  25201. while (response.find("\r\n\r\n") == std::string::npos) {
  25202. char buf[512];
  25203. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25204. if (n <= 0) { break; }
  25205. response.append(buf, static_cast<size_t>(n));
  25206. }
  25207. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25208. << "attempt " << attempt;
  25209. // Send the header of a Binary message but only the first prefix_len bytes
  25210. // of its payload, leaving the reader thread stalled inside the payload.
  25211. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25212. expected.substr(0, prefix_len)))
  25213. << "attempt " << attempt;
  25214. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25215. peer_stalled = true;
  25216. // Let close() send its Close frame and park in its own read before the
  25217. // rest of the payload arrives, so both threads are waiting for it.
  25218. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25219. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25220. close_frame += static_cast<char>(0x03); // status 1000
  25221. close_frame += static_cast<char>(0xE8);
  25222. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25223. << "attempt " << attempt;
  25224. // Closing the peer releases the reader thread even on the buggy path,
  25225. // where it waits for bytes another thread already consumed.
  25226. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25227. detail::close_socket(sock);
  25228. sock = INVALID_SOCKET;
  25229. wait_for(handler_done);
  25230. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25231. }
  25232. std::lock_guard<std::mutex> guard(received_mutex);
  25233. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25234. << "a message in flight when close() ran was dropped";
  25235. for (size_t i = 0; i < received.size(); i++) {
  25236. EXPECT_EQ(expected, received[i]) << "message " << i;
  25237. }
  25238. }
  25239. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25240. // returning the socket, or INVALID_SOCKET.
  25241. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25242. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25243. if (sock == INVALID_SOCKET) { return sock; }
  25244. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25245. sockaddr_in addr{};
  25246. addr.sin_family = AF_INET;
  25247. addr.sin_port = htons(static_cast<uint16_t>(port));
  25248. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25249. std::string req = "GET " + path +
  25250. " HTTP/1.1\r\n"
  25251. "Host: 127.0.0.1\r\n"
  25252. "Upgrade: websocket\r\n"
  25253. "Connection: Upgrade\r\n"
  25254. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25255. "Sec-WebSocket-Version: 13\r\n"
  25256. "\r\n";
  25257. std::string res;
  25258. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25259. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25260. static_cast<ssize_t>(req.size())) {
  25261. char c;
  25262. while (res.find("\r\n\r\n") == std::string::npos &&
  25263. ::recv(sock, &c, 1, 0) == 1) {
  25264. res += c;
  25265. }
  25266. }
  25267. if (res.find(" 101 ") == std::string::npos) {
  25268. detail::close_socket(sock);
  25269. return INVALID_SOCKET;
  25270. }
  25271. return sock;
  25272. }
  25273. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25274. // The payload must fit the 7-bit length field.
  25275. static std::string masked_frame(uint8_t first_byte,
  25276. const std::string &payload) {
  25277. std::string f;
  25278. f += static_cast<char>(first_byte);
  25279. f += static_cast<char>(0x80 | payload.size());
  25280. f.append(4, '\0');
  25281. return f + payload;
  25282. }
  25283. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25284. std::atomic<bool> done{false};
  25285. std::string received;
  25286. Server svr;
  25287. svr.set_websocket_ping_interval(0);
  25288. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25289. std::string msg;
  25290. if (ws.read(msg) == ws::Binary) { received = msg; }
  25291. done = true;
  25292. });
  25293. auto port = svr.bind_to_any_port("127.0.0.1");
  25294. std::thread t([&]() { svr.listen_after_bind(); });
  25295. auto se = detail::scope_exit([&] {
  25296. svr.stop();
  25297. t.join();
  25298. });
  25299. svr.wait_until_ready();
  25300. auto sock = connect_raw_websocket(port, "/ws");
  25301. ASSERT_NE(INVALID_SOCKET, sock);
  25302. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25303. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25304. masked_frame(0x89, "p") + // FIN + Ping
  25305. masked_frame(0x80, "lo"); // FIN + Continuation
  25306. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25307. for (int i = 0; i < 500 && !done; i++) {
  25308. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25309. }
  25310. ASSERT_TRUE(done);
  25311. EXPECT_EQ("Hello", received);
  25312. // The Ping between the fragments is answered with a Pong.
  25313. char pong[3];
  25314. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25315. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25316. }
  25317. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25318. Server svr;
  25319. svr.set_websocket_ping_interval(-1);
  25320. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25321. std::string msg;
  25322. while (ws.read(msg)) {}
  25323. });
  25324. auto port = svr.bind_to_any_port("127.0.0.1");
  25325. std::thread t([&]() { svr.listen_after_bind(); });
  25326. auto se = detail::scope_exit([&] {
  25327. svr.stop();
  25328. t.join();
  25329. });
  25330. svr.wait_until_ready();
  25331. auto sock = connect_raw_websocket(port, "/ws");
  25332. ASSERT_NE(INVALID_SOCKET, sock);
  25333. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25334. // Nothing comes while the client stays quiet.
  25335. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25336. char c;
  25337. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25338. }
  25339. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25340. // and that has to end a read() already waiting on the peer, on every platform.
  25341. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25342. // The peer sends no pings, and its handler never calls read(), which is
  25343. // where pongs are written.
  25344. std::mutex mutex;
  25345. std::condition_variable cv;
  25346. auto release = false;
  25347. svr.set_websocket_ping_interval(0);
  25348. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25349. std::unique_lock<std::mutex> lock(mutex);
  25350. cv.wait(lock, [&] { return release; });
  25351. });
  25352. auto port = svr.bind_to_any_port(HOST);
  25353. std::thread t([&]() { svr.listen_after_bind(); });
  25354. auto se = detail::scope_exit([&] {
  25355. {
  25356. std::lock_guard<std::mutex> lock(mutex);
  25357. release = true;
  25358. }
  25359. cv.notify_all();
  25360. svr.stop();
  25361. t.join();
  25362. });
  25363. svr.wait_until_ready();
  25364. ws::WebSocketClient client(std::string(scheme) +
  25365. "://localhost:" + std::to_string(port) + "/ws");
  25366. #ifdef CPPHTTPLIB_SSL_ENABLED
  25367. client.enable_server_certificate_verification(false);
  25368. #endif
  25369. // A ping a second, given up on after two go unanswered: about 3s
  25370. client.set_websocket_ping_interval(1);
  25371. client.set_websocket_max_missed_pongs(2);
  25372. // Well past that, so that a read the timeout ends instead stands out
  25373. client.set_read_timeout(10);
  25374. ASSERT_TRUE(client.connect());
  25375. auto start = std::chrono::steady_clock::now();
  25376. std::string msg;
  25377. EXPECT_EQ(ws::Fail, client.read(msg));
  25378. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25379. std::chrono::steady_clock::now() - start)
  25380. .count(),
  25381. 6000);
  25382. EXPECT_FALSE(client.is_open());
  25383. }
  25384. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25385. Server svr;
  25386. check_pong_timeout_ends_read(svr, "ws");
  25387. }
  25388. #ifdef CPPHTTPLIB_SSL_ENABLED
  25389. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25391. ASSERT_TRUE(svr.is_valid());
  25392. check_pong_timeout_ends_read(svr, "wss");
  25393. }
  25394. #endif
  25395. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25396. Server svr;
  25397. svr.set_websocket_ping_interval(0);
  25398. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25399. std::string msg;
  25400. while (ws.read(msg)) {}
  25401. });
  25402. auto port = svr.bind_to_any_port("127.0.0.1");
  25403. std::thread t([&]() { svr.listen_after_bind(); });
  25404. auto se = detail::scope_exit([&] {
  25405. svr.stop();
  25406. t.join();
  25407. });
  25408. svr.wait_until_ready();
  25409. // Each Close payload and the reply it should get: an echo when valid, 1002
  25410. // otherwise.
  25411. std::vector<std::pair<std::string, std::string>> cases = {
  25412. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25413. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25414. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25415. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25416. };
  25417. // Also between the fragments of a message.
  25418. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25419. for (const auto &c : cases) {
  25420. auto sock = connect_raw_websocket(port, "/ws");
  25421. ASSERT_NE(INVALID_SOCKET, sock);
  25422. auto frames = prefix + masked_frame(0x88, c.first);
  25423. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25424. std::string reply;
  25425. char buf[256];
  25426. while (reply.size() < 2 + c.second.size()) {
  25427. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25428. if (n <= 0) { break; }
  25429. reply.append(buf, static_cast<size_t>(n));
  25430. }
  25431. detail::close_socket(sock);
  25432. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25433. c.second,
  25434. reply);
  25435. }
  25436. }
  25437. }
  25438. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25439. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25440. protected:
  25441. void SetUp() override {
  25442. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25443. SERVER_PRIVATE_KEY_FILE);
  25444. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25445. std::string msg;
  25446. ws::ReadResult ret;
  25447. while ((ret = ws.read(msg))) {
  25448. if (ret == ws::Binary) {
  25449. ws.send(msg.data(), msg.size());
  25450. } else {
  25451. ws.send(msg);
  25452. }
  25453. }
  25454. });
  25455. port_ = server_->bind_to_any_port(HOST);
  25456. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25457. server_->wait_until_ready();
  25458. }
  25459. void TearDown() override {
  25460. server_->stop();
  25461. if (server_thread_.joinable()) { server_thread_.join(); }
  25462. }
  25463. std::unique_ptr<SSLServer> server_;
  25464. std::thread server_thread_;
  25465. int port_ = 0;
  25466. };
  25467. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25468. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25469. {
  25470. ws::WebSocketClient client(url);
  25471. client.enable_server_certificate_verification(false);
  25472. auto calls = 0;
  25473. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25474. calls++;
  25475. return false;
  25476. });
  25477. EXPECT_FALSE(client.connect());
  25478. EXPECT_GT(calls, 0);
  25479. }
  25480. {
  25481. ws::WebSocketClient client(url);
  25482. client.enable_server_certificate_verification(false);
  25483. client.set_session_verifier([](tls::session_t) {
  25484. return SSLVerifierResponse::CertificateRejected;
  25485. });
  25486. EXPECT_FALSE(client.connect());
  25487. }
  25488. {
  25489. ws::WebSocketClient client(url);
  25490. client.enable_server_certificate_verification(false);
  25491. client.set_session_verifier([](tls::session_t) {
  25492. return SSLVerifierResponse::CertificateAccepted;
  25493. });
  25494. EXPECT_TRUE(client.connect());
  25495. }
  25496. }
  25497. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25498. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25499. "/ws-echo");
  25500. client.enable_server_certificate_verification(false);
  25501. ASSERT_TRUE(client.connect());
  25502. ASSERT_TRUE(client.is_open());
  25503. ASSERT_TRUE(client.send("Hello WSS"));
  25504. std::string msg;
  25505. EXPECT_EQ(ws::Text, client.read(msg));
  25506. EXPECT_EQ("Hello WSS", msg);
  25507. client.close();
  25508. }
  25509. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25510. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25511. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25512. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25513. // client (without calling close() first) is the only path that runs
  25514. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25515. // bug exactly.
  25516. //
  25517. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25518. // when linked against an instrumented libssl; run under Valgrind to catch it
  25519. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25520. // suite (the freed session otherwise stalls on the close handshake) — this test
  25521. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25522. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25523. {
  25524. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25525. "/ws-echo");
  25526. client.enable_server_certificate_verification(false);
  25527. client.set_read_timeout(2, 0);
  25528. client.set_write_timeout(2, 0);
  25529. ASSERT_TRUE(client.connect());
  25530. ASSERT_TRUE(client.is_open());
  25531. ASSERT_TRUE(client.send("still open"));
  25532. // Intentionally do NOT call client.close(): leaving scope runs
  25533. // shutdown_and_close() with the WebSocket still open, which must send the
  25534. // close frame while the TLS session is still alive.
  25535. }
  25536. }
  25537. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25538. // shutdown_and_close() at the start of connect(), reproducing the same
  25539. // use-after-free within the test body rather than at scope exit. The second
  25540. // connect must succeed and echo, proving the close handshake ran over a live
  25541. // session. See the note above about memory-tool requirements.
  25542. TEST_F(WebSocketSSLIntegrationTest,
  25543. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25544. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25545. "/ws-echo");
  25546. client.enable_server_certificate_verification(false);
  25547. client.set_read_timeout(2, 0);
  25548. client.set_write_timeout(2, 0);
  25549. ASSERT_TRUE(client.connect());
  25550. ASSERT_TRUE(client.is_open());
  25551. ASSERT_TRUE(client.send("still open"));
  25552. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25553. // the still-open connection, which must not touch a freed TLS session.
  25554. ASSERT_TRUE(client.connect());
  25555. ASSERT_TRUE(client.is_open());
  25556. ASSERT_TRUE(client.send("after reconnect"));
  25557. std::string msg;
  25558. EXPECT_EQ(ws::Text, client.read(msg));
  25559. EXPECT_EQ("after reconnect", msg);
  25560. client.close();
  25561. }
  25562. #endif
  25563. #ifdef CPPHTTPLIB_SSL_ENABLED
  25564. class WebSocketSSLCATest : public ::testing::Test {
  25565. protected:
  25566. void SetUp() override {
  25567. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25568. SERVER_PRIVATE_KEY_FILE);
  25569. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25570. std::string msg;
  25571. while (ws.read(msg)) {
  25572. ws.send(msg);
  25573. }
  25574. });
  25575. port_ = server_->bind_to_any_port("127.0.0.1");
  25576. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25577. server_->wait_until_ready();
  25578. }
  25579. void TearDown() override {
  25580. server_->stop();
  25581. if (server_thread_.joinable()) { server_thread_.join(); }
  25582. }
  25583. std::string url() const {
  25584. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25585. }
  25586. std::unique_ptr<SSLServer> server_;
  25587. std::thread server_thread_;
  25588. int port_ = 0;
  25589. };
  25590. // A custom CA loaded as PEM verifies the server with full certificate
  25591. // verification enabled
  25592. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25593. ws::WebSocketClient client(url());
  25594. std::string cert;
  25595. read_file(SERVER_CERT2_FILE, cert);
  25596. client.load_ca_cert_store(cert.c_str(), cert.size());
  25597. ASSERT_TRUE(client.connect());
  25598. ASSERT_TRUE(client.send("hello"));
  25599. std::string msg;
  25600. EXPECT_EQ(ws::Text, client.read(msg));
  25601. EXPECT_EQ("hello", msg);
  25602. client.close();
  25603. }
  25604. // A custom CA that does not cover the server must fail verification (the
  25605. // custom CA is exclusive; system certs are not loaded alongside it)
  25606. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25607. ws::WebSocketClient client(url());
  25608. std::string cert;
  25609. read_file(CLIENT_CA_CERT_FILE, cert);
  25610. client.load_ca_cert_store(cert.c_str(), cert.size());
  25611. auto res = client.connect();
  25612. ASSERT_FALSE(res);
  25613. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25614. EXPECT_EQ(-1, res.status());
  25615. EXPECT_NE(0u, res.ssl_backend_error());
  25616. }
  25617. // The same CA as a file path rather than PEM in memory
  25618. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25619. ws::WebSocketClient client(url());
  25620. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25621. ASSERT_TRUE(client.connect());
  25622. ASSERT_TRUE(client.send("hello"));
  25623. std::string msg;
  25624. EXPECT_EQ(ws::Text, client.read(msg));
  25625. EXPECT_EQ("hello", msg);
  25626. client.close();
  25627. }
  25628. // ...and a CA file that does not cover the server still fails, so it is the
  25629. // path above that decides the outcome
  25630. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25631. ws::WebSocketClient client(url());
  25632. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25633. ASSERT_FALSE(client.connect());
  25634. }
  25635. // Regression test: reconnecting with a native custom CA store used to reuse
  25636. // a store handle the previous TLS context had already freed (use-after-free
  25637. // under the OpenSSL backend). The context now lives as long as the client.
  25638. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25639. ws::WebSocketClient client(url());
  25640. std::string cert;
  25641. read_file(SERVER_CERT2_FILE, cert);
  25642. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25643. ASSERT_TRUE(client.connect());
  25644. client.close();
  25645. ASSERT_TRUE(client.connect());
  25646. ASSERT_TRUE(client.send("again"));
  25647. std::string msg;
  25648. EXPECT_EQ(ws::Text, client.read(msg));
  25649. EXPECT_EQ("again", msg);
  25650. client.close();
  25651. }
  25652. // Regression test: a certificate with a trusted chain but no identity match
  25653. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25654. // verification entirely for IP hosts, so this connection succeeded there.
  25655. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25656. // chain verification while the identity check must still fail.
  25657. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25659. ASSERT_TRUE(svr.is_valid());
  25660. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25661. std::string msg;
  25662. while (ws.read(msg)) {
  25663. ws.send(msg);
  25664. }
  25665. });
  25666. auto port = svr.bind_to_any_port("127.0.0.1");
  25667. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25668. auto se = detail::scope_exit([&] {
  25669. svr.stop();
  25670. t.join();
  25671. });
  25672. svr.wait_until_ready();
  25673. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25674. "/echo");
  25675. std::string cert;
  25676. read_file(SERVER_CERT_FILE, cert);
  25677. client.load_ca_cert_store(cert.c_str(), cert.size());
  25678. ASSERT_FALSE(client.connect());
  25679. }
  25680. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25681. // SNI, so nothing binds the host name to the TLS session. These bind the
  25682. // server to "localhost" instead, the only shape that exercises the SNI and
  25683. // hostname-verification path with certificate verification left enabled.
  25684. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25685. protected:
  25686. void Start(const char *cert_file) {
  25687. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25688. SERVER_PRIVATE_KEY_FILE);
  25689. ASSERT_TRUE(server_->is_valid());
  25690. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25691. std::string msg;
  25692. while (ws.read(msg)) {
  25693. ws.send(msg);
  25694. }
  25695. });
  25696. port_ = server_->bind_to_any_port("localhost");
  25697. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25698. server_->wait_until_ready();
  25699. }
  25700. void TearDown() override {
  25701. if (server_) { server_->stop(); }
  25702. if (server_thread_.joinable()) { server_thread_.join(); }
  25703. }
  25704. std::string url() const {
  25705. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25706. }
  25707. std::unique_ptr<SSLServer> server_;
  25708. std::thread server_thread_;
  25709. int port_ = 0;
  25710. };
  25711. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25712. // out and the connection is usable
  25713. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25714. Start(SERVER_CERT2_FILE);
  25715. ws::WebSocketClient client(url());
  25716. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25717. ASSERT_TRUE(client.connect());
  25718. ASSERT_TRUE(client.send("hello"));
  25719. std::string msg;
  25720. EXPECT_EQ(ws::Text, client.read(msg));
  25721. EXPECT_EQ("hello", msg);
  25722. client.close();
  25723. }
  25724. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25725. // while the identity check must still reject "localhost"
  25726. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25727. Start(SERVER_CERT_FILE);
  25728. ws::WebSocketClient client(url());
  25729. client.set_ca_cert_path(SERVER_CERT_FILE);
  25730. auto res = client.connect();
  25731. ASSERT_FALSE(res);
  25732. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25733. EXPECT_EQ(-1, res.status());
  25734. }
  25735. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25736. // disabled: the chain is still checked, only the identity check is skipped
  25737. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25738. Start(SERVER_CERT_FILE);
  25739. ws::WebSocketClient client(url());
  25740. client.set_ca_cert_path(SERVER_CERT_FILE);
  25741. client.enable_server_hostname_verification(false);
  25742. ASSERT_TRUE(client.connect());
  25743. ASSERT_TRUE(client.send("hello"));
  25744. std::string msg;
  25745. EXPECT_EQ(ws::Text, client.read(msg));
  25746. EXPECT_EQ("hello", msg);
  25747. client.close();
  25748. }
  25749. // A CA that did not sign the server certificate fails the chain, even though
  25750. // the name would match
  25751. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25752. Start(SERVER_CERT2_FILE);
  25753. ws::WebSocketClient client(url());
  25754. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25755. ASSERT_FALSE(client.connect());
  25756. }
  25757. // With verification disabled, neither the chain nor the name is checked
  25758. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25759. Start(SERVER_CERT_FILE);
  25760. ws::WebSocketClient client(url());
  25761. client.enable_server_certificate_verification(false);
  25762. ASSERT_TRUE(client.connect());
  25763. ASSERT_TRUE(client.send("hello"));
  25764. std::string msg;
  25765. EXPECT_EQ(ws::Text, client.read(msg));
  25766. EXPECT_EQ("hello", msg);
  25767. client.close();
  25768. }
  25769. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25770. protected:
  25771. void SetUp() override {
  25772. server_ = httplib::detail::make_unique<SSLServer>(
  25773. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25774. ASSERT_TRUE(server_->is_valid());
  25775. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25776. std::string msg;
  25777. while (ws.read(msg)) {
  25778. ws.send(msg);
  25779. }
  25780. });
  25781. port_ = server_->bind_to_any_port("localhost");
  25782. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25783. server_->wait_until_ready();
  25784. }
  25785. void TearDown() override {
  25786. server_->stop();
  25787. if (server_thread_.joinable()) { server_thread_.join(); }
  25788. }
  25789. std::string url() const {
  25790. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25791. }
  25792. void ConnectWithClientCert(const std::string &client_cert_file,
  25793. const std::string &client_private_key_file,
  25794. const char *private_key_password) {
  25795. std::string cert_pem, key_pem;
  25796. read_file(client_cert_file, cert_pem);
  25797. read_file(client_private_key_file, key_pem);
  25798. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25799. key_pem.c_str(), key_pem.size(),
  25800. private_key_password};
  25801. ConnectWithPem(pem);
  25802. }
  25803. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25804. ws::WebSocketClient client(url(), pem);
  25805. ASSERT_TRUE(client.is_valid());
  25806. client.enable_server_certificate_verification(false);
  25807. ASSERT_TRUE(client.connect());
  25808. ASSERT_TRUE(client.send("hello"));
  25809. std::string msg;
  25810. EXPECT_EQ(ws::Text, client.read(msg));
  25811. EXPECT_EQ("hello", msg);
  25812. client.close();
  25813. }
  25814. std::unique_ptr<SSLServer> server_;
  25815. std::thread server_thread_;
  25816. int port_ = 0;
  25817. };
  25818. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25819. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25820. }
  25821. // Control for the tests above: the fixture's server really does require a
  25822. // client certificate, so it is the PEM the constructor installed that decides
  25823. // the outcome.
  25824. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25825. ws::WebSocketClient client(url());
  25826. ASSERT_TRUE(client.is_valid());
  25827. client.enable_server_certificate_verification(false);
  25828. EXPECT_FALSE(client.connect());
  25829. }
  25830. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25831. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25832. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25833. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25834. }
  25835. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25836. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25837. std::string cert_pem, key_pem;
  25838. read_file(CLIENT_CERT_FILE, cert_pem);
  25839. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25840. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25841. std::vector<char> key(key_pem.begin(), key_pem.end());
  25842. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25843. key.size(), nullptr};
  25844. ConnectWithPem(pem);
  25845. }
  25846. #endif
  25847. #if !defined(_WIN32)
  25848. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25849. auto secret_dir = std::string("./symlink_test_secret");
  25850. auto served_dir = std::string("./symlink_test_served");
  25851. auto secret_file = secret_dir + "/secret.txt";
  25852. auto symlink_path = served_dir + "/escape";
  25853. // Setup: create directories and files
  25854. mkdir(secret_dir.c_str(), 0755);
  25855. mkdir(served_dir.c_str(), 0755);
  25856. {
  25857. std::ofstream ofs(secret_file);
  25858. ofs << "SECRET_DATA";
  25859. }
  25860. // Create symlink using absolute path so it resolves correctly
  25861. #ifdef PATH_MAX
  25862. char abs_secret[PATH_MAX];
  25863. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25864. #else
  25865. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25866. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25867. ASSERT_NE(nullptr, abs_secret);
  25868. #endif
  25869. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25870. auto se = detail::scope_exit([&] {
  25871. unlink(symlink_path.c_str());
  25872. unlink(secret_file.c_str());
  25873. rmdir(served_dir.c_str());
  25874. rmdir(secret_dir.c_str());
  25875. });
  25876. Server svr;
  25877. svr.set_mount_point("/", served_dir);
  25878. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25879. auto se2 = detail::scope_exit([&] {
  25880. svr.stop();
  25881. listen_thread.join();
  25882. });
  25883. svr.wait_until_ready();
  25884. Client cli("localhost", PORT);
  25885. // Symlink pointing outside base dir should be blocked
  25886. auto res = cli.Get("/escape/secret.txt");
  25887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25888. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25889. }
  25890. #endif
  25891. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25892. // "GET /smuggled" request), reads the first response, and only then sends the
  25893. // embedded request as the body. Returns how many times /smuggled ran.
  25894. //
  25895. // The body is sent AFTER receiving the first response (as in the original
  25896. // PoC) so that the stream_line_reader cannot buffer it together with the
  25897. // headers of the first request.
  25898. static int count_smuggled_requests(const std::string &outer_head,
  25899. std::string &first_response) {
  25900. Server svr;
  25901. svr.set_mount_point("/", "./www");
  25902. std::atomic<int> smuggled_count(0);
  25903. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25904. smuggled_count++;
  25905. res.set_content("oops", "text/plain");
  25906. });
  25907. svr.Post("/post", [&](const Request &req, Response &res) {
  25908. res.set_content(req.body, "text/plain");
  25909. });
  25910. auto port = svr.bind_to_any_port("localhost");
  25911. thread t = thread([&] { svr.listen_after_bind(); });
  25912. auto se = detail::scope_exit([&] {
  25913. svr.stop();
  25914. t.join();
  25915. });
  25916. svr.wait_until_ready();
  25917. auto error = Error::Success;
  25918. auto sock = detail::create_client_socket(
  25919. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25920. /*connection_timeout_sec=*/2, 0,
  25921. /*read_timeout_sec=*/2, 0,
  25922. /*write_timeout_sec=*/2, 0, std::string(), error);
  25923. EXPECT_NE(INVALID_SOCKET, sock);
  25924. if (sock == INVALID_SOCKET) { return -1; }
  25925. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25926. // The "smuggled" request will be sent as the body of the outer request
  25927. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25928. "Host: localhost\r\n"
  25929. "Connection: close\r\n"
  25930. "\r\n";
  25931. auto head = outer_head;
  25932. auto len = std::to_string(smuggled.size());
  25933. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25934. pos = head.find("{len}", pos + len.size())) {
  25935. head.replace(pos, 5, len);
  25936. }
  25937. // Step 1: Send only the outer request headers (no body yet)
  25938. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25939. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25940. // Step 2: Read the first response
  25941. char buf[4096];
  25942. for (;;) {
  25943. auto n = recv(sock, buf, sizeof(buf), 0);
  25944. if (n <= 0) break;
  25945. first_response.append(buf, static_cast<size_t>(n));
  25946. // Stop once we have a complete response (headers + body)
  25947. auto hdr_end = first_response.find("\r\n\r\n");
  25948. if (hdr_end != std::string::npos) {
  25949. // Check for Content-Length to know when the body is complete
  25950. auto cl_pos = first_response.find("Content-Length:");
  25951. if (cl_pos != std::string::npos) {
  25952. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25953. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25954. auto cl = std::stoul(
  25955. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25956. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25957. } else {
  25958. break; // No Content-Length, assume headers-only response
  25959. }
  25960. }
  25961. }
  25962. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25963. // vulnerable server the keep-alive loop reads this as a second request. The
  25964. // server may already have closed the connection, so the result is ignored.
  25965. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25966. // Half-close so that a server which drained the body sees EOF and closes,
  25967. // instead of the read below waiting for the read timeout.
  25968. #ifdef _WIN32
  25969. ::shutdown(sock, SD_SEND);
  25970. #else
  25971. ::shutdown(sock, SHUT_WR);
  25972. #endif
  25973. // Step 4: Read until the server closes the connection
  25974. for (;;) {
  25975. auto n = recv(sock, buf, sizeof(buf), 0);
  25976. if (n <= 0) break;
  25977. }
  25978. return smuggled_count.load();
  25979. }
  25980. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25981. // A GET request with Content-Length to a static file handler must have its
  25982. // body drained before the keep-alive connection is reused. Otherwise the
  25983. // unread body bytes are interpreted as the next HTTP request.
  25984. std::string first_response;
  25985. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25986. "Host: localhost\r\n"
  25987. "Content-Length: {len}\r\n"
  25988. "\r\n",
  25989. first_response));
  25990. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25991. }
  25992. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25993. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25994. // be answered with 400 and the connection closed. Treating it as "no body"
  25995. // leaves the body to be parsed as the next request.
  25996. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25997. const char *targets[] = {
  25998. "GET /file", // handler that never reads the body
  25999. "GET /not-found", // no handler matches (404)
  26000. "POST /post", // handler that reads the body
  26001. };
  26002. for (auto target : targets) {
  26003. for (auto value : values) {
  26004. std::string first_response;
  26005. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26006. " HTTP/1.1\r\n"
  26007. "Host: localhost\r\n"
  26008. "Content-Length: " +
  26009. value + "\r\n\r\n",
  26010. first_response))
  26011. << target << " with Content-Length: " << value;
  26012. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  26013. << target << " with Content-Length: " << value;
  26014. }
  26015. }
  26016. }
  26017. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  26018. // A 400 for an unparseable request line leaves the rest of the message
  26019. // unread, so the connection must be closed rather than reused.
  26020. std::string first_response;
  26021. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  26022. "Host: localhost\r\n"
  26023. "Content-Length: {len}\r\n"
  26024. "\r\n",
  26025. first_response));
  26026. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26027. }
  26028. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  26029. // Same as above for a header block that fails to parse.
  26030. std::string first_response;
  26031. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26032. "Host: localhost\r\n"
  26033. "Bad Header\r\n"
  26034. "Content-Length: {len}\r\n"
  26035. "\r\n",
  26036. first_response));
  26037. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26038. }
  26039. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  26040. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  26041. // server must not read another request on that connection, even when the
  26042. // request had no body to drain.
  26043. std::string first_response;
  26044. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  26045. "Host: localhost\r\n"
  26046. "\r\n",
  26047. first_response));
  26048. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26049. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26050. }
  26051. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26052. // A content reader that stops early leaves the stream inside the body.
  26053. // Draining the whole Content-Length from there, or reading the body again,
  26054. // reads into the next request, and whatever follows is parsed as a request
  26055. // of its own.
  26056. Server svr;
  26057. std::atomic<int> smuggled_count(0);
  26058. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26059. svr.Post("/upload", [](const Request &req, Response &res,
  26060. const ContentReader &content_reader) {
  26061. // Stop at the last chunk, so the whole body has been read however it
  26062. // arrives.
  26063. auto length = req.get_header_value_u64("Content-Length");
  26064. size_t total = 0;
  26065. auto consumed = content_reader([&](const char *, size_t n) {
  26066. total += n;
  26067. return total < length;
  26068. });
  26069. EXPECT_FALSE(consumed);
  26070. if (req.has_param("retry")) {
  26071. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26072. }
  26073. // Replace the 400 the aborted read set, which would close the connection.
  26074. res.set_redirect("/done");
  26075. });
  26076. auto port = svr.bind_to_any_port(HOST);
  26077. thread t = thread([&] { svr.listen_after_bind(); });
  26078. auto se = detail::scope_exit([&] {
  26079. svr.stop();
  26080. t.join();
  26081. });
  26082. svr.wait_until_ready();
  26083. // A front end sees the second request as a POST whose body is the GET. The
  26084. // first body is as long as the POST's headers, so draining it again reads
  26085. // exactly those and leaves the GET to be parsed next.
  26086. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26087. "Host: localhost\r\n"
  26088. "\r\n";
  26089. std::string second_head = "POST /post HTTP/1.1\r\n"
  26090. "Host: localhost\r\n"
  26091. "Content-Length: " +
  26092. std::to_string(inner.size()) +
  26093. "\r\n"
  26094. "\r\n";
  26095. for (auto target : {"/upload", "/upload?retry"}) {
  26096. smuggled_count = 0;
  26097. std::string request = "POST " + std::string(target) +
  26098. " HTTP/1.1\r\n"
  26099. "Host: localhost\r\n"
  26100. "Content-Length: " +
  26101. std::to_string(second_head.size()) +
  26102. "\r\n"
  26103. "\r\n" +
  26104. std::string(second_head.size(), 'A') + second_head +
  26105. inner;
  26106. std::string response;
  26107. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26108. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26109. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26110. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26111. EXPECT_EQ(0, smuggled_count.load()) << target;
  26112. }
  26113. }
  26114. // An error response closes the connection anyway, so the body is left unread
  26115. // with a redirect, such as one to a login page.
  26116. static void serve_redirects(Server &svr,
  26117. const std::function<void(int)> &client) {
  26118. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26119. res.set_redirect("/login");
  26120. return Server::HandlerResponse::Handled;
  26121. });
  26122. auto port = svr.bind_to_any_port(HOST);
  26123. ASSERT_GT(port, 0);
  26124. thread t = thread([&] { svr.listen_after_bind(); });
  26125. auto se = detail::scope_exit([&] {
  26126. svr.stop();
  26127. t.join();
  26128. ASSERT_FALSE(svr.is_running());
  26129. });
  26130. svr.wait_until_ready();
  26131. client(port);
  26132. }
  26133. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26134. Server svr;
  26135. serve_redirects(svr, [](int port) {
  26136. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26137. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26138. std::to_string(body.size()) + "\r\n\r\n" + body +
  26139. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26140. std::string resp;
  26141. ASSERT_TRUE(send_request(1, req, &resp, port));
  26142. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26143. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26144. });
  26145. }
  26146. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26147. Server svr;
  26148. svr.set_read_timeout(0, 200000);
  26149. serve_redirects(svr, [](int port) {
  26150. // A byte every 100 ms keeps each read within the read timeout, but not the
  26151. // body as a whole, so the server closes and the bytes sent after that fail.
  26152. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26153. "Content-Length: 10\r\n\r\n"};
  26154. parts.resize(11, "x");
  26155. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26156. });
  26157. }
  26158. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26159. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26160. // must be rejected with 400 Bad Request.
  26161. Server svr;
  26162. svr.Post("/test", [&](const Request &, Response &res) {
  26163. res.set_content("ok", "text/plain");
  26164. });
  26165. thread t = thread([&] { svr.listen(HOST, PORT); });
  26166. auto se = detail::scope_exit([&] {
  26167. svr.stop();
  26168. t.join();
  26169. ASSERT_FALSE(svr.is_running());
  26170. });
  26171. svr.wait_until_ready();
  26172. // Exact "chunked"
  26173. {
  26174. auto req = "POST /test HTTP/1.1\r\n"
  26175. "Host: localhost\r\n"
  26176. "Content-Length: 5\r\n"
  26177. "Transfer-Encoding: chunked\r\n"
  26178. "Connection: close\r\n"
  26179. "\r\n"
  26180. "hello";
  26181. std::string response;
  26182. ASSERT_TRUE(send_request(1, req, &response));
  26183. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26184. response.substr(0, response.find("\r\n")));
  26185. }
  26186. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26187. {
  26188. auto req = "POST /test HTTP/1.1\r\n"
  26189. "Host: localhost\r\n"
  26190. "Content-Length: 5\r\n"
  26191. "Transfer-Encoding: gzip, chunked\r\n"
  26192. "Connection: close\r\n"
  26193. "\r\n"
  26194. "hello";
  26195. std::string response;
  26196. ASSERT_TRUE(send_request(1, req, &response));
  26197. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26198. response.substr(0, response.find("\r\n")));
  26199. }
  26200. }
  26201. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26202. Server svr;
  26203. svr.Post("/test", [&](const Request &, Response &res) {
  26204. res.set_content("ok", "text/plain");
  26205. });
  26206. thread t = thread([&] { svr.listen(HOST, PORT); });
  26207. auto se = detail::scope_exit([&] {
  26208. svr.stop();
  26209. t.join();
  26210. ASSERT_FALSE(svr.is_running());
  26211. });
  26212. svr.wait_until_ready();
  26213. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26214. // length cannot be determined, so the server must answer 400 and close
  26215. // rather than treat the request as bodyless and leave the body in the
  26216. // socket for the next request to pick up.
  26217. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26218. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26219. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26220. std::string response;
  26221. ASSERT_TRUE(send_request(1, req, &response));
  26222. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26223. response.substr(0, response.find("\r\n")))
  26224. << transfer_encoding;
  26225. }
  26226. // RFC 9110 5.3: the codings may also be split across several
  26227. // Transfer-Encoding lines, which combine in the order they were received.
  26228. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26229. // just like the single-line "chunked, gzip" above.
  26230. {
  26231. auto req = "POST /test HTTP/1.1\r\n"
  26232. "Host: localhost\r\n"
  26233. "Transfer-Encoding: chunked\r\n"
  26234. "Transfer-Encoding: gzip\r\n"
  26235. "\r\n"
  26236. "0\r\n\r\n";
  26237. std::string response;
  26238. ASSERT_TRUE(send_request(1, req, &response));
  26239. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26240. response.substr(0, response.find("\r\n")));
  26241. }
  26242. }
  26243. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26244. Server svr;
  26245. svr.Post("/test", [&](const Request &, Response &res) {
  26246. res.set_content("ok", "text/plain");
  26247. });
  26248. auto port = svr.bind_to_any_port(HOST);
  26249. ASSERT_GT(port, 0);
  26250. thread t = thread([&] { svr.listen_after_bind(); });
  26251. auto se = detail::scope_exit([&] {
  26252. svr.stop();
  26253. t.join();
  26254. ASSERT_FALSE(svr.is_running());
  26255. });
  26256. svr.wait_until_ready();
  26257. for (auto transfer_encoding :
  26258. {"Transfer-Encoding: gzip, chunked\r\n",
  26259. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26260. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26261. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26262. transfer_encoding + "\r\n0\r\n\r\n";
  26263. std::string response;
  26264. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26265. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26266. response.substr(0, response.find("\r\n")))
  26267. << transfer_encoding;
  26268. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26269. << transfer_encoding;
  26270. }
  26271. }
  26272. // Regression for issue #2450: a DELETE without Content-Length on a
  26273. // keep-alive connection must not let the post-response drain consume the
  26274. // next request's bytes.
  26275. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26276. Server svr;
  26277. std::atomic<int> delete_count(0);
  26278. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26279. delete_count++;
  26280. res.status = StatusCode::NoContent_204;
  26281. });
  26282. auto port = svr.bind_to_any_port(HOST);
  26283. thread t = thread([&] { svr.listen_after_bind(); });
  26284. auto se = detail::scope_exit([&] {
  26285. svr.stop();
  26286. t.join();
  26287. });
  26288. svr.wait_until_ready();
  26289. auto error = Error::Success;
  26290. auto sock = detail::create_client_socket(
  26291. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26292. /*connection_timeout_sec=*/2, 0,
  26293. /*read_timeout_sec=*/2, 0,
  26294. /*write_timeout_sec=*/2, 0, std::string(), error);
  26295. ASSERT_NE(INVALID_SOCKET, sock);
  26296. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26297. auto send_request_and_read_response = [&](const std::string &req,
  26298. std::string &out) -> bool {
  26299. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26300. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26301. char buf[4096];
  26302. for (;;) {
  26303. auto n = recv(sock, buf, sizeof(buf), 0);
  26304. if (n <= 0) { return !out.empty(); }
  26305. out.append(buf, static_cast<size_t>(n));
  26306. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26307. }
  26308. };
  26309. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26310. "Host: localhost\r\n"
  26311. "\r\n";
  26312. std::string resp1;
  26313. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26314. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26315. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26316. "Host: localhost\r\n"
  26317. "Connection: close\r\n"
  26318. "\r\n";
  26319. std::string resp2;
  26320. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26321. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26322. EXPECT_EQ(2, delete_count.load());
  26323. }
  26324. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26325. Server svr;
  26326. svr.Post("/ingest", [&](const Request &, Response &res,
  26327. const ContentReader &content_reader) {
  26328. auto consumed = content_reader([](const char *, size_t) { return false; });
  26329. EXPECT_FALSE(consumed);
  26330. res.status = StatusCode::Conflict_409;
  26331. res.set_header("Connection", "close");
  26332. });
  26333. auto port = svr.bind_to_any_port(HOST);
  26334. thread t = thread([&] { svr.listen_after_bind(); });
  26335. auto se = detail::scope_exit([&] {
  26336. svr.stop();
  26337. t.join();
  26338. });
  26339. svr.wait_until_ready();
  26340. auto error = Error::Success;
  26341. auto sock = detail::create_client_socket(
  26342. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26343. /*connection_timeout_sec=*/2, 0,
  26344. /*read_timeout_sec=*/1, 0,
  26345. /*write_timeout_sec=*/2, 0, std::string(), error);
  26346. ASSERT_NE(INVALID_SOCKET, sock);
  26347. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26348. std::string request = "POST /ingest HTTP/1.1\r\n"
  26349. "Host: localhost\r\n"
  26350. "Transfer-Encoding: chunked\r\n"
  26351. "\r\n"
  26352. "4\r\n"
  26353. "data\r\n";
  26354. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26355. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26356. std::string response;
  26357. ssize_t received = 0;
  26358. do {
  26359. char buf[4096];
  26360. received = recv(sock, buf, sizeof(buf), 0);
  26361. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26362. } while (received > 0);
  26363. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26364. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26365. EXPECT_EQ(0, received);
  26366. }
  26367. namespace no_proxy_test {
  26368. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26369. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26370. // calling listen().
  26371. class ScopedServer {
  26372. public:
  26373. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26374. ~ScopedServer() {
  26375. svr_.stop();
  26376. if (th_.joinable()) { th_.join(); }
  26377. }
  26378. Server &svr() { return svr_; }
  26379. int port() const { return port_; }
  26380. void listen() {
  26381. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26382. svr_.wait_until_ready();
  26383. }
  26384. private:
  26385. Server svr_;
  26386. std::thread th_;
  26387. int port_ = 0;
  26388. };
  26389. class ProxyAndTargetServers {
  26390. public:
  26391. ProxyAndTargetServers() {
  26392. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26393. proxy_hits_++;
  26394. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26395. res.set_content("via-proxy", "text/plain");
  26396. });
  26397. target_.Get(".*", [this](const Request &req, Response &res) {
  26398. target_hits_++;
  26399. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26400. res.set_content("direct", "text/plain");
  26401. });
  26402. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26403. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26404. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26405. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26406. proxy_mock_.wait_until_ready();
  26407. target_.wait_until_ready();
  26408. }
  26409. ~ProxyAndTargetServers() {
  26410. proxy_mock_.stop();
  26411. target_.stop();
  26412. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26413. if (target_thread_.joinable()) { target_thread_.join(); }
  26414. }
  26415. Server &proxy_mock() { return proxy_mock_; }
  26416. Server &target() { return target_; }
  26417. int proxy_port() const { return proxy_port_; }
  26418. int target_port() const { return target_port_; }
  26419. int proxy_hits() const { return proxy_hits_.load(); }
  26420. int target_hits() const { return target_hits_.load(); }
  26421. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26422. void reset_counters() {
  26423. proxy_hits_ = 0;
  26424. target_hits_ = 0;
  26425. last_had_proxy_authz_ = false;
  26426. }
  26427. private:
  26428. Server proxy_mock_;
  26429. Server target_;
  26430. std::thread proxy_thread_;
  26431. std::thread target_thread_;
  26432. int proxy_port_ = 0;
  26433. int target_port_ = 0;
  26434. std::atomic<int> proxy_hits_{0};
  26435. std::atomic<int> target_hits_{0};
  26436. std::atomic<bool> last_had_proxy_authz_{false};
  26437. };
  26438. inline std::unique_ptr<Client> make_client(const std::string &host,
  26439. ProxyAndTargetServers &s) {
  26440. auto cli = detail::make_unique<Client>(host, s.target_port());
  26441. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26442. cli->set_proxy("127.0.0.1", s.proxy_port());
  26443. return cli;
  26444. }
  26445. } // namespace no_proxy_test
  26446. using no_proxy_test::make_client;
  26447. using no_proxy_test::ProxyAndTargetServers;
  26448. // A stream request carries the credentials a buffered request does
  26449. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26450. no_proxy_test::ScopedServer origin;
  26451. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26452. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26453. });
  26454. origin.listen();
  26455. Client cli("127.0.0.1", origin.port());
  26456. cli.set_basic_auth("user", "pass");
  26457. auto handle = cli.open_stream("GET", "/x");
  26458. ASSERT_TRUE(handle.is_valid());
  26459. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26460. Client bearer("127.0.0.1", origin.port());
  26461. bearer.set_bearer_token_auth("tok");
  26462. auto handle2 = bearer.open_stream("GET", "/x");
  26463. ASSERT_TRUE(handle2.is_valid());
  26464. EXPECT_EQ("Bearer tok", read_all(handle2));
  26465. }
  26466. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26467. // takes its own credentials, as for a buffered request
  26468. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26469. std::string target, authz, proxy_authz;
  26470. no_proxy_test::ScopedServer proxy;
  26471. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26472. target = req.target;
  26473. authz = req.get_header_value("Authorization");
  26474. proxy_authz = req.get_header_value("Proxy-Authorization");
  26475. res.set_content("ok", "text/plain");
  26476. });
  26477. proxy.listen();
  26478. Client cli("origin.example", 8080);
  26479. cli.set_proxy("127.0.0.1", proxy.port());
  26480. cli.set_proxy_basic_auth("puser", "ppass");
  26481. cli.set_basic_auth("user", "pass");
  26482. auto handle = cli.open_stream("GET", "/x");
  26483. ASSERT_TRUE(handle.is_valid());
  26484. EXPECT_EQ("ok", read_all(handle));
  26485. EXPECT_EQ("http://origin.example:8080/x", target);
  26486. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26487. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26488. }
  26489. // In absolute-form the path follows the authority, so a path that does not
  26490. // begin with '/' would make the proxy connect to another host
  26491. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26492. std::vector<std::string> targets;
  26493. no_proxy_test::ScopedServer proxy;
  26494. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26495. targets.push_back(req.target);
  26496. res.set_content("ok", "text/plain");
  26497. });
  26498. proxy.listen();
  26499. Client cli("origin.example", 8080);
  26500. cli.set_proxy("127.0.0.1", proxy.port());
  26501. cli.set_basic_auth("user", "pass");
  26502. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26503. auto res = cli.Get(path);
  26504. EXPECT_FALSE(res) << path;
  26505. auto handle = cli.open_stream("GET", path);
  26506. EXPECT_FALSE(handle.is_valid()) << path;
  26507. }
  26508. EXPECT_TRUE(targets.empty());
  26509. auto res = cli.Get("/x");
  26510. ASSERT_TRUE(res);
  26511. ASSERT_EQ(1u, targets.size());
  26512. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26513. }
  26514. TEST(NoProxyTest, ExactHostnameBypasses) {
  26515. ProxyAndTargetServers s;
  26516. auto cli = make_client("example.com", s);
  26517. cli->set_no_proxy({"example.com"});
  26518. auto res = cli->Get("/");
  26519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26520. EXPECT_EQ(0, s.proxy_hits());
  26521. EXPECT_EQ(1, s.target_hits());
  26522. }
  26523. TEST(NoProxyTest, SubdomainBypasses) {
  26524. ProxyAndTargetServers s;
  26525. auto cli = make_client("foo.example.com", s);
  26526. cli->set_no_proxy({"example.com"});
  26527. auto res = cli->Get("/");
  26528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26529. EXPECT_EQ(0, s.proxy_hits());
  26530. EXPECT_EQ(1, s.target_hits());
  26531. }
  26532. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26533. // Regression guard: "evilexample.com" must not be considered a subdomain
  26534. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26535. // check would let traffic bypass the proxy and leak credentials direct
  26536. // to the attacker host.
  26537. ProxyAndTargetServers s;
  26538. auto cli = make_client("evilexample.com", s);
  26539. cli->set_no_proxy({"example.com"});
  26540. auto res = cli->Get("/");
  26541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26542. EXPECT_GE(s.proxy_hits(), 1);
  26543. EXPECT_EQ(0, s.target_hits());
  26544. }
  26545. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26546. ProxyAndTargetServers s;
  26547. auto cli = make_client("example.com.evil.com", s);
  26548. cli->set_no_proxy({"example.com"});
  26549. auto res = cli->Get("/");
  26550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26551. EXPECT_GE(s.proxy_hits(), 1);
  26552. EXPECT_EQ(0, s.target_hits());
  26553. }
  26554. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26555. ProxyAndTargetServers s;
  26556. auto cli = make_client("example.com", s);
  26557. cli->set_no_proxy({".example.com"});
  26558. auto res = cli->Get("/");
  26559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26560. EXPECT_EQ(0, s.proxy_hits());
  26561. EXPECT_EQ(1, s.target_hits());
  26562. }
  26563. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26564. ProxyAndTargetServers s;
  26565. auto cli = make_client("Example.COM", s);
  26566. cli->set_no_proxy({"EXAMPLE.com"});
  26567. auto res = cli->Get("/");
  26568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26569. EXPECT_EQ(0, s.proxy_hits());
  26570. EXPECT_EQ(1, s.target_hits());
  26571. }
  26572. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26573. ProxyAndTargetServers s;
  26574. auto cli = make_client("example.com.", s);
  26575. cli->set_no_proxy({"example.com"});
  26576. auto res = cli->Get("/");
  26577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26578. EXPECT_EQ(0, s.proxy_hits());
  26579. EXPECT_EQ(1, s.target_hits());
  26580. }
  26581. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26582. // Trailing dots must be normalized on BOTH sides — host and entry.
  26583. // An implementation that only strips the host-side trailing dot would
  26584. // fail to match host "example.com" against entry "example.com." because
  26585. // a literal substring search would compare 11 chars against 12.
  26586. ProxyAndTargetServers s;
  26587. auto cli = make_client("example.com", s);
  26588. cli->set_no_proxy({"example.com."});
  26589. auto res = cli->Get("/");
  26590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26591. EXPECT_EQ(0, s.proxy_hits());
  26592. EXPECT_EQ(1, s.target_hits());
  26593. }
  26594. TEST(NoProxyTest, WildcardBypassesEverything) {
  26595. ProxyAndTargetServers s;
  26596. auto cli = make_client("anything.invalid.test", s);
  26597. cli->set_no_proxy({"*"});
  26598. auto res = cli->Get("/");
  26599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26600. EXPECT_EQ(0, s.proxy_hits());
  26601. EXPECT_EQ(1, s.target_hits());
  26602. }
  26603. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26604. ProxyAndTargetServers s;
  26605. Client cli("127.0.0.1", s.target_port());
  26606. cli.set_proxy("127.0.0.1", s.proxy_port());
  26607. cli.set_no_proxy({"127.0.0.1"});
  26608. auto res = cli.Get("/");
  26609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26610. EXPECT_EQ(0, s.proxy_hits());
  26611. EXPECT_EQ(1, s.target_hits());
  26612. }
  26613. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26614. ProxyAndTargetServers s;
  26615. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26616. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26617. cli.set_proxy("127.0.0.1", s.proxy_port());
  26618. cli.set_no_proxy({"::1"});
  26619. auto res = cli.Get("/");
  26620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26621. EXPECT_EQ(0, s.proxy_hits());
  26622. EXPECT_EQ(1, s.target_hits());
  26623. }
  26624. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26625. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26626. // must still be recognized as IPv6 for CIDR matching. Implementations
  26627. // that detect IPv6 only when the host begins with '[' would parse the
  26628. // host as a hostname and miss the match.
  26629. ProxyAndTargetServers s;
  26630. Client cli("fe80::1", s.target_port());
  26631. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26632. cli.set_proxy("127.0.0.1", s.proxy_port());
  26633. cli.set_no_proxy({"fe80::/10"});
  26634. auto res = cli.Get("/");
  26635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26636. EXPECT_EQ(0, s.proxy_hits());
  26637. EXPECT_EQ(1, s.target_hits());
  26638. }
  26639. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26640. ProxyAndTargetServers s;
  26641. Client cli("::1", s.target_port());
  26642. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26643. cli.set_proxy("127.0.0.1", s.proxy_port());
  26644. cli.set_no_proxy({"[::1]"});
  26645. auto res = cli.Get("/");
  26646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26647. EXPECT_EQ(0, s.proxy_hits());
  26648. EXPECT_EQ(1, s.target_hits());
  26649. }
  26650. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26651. ProxyAndTargetServers s;
  26652. Client cli("fe80::1", s.target_port());
  26653. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26654. cli.set_proxy("127.0.0.1", s.proxy_port());
  26655. cli.set_no_proxy({"[fe80::]/10"});
  26656. auto res = cli.Get("/");
  26657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26658. EXPECT_EQ(0, s.proxy_hits());
  26659. EXPECT_EQ(1, s.target_hits());
  26660. }
  26661. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26662. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26663. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26664. // tricks via address-family conversion.
  26665. ProxyAndTargetServers s;
  26666. Client cli("::ffff:127.0.0.1", s.target_port());
  26667. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26668. cli.set_proxy("127.0.0.1", s.proxy_port());
  26669. cli.set_no_proxy({"127.0.0.1"});
  26670. auto res = cli.Get("/");
  26671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26672. EXPECT_GE(s.proxy_hits(), 1);
  26673. EXPECT_EQ(0, s.target_hits());
  26674. }
  26675. TEST(NoProxyTest, IPv4CidrMatch) {
  26676. ProxyAndTargetServers s;
  26677. Client cli("127.0.0.1", s.target_port());
  26678. cli.set_proxy("127.0.0.1", s.proxy_port());
  26679. cli.set_no_proxy({"127.0.0.0/8"});
  26680. auto res = cli.Get("/");
  26681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26682. EXPECT_EQ(0, s.proxy_hits());
  26683. EXPECT_EQ(1, s.target_hits());
  26684. }
  26685. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26686. ProxyAndTargetServers s;
  26687. Client cli("127.0.0.1", s.target_port());
  26688. cli.set_proxy("127.0.0.1", s.proxy_port());
  26689. cli.set_no_proxy({"10.0.0.0/8"});
  26690. auto res = cli.Get("/");
  26691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26692. EXPECT_GE(s.proxy_hits(), 1);
  26693. EXPECT_EQ(0, s.target_hits());
  26694. }
  26695. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26696. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26697. // IPv4 target matches.
  26698. ProxyAndTargetServers s;
  26699. Client cli("127.0.0.1", s.target_port());
  26700. cli.set_proxy("127.0.0.1", s.proxy_port());
  26701. cli.set_no_proxy({"0.0.0.0/0"});
  26702. auto res = cli.Get("/");
  26703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26704. EXPECT_EQ(0, s.proxy_hits());
  26705. EXPECT_EQ(1, s.target_hits());
  26706. }
  26707. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26708. ProxyAndTargetServers s;
  26709. Client cli("127.0.0.1", s.target_port());
  26710. cli.set_proxy("127.0.0.1", s.proxy_port());
  26711. cli.set_no_proxy({"127.0.0.1"});
  26712. auto res = cli.Get("/");
  26713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26714. EXPECT_EQ(0, s.proxy_hits());
  26715. EXPECT_EQ(1, s.target_hits());
  26716. }
  26717. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26718. ProxyAndTargetServers s;
  26719. Client cli("127.0.0.1", s.target_port());
  26720. cli.set_proxy("127.0.0.1", s.proxy_port());
  26721. cli.set_no_proxy({"127.0.0.0/33"});
  26722. auto res = cli.Get("/");
  26723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26724. EXPECT_GE(s.proxy_hits(), 1);
  26725. EXPECT_EQ(0, s.target_hits());
  26726. }
  26727. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26728. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26729. ProxyAndTargetServers s;
  26730. Client cli("127.0.0.1", s.target_port());
  26731. cli.set_proxy("127.0.0.1", s.proxy_port());
  26732. cli.set_no_proxy({"127.0.0.1/"});
  26733. auto res = cli.Get("/");
  26734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26735. EXPECT_GE(s.proxy_hits(), 1);
  26736. EXPECT_EQ(0, s.target_hits());
  26737. }
  26738. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26739. ProxyAndTargetServers s;
  26740. auto cli = make_client("internal.corp", s);
  26741. cli->set_proxy_basic_auth("u", "p");
  26742. cli->set_no_proxy({"internal.corp"});
  26743. auto res = cli->Get("/");
  26744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26745. EXPECT_EQ(1, s.target_hits());
  26746. EXPECT_EQ(0, s.proxy_hits());
  26747. EXPECT_FALSE(s.last_had_proxy_authz())
  26748. << "Proxy-Authorization must not be sent direct to the target";
  26749. }
  26750. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26751. ProxyAndTargetServers s;
  26752. auto cli = make_client("public.example", s);
  26753. cli->set_proxy_basic_auth("u", "p");
  26754. cli->set_no_proxy({"internal.corp"}); // does not match
  26755. auto res = cli->Get("/");
  26756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26757. EXPECT_GE(s.proxy_hits(), 1);
  26758. EXPECT_TRUE(s.last_had_proxy_authz());
  26759. }
  26760. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26761. std::atomic<int> hits{0};
  26762. std::atomic<int> hits_with_authz{0};
  26763. no_proxy_test::ScopedServer proxy_mock;
  26764. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26765. hits++;
  26766. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26767. if (req.target.find("/redir") != std::string::npos) {
  26768. res.set_redirect("http://other.example/landed");
  26769. } else {
  26770. res.set_content("via-proxy", "text/plain");
  26771. }
  26772. });
  26773. proxy_mock.listen();
  26774. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26775. hits = 0;
  26776. hits_with_authz = 0;
  26777. Client cli("public.example", 80);
  26778. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26779. cli.set_proxy_basic_auth(c.first, c.second);
  26780. cli.set_follow_location(true);
  26781. // The redirect to another host goes through the proxy as well
  26782. auto res = cli.Get("/redir");
  26783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26784. EXPECT_EQ(2, hits.load());
  26785. EXPECT_EQ(2, hits_with_authz.load());
  26786. }
  26787. }
  26788. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26789. ProxyAndTargetServers s;
  26790. auto cli = make_client("anything.test", s);
  26791. auto res = cli->Get("/");
  26792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26793. EXPECT_GE(s.proxy_hits(), 1);
  26794. EXPECT_EQ(0, s.target_hits());
  26795. }
  26796. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26797. ProxyAndTargetServers s;
  26798. auto cli = make_client("example.com", s);
  26799. cli->set_no_proxy({"example.com:8080"});
  26800. auto res = cli->Get("/");
  26801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26802. EXPECT_GE(s.proxy_hits(), 1);
  26803. EXPECT_EQ(0, s.target_hits());
  26804. }
  26805. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26806. ProxyAndTargetServers s;
  26807. auto cli = make_client("anything.test", s);
  26808. cli->set_no_proxy({"", " ", "\t"});
  26809. auto res = cli->Get("/");
  26810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26811. EXPECT_GE(s.proxy_hits(), 1);
  26812. EXPECT_EQ(0, s.target_hits());
  26813. }
  26814. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26815. // An entry with leading/trailing whitespace must still match — env-style
  26816. // values are commonly pasted with stray spaces and an implementation
  26817. // that feeds the raw token directly to inet_pton would fail to match
  26818. // valid CIDRs because of the spaces.
  26819. ProxyAndTargetServers s;
  26820. Client cli("127.0.0.1", s.target_port());
  26821. cli.set_proxy("127.0.0.1", s.proxy_port());
  26822. cli.set_no_proxy({" 127.0.0.0/8 "});
  26823. auto res = cli.Get("/");
  26824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26825. EXPECT_EQ(0, s.proxy_hits());
  26826. EXPECT_EQ(1, s.target_hits());
  26827. }
  26828. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26829. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26830. // go direct and must NOT carry Proxy-Authorization.
  26831. std::atomic<int> proxy_hits{0};
  26832. std::atomic<int> target_hits{0};
  26833. std::atomic<bool> target_saw_authz{false};
  26834. no_proxy_test::ScopedServer proxy_mock, target;
  26835. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26836. proxy_hits++;
  26837. res.status = 302;
  26838. res.set_header("Location", "http://127.0.0.1:" +
  26839. std::to_string(target.port()) + "/landed");
  26840. });
  26841. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26842. target_hits++;
  26843. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26844. res.set_content("direct", "text/plain");
  26845. });
  26846. proxy_mock.listen();
  26847. target.listen();
  26848. Client cli("public.example", target.port());
  26849. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26850. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26851. cli.set_proxy_basic_auth("u", "p");
  26852. cli.set_no_proxy({"127.0.0.1"});
  26853. cli.set_follow_location(true);
  26854. auto res = cli.Get("/redir");
  26855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26856. EXPECT_GE(proxy_hits.load(), 1);
  26857. EXPECT_GE(target_hits.load(), 1);
  26858. EXPECT_FALSE(target_saw_authz.load());
  26859. }
  26860. #ifdef CPPHTTPLIB_SSL_ENABLED
  26861. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26862. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26863. // proxy creds would be sent to the (possibly hostile) origin.
  26864. std::atomic<int> target_hits{0};
  26865. std::atomic<bool> target_saw_proxy_authz{false};
  26866. no_proxy_test::ScopedServer target;
  26867. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26868. target_hits++;
  26869. if (req.has_header("Proxy-Authorization")) {
  26870. target_saw_proxy_authz = true;
  26871. }
  26872. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26873. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26874. "nonce=\"abc\", algorithm=MD5");
  26875. });
  26876. target.listen();
  26877. // The proxy address is set to the target's port: the bypass MUST kick in;
  26878. // if it doesn't, the test still routes "via proxy" to the same server and
  26879. // the Proxy-Authorization assertion below catches the leak.
  26880. Client cli("evil.example", target.port());
  26881. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26882. cli.set_proxy("127.0.0.1", target.port());
  26883. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26884. cli.set_no_proxy({"evil.example"});
  26885. auto res = cli.Get("/x");
  26886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26887. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26888. EXPECT_EQ(1, target_hits.load());
  26889. EXPECT_FALSE(target_saw_proxy_authz.load());
  26890. }
  26891. #endif
  26892. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26893. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26894. std::atomic<int> proxy_hits{0};
  26895. std::atomic<int> bypass_hits{0};
  26896. std::atomic<bool> proxy_saw_c_url{false};
  26897. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26898. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26899. proxy_hits++;
  26900. if (req.path.find("/start") != std::string::npos) {
  26901. res.status = 302;
  26902. res.set_header("Location", "http://127.0.0.1:" +
  26903. std::to_string(bypass_server.port()) +
  26904. "/middle");
  26905. return;
  26906. }
  26907. if (req.path.find("/end") != std::string::npos) {
  26908. proxy_saw_c_url = true;
  26909. res.set_content("c-via-proxy", "text/plain");
  26910. return;
  26911. }
  26912. res.set_content("unexpected", "text/plain");
  26913. });
  26914. // public.example's "advertised" port is arbitrary (the request never lands
  26915. // there — it goes through the proxy), but use a dynamic value to stay
  26916. // friendly with sharded parallel runs.
  26917. int public_port = bypass_server.port();
  26918. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26919. bypass_hits++;
  26920. res.status = 302;
  26921. res.set_header("Location", "http://public.example:" +
  26922. std::to_string(public_port) + "/end");
  26923. });
  26924. proxy_mock.listen();
  26925. bypass_server.listen();
  26926. Client cli("public.example", public_port);
  26927. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26928. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26929. cli.set_no_proxy({"127.0.0.1"});
  26930. cli.set_follow_location(true);
  26931. auto res = cli.Get("/start");
  26932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26933. EXPECT_EQ(StatusCode::OK_200, res->status);
  26934. EXPECT_EQ("c-via-proxy", res->body);
  26935. EXPECT_GE(proxy_hits.load(), 2);
  26936. EXPECT_GE(bypass_hits.load(), 1);
  26937. EXPECT_TRUE(proxy_saw_c_url.load());
  26938. }
  26939. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26940. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26941. // request reconnects to the correct endpoint.
  26942. std::atomic<int> proxy_hits{0};
  26943. std::atomic<int> target_hits{0};
  26944. no_proxy_test::ScopedServer proxy_mock, target;
  26945. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26946. proxy_hits++;
  26947. res.set_content("via-proxy", "text/plain");
  26948. });
  26949. target.svr().Get(".*", [&](const Request &, Response &res) {
  26950. target_hits++;
  26951. res.set_content("direct", "text/plain");
  26952. });
  26953. proxy_mock.listen();
  26954. target.listen();
  26955. Client cli("public.example", target.port());
  26956. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26957. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26958. cli.set_keep_alive(true);
  26959. auto res1 = cli.Get("/a");
  26960. ASSERT_TRUE(res1);
  26961. EXPECT_EQ("via-proxy", res1->body);
  26962. EXPECT_EQ(1, proxy_hits.load());
  26963. EXPECT_EQ(0, target_hits.load());
  26964. cli.set_no_proxy({"public.example"});
  26965. auto res2 = cli.Get("/b");
  26966. ASSERT_TRUE(res2);
  26967. EXPECT_EQ("direct", res2->body);
  26968. EXPECT_EQ(1, proxy_hits.load());
  26969. EXPECT_EQ(1, target_hits.load());
  26970. }
  26971. // Forward declarations (see the base64_encode note).
  26972. namespace httplib {
  26973. namespace detail {
  26974. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26975. int shutdown_socket(socket_t sock) noexcept;
  26976. } // namespace detail
  26977. } // namespace httplib
  26978. namespace proxy_tunnel_test {
  26979. const char *const kTunnelEstablished =
  26980. "HTTP/1.1 200 Connection established\r\n\r\n";
  26981. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26982. using ConnectReply = std::function<std::string(const std::string &head)>;
  26983. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26984. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26985. class ScopedConnectProxy {
  26986. public:
  26987. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26988. : forward_port_(forward_port), reply_(std::move(reply)) {
  26989. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26990. if (listen_sock_ == INVALID_SOCKET) { return; }
  26991. auto a = loopback(0);
  26992. auto addr = reinterpret_cast<sockaddr *>(&a);
  26993. socklen_t alen = sizeof(a);
  26994. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26995. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26996. ::listen(listen_sock_, 4) != 0) {
  26997. return;
  26998. }
  26999. port_ = ntohs(a.sin_port);
  27000. th_ = std::thread([this] { run(); });
  27001. }
  27002. ~ScopedConnectProxy() {
  27003. if (th_.joinable()) {
  27004. stop_ = true;
  27005. auto wake = connect_to(port_);
  27006. th_.join();
  27007. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27008. }
  27009. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27010. }
  27011. int port() const { return port_; }
  27012. int connect_hits() const { return connect_hits_.load(); }
  27013. // Head of the last CONNECT request, as the proxy saw it on the wire.
  27014. std::string connect_request() const {
  27015. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27016. return connect_request_;
  27017. }
  27018. private:
  27019. static sockaddr_in loopback(int port) {
  27020. sockaddr_in a{};
  27021. a.sin_family = AF_INET;
  27022. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  27023. a.sin_port = htons(static_cast<unsigned short>(port));
  27024. return a;
  27025. }
  27026. static socket_t connect_to(int port) {
  27027. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  27028. if (sock == INVALID_SOCKET) { return sock; }
  27029. auto a = loopback(port);
  27030. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  27031. detail::close_socket(sock);
  27032. return INVALID_SOCKET;
  27033. }
  27034. return sock;
  27035. }
  27036. static bool send_all(socket_t sock, const char *data, size_t size) {
  27037. while (size > 0) {
  27038. auto n = detail::send_socket(sock, data, size, 0);
  27039. if (n <= 0) { return false; }
  27040. data += n;
  27041. size -= static_cast<size_t>(n);
  27042. }
  27043. return true;
  27044. }
  27045. void run() {
  27046. for (;;) {
  27047. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27048. if (stop_) {
  27049. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27050. return;
  27051. }
  27052. if (client == INVALID_SOCKET) { continue; }
  27053. serve(client);
  27054. detail::close_socket(client);
  27055. }
  27056. }
  27057. void serve(socket_t client) {
  27058. std::string head;
  27059. char buf[2048];
  27060. while (head.find("\r\n\r\n") == std::string::npos) {
  27061. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27062. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27063. if (n <= 0) { return; }
  27064. head.append(buf, static_cast<size_t>(n));
  27065. }
  27066. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27067. connect_hits_++;
  27068. {
  27069. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27070. connect_request_ = head;
  27071. }
  27072. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27073. if (!send_all(client, res.data(), res.size()) ||
  27074. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27075. return;
  27076. }
  27077. auto origin = connect_to(forward_port_);
  27078. if (origin == INVALID_SOCKET) { return; }
  27079. // When either side stops, shut both down so the other pump returns too.
  27080. auto pump = [&](socket_t from, socket_t to) {
  27081. char b[8192];
  27082. for (;;) {
  27083. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27084. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27085. }
  27086. detail::shutdown_socket(client);
  27087. detail::shutdown_socket(origin);
  27088. };
  27089. std::thread up([&] { pump(client, origin); });
  27090. pump(origin, client);
  27091. up.join();
  27092. detail::close_socket(origin);
  27093. }
  27094. int forward_port_;
  27095. ConnectReply reply_;
  27096. socket_t listen_sock_ = INVALID_SOCKET;
  27097. int port_ = 0;
  27098. std::thread th_;
  27099. std::atomic<bool> stop_{false};
  27100. std::atomic<int> connect_hits_{0};
  27101. mutable std::mutex connect_request_mutex_;
  27102. std::string connect_request_;
  27103. };
  27104. } // namespace proxy_tunnel_test
  27105. #ifdef CPPHTTPLIB_SSL_ENABLED
  27106. namespace proxy_tunnel_test {
  27107. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27108. class ScopedSSLServer {
  27109. public:
  27110. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27111. port_ = svr_.bind_to_any_port("127.0.0.1");
  27112. }
  27113. ~ScopedSSLServer() {
  27114. svr_.stop();
  27115. if (th_.joinable()) { th_.join(); }
  27116. }
  27117. SSLServer &svr() { return svr_; }
  27118. int port() const { return port_; }
  27119. void listen() {
  27120. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27121. svr_.wait_until_ready();
  27122. }
  27123. private:
  27124. SSLServer svr_;
  27125. std::thread th_;
  27126. int port_ = 0;
  27127. };
  27128. // Sends one request through the CONNECT proxy to the TLS origin with a
  27129. // credential configured for each hop, and checks that each credential reaches
  27130. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27131. // origin's (every header in origin_headers) on the tunnelled request.
  27132. void CredentialsStayWithTheirHop(
  27133. const std::function<void(SSLClient &)> &set_credentials,
  27134. const std::string &scheme,
  27135. const std::vector<std::string> &origin_headers = {"Authorization"},
  27136. bool stream = false) {
  27137. std::atomic<int> origin_hits{0};
  27138. std::atomic<bool> origin_saw_proxy_authz{false};
  27139. std::atomic<bool> origin_saw_headers{false};
  27140. ScopedSSLServer origin;
  27141. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27142. origin_hits++;
  27143. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27144. origin_saw_headers =
  27145. std::all_of(origin_headers.begin(), origin_headers.end(),
  27146. [&](const std::string &h) { return req.has_header(h); });
  27147. res.set_content("ok", "text/plain");
  27148. });
  27149. origin.listen();
  27150. ScopedConnectProxy proxy(origin.port());
  27151. ASSERT_NE(0, proxy.port());
  27152. // Pinned to 127.0.0.1 for the same reason as the test below.
  27153. SSLClient cli("127.0.0.1", origin.port());
  27154. cli.enable_server_certificate_verification(false);
  27155. cli.set_proxy("127.0.0.1", proxy.port());
  27156. set_credentials(cli);
  27157. if (stream) {
  27158. auto handle = cli.open_stream("GET", "/x");
  27159. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27160. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27161. } else {
  27162. auto res = cli.Get("/x");
  27163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27164. EXPECT_EQ(StatusCode::OK_200, res->status);
  27165. }
  27166. EXPECT_EQ(1, origin_hits.load());
  27167. EXPECT_EQ(1, proxy.connect_hits());
  27168. EXPECT_TRUE(origin_saw_headers.load());
  27169. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27170. << "Proxy-Authorization must not be sent inside the tunnel";
  27171. auto connect_req = proxy.connect_request();
  27172. EXPECT_NE(std::string::npos,
  27173. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27174. for (const auto &h : origin_headers) {
  27175. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27176. << h << " must not be sent to the proxy on CONNECT";
  27177. }
  27178. }
  27179. } // namespace proxy_tunnel_test
  27180. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27181. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27182. [](SSLClient &cli) {
  27183. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27184. cli.set_basic_auth("origin-user", "origin-pass");
  27185. },
  27186. "Basic");
  27187. }
  27188. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27189. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27190. [](SSLClient &cli) {
  27191. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27192. cli.set_basic_auth("origin-user", "origin-pass");
  27193. },
  27194. "Basic", {"Authorization"}, true);
  27195. }
  27196. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27197. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27198. [](SSLClient &cli) {
  27199. cli.set_proxy_bearer_token_auth("proxy-token");
  27200. cli.set_bearer_token_auth("origin-token");
  27201. },
  27202. "Bearer");
  27203. }
  27204. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27205. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27206. [](SSLClient &cli) {
  27207. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27208. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27209. {"Cookie", "sid=origin-session"},
  27210. {"X-Api-Key", "origin-key"}});
  27211. },
  27212. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27213. }
  27214. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27215. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27216. // retry; otherwise proxy creds would be sent to the origin.
  27217. std::atomic<int> origin_hits{0};
  27218. std::atomic<bool> origin_saw_proxy_authz{false};
  27219. proxy_tunnel_test::ScopedSSLServer origin;
  27220. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27221. origin_hits++;
  27222. if (req.has_header("Proxy-Authorization")) {
  27223. origin_saw_proxy_authz = true;
  27224. }
  27225. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27226. res.set_header("Proxy-Authenticate",
  27227. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27228. "algorithm=MD5");
  27229. });
  27230. origin.listen();
  27231. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27232. ASSERT_NE(0, proxy.port());
  27233. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27234. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27235. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27236. // and answer with its own status, making this test flaky.
  27237. SSLClient cli("127.0.0.1", origin.port());
  27238. cli.enable_server_certificate_verification(false);
  27239. cli.set_proxy("127.0.0.1", proxy.port());
  27240. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27241. auto res = cli.Get("/x");
  27242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27243. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27244. EXPECT_EQ(1, origin_hits.load());
  27245. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27246. EXPECT_EQ(1, proxy.connect_hits());
  27247. }
  27248. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27249. std::string origin_sni;
  27250. std::string origin_host;
  27251. proxy_tunnel_test::ScopedSSLServer origin;
  27252. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27253. origin_sni = req.sni();
  27254. origin_host = req.get_header_value("Host");
  27255. res.set_content("ok", "text/plain");
  27256. });
  27257. origin.listen();
  27258. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27259. ASSERT_NE(0, proxy.port());
  27260. SSLClient cli("origin.example", origin.port());
  27261. cli.enable_server_certificate_verification(false);
  27262. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27263. cli.set_proxy("127.0.0.1", proxy.port());
  27264. auto res = cli.Get("/x");
  27265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27266. EXPECT_EQ(StatusCode::OK_200, res->status);
  27267. auto port = std::to_string(origin.port());
  27268. auto target = "127.0.0.1:" + port;
  27269. auto connect_req = proxy.connect_request();
  27270. EXPECT_EQ(1, proxy.connect_hits());
  27271. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27272. EXPECT_NE(std::string::npos,
  27273. connect_req.find("\r\nHost: " + target + "\r\n"));
  27274. EXPECT_EQ("origin.example", origin_sni);
  27275. EXPECT_EQ("origin.example:" + port, origin_host);
  27276. }
  27277. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27278. proxy_tunnel_test::ScopedSSLServer origin;
  27279. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27280. res.set_content("ok", "text/plain");
  27281. });
  27282. origin.listen();
  27283. proxy_tunnel_test::ScopedConnectProxy proxy(
  27284. origin.port(), [](const std::string &head) -> std::string {
  27285. if (head.find(
  27286. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27287. std::string::npos) {
  27288. return proxy_tunnel_test::kTunnelEstablished;
  27289. }
  27290. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27291. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27292. "nonce=\"abc\", algorithm=MD5\r\n"
  27293. "Content-Length: 0\r\n\r\n";
  27294. });
  27295. ASSERT_NE(0, proxy.port());
  27296. SSLClient cli("origin.example", origin.port());
  27297. cli.enable_server_certificate_verification(false);
  27298. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27299. cli.set_proxy("127.0.0.1", proxy.port());
  27300. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27301. auto res = cli.Get("/x");
  27302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27303. EXPECT_EQ(StatusCode::OK_200, res->status);
  27304. // The retried CONNECT is the one the proxy saw last.
  27305. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27306. auto connect_req = proxy.connect_request();
  27307. EXPECT_EQ(2, proxy.connect_hits());
  27308. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27309. EXPECT_NE(std::string::npos,
  27310. connect_req.find("\r\nHost: " + target + "\r\n"));
  27311. }
  27312. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27313. proxy_tunnel_test::ScopedSSLServer origin;
  27314. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27315. res.set_content("ok", "text/plain");
  27316. });
  27317. origin.listen();
  27318. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27319. ASSERT_NE(0, proxy.port());
  27320. SSLClient cli("origin.example", origin.port());
  27321. cli.enable_server_certificate_verification(false);
  27322. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27323. cli.set_proxy("127.0.0.1", proxy.port());
  27324. auto res = cli.Get("/x");
  27325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27326. EXPECT_EQ(StatusCode::OK_200, res->status);
  27327. auto target = "origin.example:" + std::to_string(origin.port());
  27328. auto connect_req = proxy.connect_request();
  27329. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27330. EXPECT_NE(std::string::npos,
  27331. connect_req.find("\r\nHost: " + target + "\r\n"));
  27332. }
  27333. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27334. proxy_tunnel_test::ScopedSSLServer origin;
  27335. auto port = std::to_string(origin.port());
  27336. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27337. res.set_redirect("https://next.example:" + port + "/y");
  27338. });
  27339. origin.svr().Get("/y", [](const Request &, Response &res) {
  27340. res.set_content("ok", "text/plain");
  27341. });
  27342. origin.listen();
  27343. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27344. ASSERT_NE(0, proxy.port());
  27345. SSLClient cli("origin.example", origin.port());
  27346. cli.enable_server_certificate_verification(false);
  27347. cli.set_tunnel_hostname_addr_map(
  27348. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27349. cli.set_proxy("127.0.0.1", proxy.port());
  27350. cli.set_follow_location(true);
  27351. auto res = cli.Get("/x");
  27352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27353. EXPECT_EQ("ok", res->body);
  27354. // The last CONNECT is the redirect client's.
  27355. ASSERT_EQ(2, proxy.connect_hits());
  27356. auto target = "127.0.0.1:" + port;
  27357. auto connect_req = proxy.connect_request();
  27358. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27359. EXPECT_NE(std::string::npos,
  27360. connect_req.find("\r\nHost: " + target + "\r\n"));
  27361. }
  27362. #endif
  27363. namespace proxy_tunnel_test {
  27364. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27365. // anything else gets a 407 with `challenge`.
  27366. ConnectReply require_proxy_auth(const std::string &expected,
  27367. const std::string &challenge) {
  27368. return [=](const std::string &head) -> std::string {
  27369. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27370. std::string::npos) {
  27371. return kTunnelEstablished;
  27372. }
  27373. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27374. "Proxy-Authenticate: " +
  27375. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27376. };
  27377. }
  27378. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27379. // request, then echoes.
  27380. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27381. ws.send(
  27382. "authorization:" + req.get_header_value("Authorization") +
  27383. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27384. std::string msg;
  27385. while (ws.read(msg)) {
  27386. ws.send(msg);
  27387. }
  27388. }
  27389. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27390. class ScopedWebSocketOrigin {
  27391. public:
  27392. ScopedWebSocketOrigin() {
  27393. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27394. server_.listen();
  27395. }
  27396. int port() const { return server_.port(); }
  27397. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27398. std::string url() const {
  27399. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27400. }
  27401. private:
  27402. no_proxy_test::ScopedServer server_;
  27403. };
  27404. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27405. // passed as a constructor header, and checks that each reaches only its hop.
  27406. void WebSocketCredentialsStayWithTheirHop(
  27407. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27408. const std::string &proxy_authz, const std::string &origin_authz) {
  27409. ScopedWebSocketOrigin origin;
  27410. ScopedConnectProxy proxy(
  27411. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27412. ASSERT_NE(0, proxy.port());
  27413. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27414. client.set_proxy("127.0.0.1", proxy.port());
  27415. set_proxy_credentials(client);
  27416. auto res = client.connect();
  27417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27418. std::string msg;
  27419. ASSERT_TRUE(client.read(msg));
  27420. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27421. client.close();
  27422. EXPECT_EQ(1, proxy.connect_hits());
  27423. EXPECT_EQ(std::string::npos,
  27424. proxy.connect_request().find("\r\nAuthorization: "))
  27425. << "origin credentials must not be sent to the proxy";
  27426. }
  27427. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  27428. void WebSocketSetterCredentialsStayWithTheirHop(
  27429. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  27430. const std::string &proxy_authz, const std::string &origin_authz) {
  27431. ScopedWebSocketOrigin origin;
  27432. ScopedConnectProxy proxy(
  27433. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27434. ASSERT_NE(0, proxy.port());
  27435. ws::WebSocketClient client(origin.url());
  27436. client.set_proxy("127.0.0.1", proxy.port());
  27437. set_credentials(client);
  27438. auto res = client.connect();
  27439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27440. std::string msg;
  27441. ASSERT_TRUE(client.read(msg));
  27442. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27443. client.close();
  27444. EXPECT_EQ(1, proxy.connect_hits());
  27445. EXPECT_EQ(std::string::npos,
  27446. proxy.connect_request().find("\r\nAuthorization: "))
  27447. << "origin credentials must not be sent to the proxy";
  27448. }
  27449. } // namespace proxy_tunnel_test
  27450. namespace {
  27451. // Connects `client` and returns the Authorization header its upgrade
  27452. // request carried, or "<failed>" when the connection could not be opened.
  27453. std::string websocket_authorization(ws::WebSocketClient &client) {
  27454. if (!client.connect()) { return "<failed>"; }
  27455. std::string msg;
  27456. if (!client.read(msg)) { return "<failed>"; }
  27457. client.close();
  27458. auto prefix = std::string("authorization:");
  27459. auto end = msg.find("|proxy-authorization:");
  27460. return msg.substr(prefix.size(), end - prefix.size());
  27461. }
  27462. } // namespace
  27463. TEST(WebSocketClientAuthTest, BasicAuth) {
  27464. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27465. ws::WebSocketClient client(origin.url());
  27466. client.set_basic_auth("user", "pass");
  27467. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27468. websocket_authorization(client));
  27469. }
  27470. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  27471. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27472. ws::WebSocketClient client(origin.url());
  27473. client.set_basic_auth("user", "");
  27474. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  27475. websocket_authorization(client));
  27476. }
  27477. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  27478. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27479. ws::WebSocketClient client(origin.url());
  27480. client.set_bearer_token_auth("token123");
  27481. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  27482. }
  27483. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  27484. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27485. ws::WebSocketClient client(origin.url());
  27486. client.set_bearer_token_auth("token123");
  27487. client.set_basic_auth("user", "pass");
  27488. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27489. websocket_authorization(client));
  27490. }
  27491. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  27492. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27493. ws::WebSocketClient client(origin.url(),
  27494. {{"Authorization", "Bearer from-header"}});
  27495. client.set_bearer_token_auth("from-setter");
  27496. client.set_basic_auth("user", "pass");
  27497. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  27498. }
  27499. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  27500. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27501. ws::WebSocketClient client(origin.url());
  27502. EXPECT_EQ("", websocket_authorization(client));
  27503. client.set_bearer_token_auth("first");
  27504. EXPECT_EQ("Bearer first", websocket_authorization(client));
  27505. client.set_bearer_token_auth("second");
  27506. EXPECT_EQ("Bearer second", websocket_authorization(client));
  27507. client.set_bearer_token_auth("");
  27508. EXPECT_EQ("", websocket_authorization(client));
  27509. }
  27510. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27511. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27512. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27513. ASSERT_NE(0, proxy.port());
  27514. ws::WebSocketClient client(origin.url());
  27515. client.set_proxy("127.0.0.1", proxy.port());
  27516. auto res = client.connect();
  27517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27518. std::string msg;
  27519. ASSERT_TRUE(client.read(msg));
  27520. ASSERT_TRUE(client.send("hello"));
  27521. ASSERT_TRUE(client.read(msg));
  27522. EXPECT_EQ("hello", msg);
  27523. client.close();
  27524. EXPECT_EQ(1, proxy.connect_hits());
  27525. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27526. auto connect_req = proxy.connect_request();
  27527. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27528. EXPECT_NE(std::string::npos,
  27529. connect_req.find("\r\nHost: " + target + "\r\n"));
  27530. }
  27531. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27532. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27533. [](ws::WebSocketClient &cli) {
  27534. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27535. },
  27536. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27537. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27538. }
  27539. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27540. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27541. [](ws::WebSocketClient &cli) {
  27542. cli.set_proxy_bearer_token_auth("proxy-token");
  27543. },
  27544. "Bearer proxy-token", "Bearer origin-token");
  27545. }
  27546. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  27547. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27548. [](ws::WebSocketClient &cli) {
  27549. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27550. cli.set_basic_auth("origin-user", "origin-pass");
  27551. },
  27552. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27553. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27554. }
  27555. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  27556. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27557. [](ws::WebSocketClient &cli) {
  27558. cli.set_proxy_bearer_token_auth("proxy-token");
  27559. cli.set_bearer_token_auth("origin-token");
  27560. },
  27561. "Bearer proxy-token", "Bearer origin-token");
  27562. }
  27563. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27564. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27565. proxy_tunnel_test::ScopedConnectProxy proxy(
  27566. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27567. "Basic " + detail::base64_encode("proxy-user:"),
  27568. "Basic realm=\"proxy\""));
  27569. ASSERT_NE(0, proxy.port());
  27570. ws::WebSocketClient client(origin.url());
  27571. client.set_proxy("127.0.0.1", proxy.port());
  27572. client.set_proxy_basic_auth("proxy-user", "");
  27573. auto res = client.connect();
  27574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27575. client.close();
  27576. EXPECT_EQ(1, proxy.connect_hits());
  27577. }
  27578. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27579. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27580. proxy_tunnel_test::ScopedConnectProxy proxy(
  27581. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27582. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27583. ASSERT_NE(0, proxy.port());
  27584. ws::WebSocketClient client(origin.url());
  27585. client.set_proxy("127.0.0.1", proxy.port());
  27586. auto res = client.connect();
  27587. EXPECT_FALSE(res);
  27588. EXPECT_EQ(Error::ProxyConnection, res.error());
  27589. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27590. EXPECT_EQ("Basic realm=\"proxy\"",
  27591. res.get_header_value("Proxy-Authenticate"));
  27592. EXPECT_FALSE(client.is_open());
  27593. }
  27594. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27595. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27596. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27597. ASSERT_NE(0, proxy.port());
  27598. ws::WebSocketClient client(origin.url());
  27599. client.set_proxy("127.0.0.1", proxy.port());
  27600. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27601. client.set_no_proxy({"127.0.0.1"});
  27602. auto res = client.connect();
  27603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27604. std::string msg;
  27605. ASSERT_TRUE(client.read(msg));
  27606. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27607. << "proxy credentials must not reach a bypassed origin";
  27608. client.close();
  27609. EXPECT_EQ(0, proxy.connect_hits());
  27610. }
  27611. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27612. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27613. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27614. ASSERT_NE(0, proxy.port());
  27615. ws::WebSocketClient client(origin.url());
  27616. client.set_proxy("127.0.0.1", proxy.port());
  27617. ASSERT_TRUE(client.connect());
  27618. ASSERT_TRUE(client.connect());
  27619. client.close();
  27620. EXPECT_EQ(2, proxy.connect_hits());
  27621. }
  27622. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27623. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27624. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27625. ASSERT_NE(0, proxy.port());
  27626. auto port = std::to_string(origin.port());
  27627. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27628. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27629. client.set_proxy("127.0.0.1", proxy.port());
  27630. auto res = client.connect();
  27631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27632. std::string msg;
  27633. ASSERT_TRUE(client.read(msg));
  27634. client.close();
  27635. EXPECT_EQ(1, proxy.connect_hits());
  27636. auto target = "127.0.0.1:" + port;
  27637. auto connect_req = proxy.connect_request();
  27638. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27639. EXPECT_NE(std::string::npos,
  27640. connect_req.find("\r\nHost: " + target + "\r\n"));
  27641. }
  27642. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27643. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27644. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27645. ASSERT_NE(0, proxy.port());
  27646. auto port = std::to_string(origin.port());
  27647. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27648. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27649. client.set_proxy("127.0.0.1", proxy.port());
  27650. auto res = client.connect();
  27651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27652. client.close();
  27653. auto target = "origin.example:" + port;
  27654. auto connect_req = proxy.connect_request();
  27655. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27656. EXPECT_NE(std::string::npos,
  27657. connect_req.find("\r\nHost: " + target + "\r\n"));
  27658. }
  27659. #ifdef CPPHTTPLIB_SSL_ENABLED
  27660. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27661. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27662. proxy_tunnel_test::ScopedConnectProxy proxy(
  27663. origin.port(), [](const std::string &head) -> std::string {
  27664. if (head.find(
  27665. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27666. std::string::npos) {
  27667. return proxy_tunnel_test::kTunnelEstablished;
  27668. }
  27669. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27670. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27671. "nonce=\"abc\", algorithm=MD5\r\n"
  27672. "Content-Length: 0\r\n\r\n";
  27673. });
  27674. ASSERT_NE(0, proxy.port());
  27675. ws::WebSocketClient client(origin.url());
  27676. client.set_proxy("127.0.0.1", proxy.port());
  27677. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27678. auto res = client.connect();
  27679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27680. std::string msg;
  27681. ASSERT_TRUE(client.read(msg));
  27682. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27683. client.close();
  27684. EXPECT_EQ(2, proxy.connect_hits());
  27685. }
  27686. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27687. proxy_tunnel_test::ScopedSSLServer origin;
  27688. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27689. origin.listen();
  27690. proxy_tunnel_test::ScopedConnectProxy proxy(
  27691. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27692. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27693. ASSERT_NE(0, proxy.port());
  27694. ws::WebSocketClient client(
  27695. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27696. client.enable_server_certificate_verification(false);
  27697. client.set_proxy("127.0.0.1", proxy.port());
  27698. client.set_proxy_bearer_token_auth("proxy-token");
  27699. auto res = client.connect();
  27700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27701. std::string msg;
  27702. ASSERT_TRUE(client.read(msg));
  27703. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27704. << "Proxy-Authorization must not be sent inside the tunnel";
  27705. client.close();
  27706. EXPECT_EQ(1, proxy.connect_hits());
  27707. }
  27708. #endif