test.cc 888 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425
  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_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 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(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declaration: in split builds split.py strips `inline` and moves the
  474. // definition into httplib.cc, so detail::base64_encode is not visible from the
  475. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  476. // in both header-only and split builds.
  477. namespace httplib {
  478. namespace detail {
  479. std::string base64_encode(const std::string &in);
  480. } // namespace detail
  481. } // namespace httplib
  482. TEST(Base64EncodeTest, KnownAnswers) {
  483. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  484. // where the accumulator's top bit is already set before the next shift.
  485. EXPECT_EQ("", detail::base64_encode(""));
  486. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  487. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  488. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  489. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  490. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  491. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  492. // High bytes keep the top bit set across several rounds.
  493. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  494. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  495. }
  496. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  497. string unescapedCharacters = "-_.!~*'()";
  498. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  499. }
  500. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  501. string reservedCharacters = ";,/?:@&=+$";
  502. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  503. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  504. }
  505. TEST(ClientQueryOrder, PreserveOrder) {
  506. // This test reproduces Issue #2259: client may reorder query parameters
  507. // when sending a GET request. The expected behavior is that the client
  508. // preserves the original query string order when the caller supplied it
  509. // as part of the path.
  510. Server svr;
  511. svr.Get("/", [&](const Request &req, Response &res) {
  512. // Echo back the raw target so the test can assert ordering
  513. res.set_content(req.target, "text/plain");
  514. });
  515. std::thread t{[&] { svr.listen(HOST, PORT); }};
  516. auto se = detail::scope_exit([&] {
  517. svr.stop();
  518. t.join();
  519. ASSERT_FALSE(svr.is_running());
  520. });
  521. svr.wait_until_ready();
  522. Client cli(HOST, PORT);
  523. ASSERT_TRUE(cli.is_valid());
  524. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  525. auto res = cli.Get(original);
  526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  527. // Expect the echoed target to exactly match the original path (order
  528. // preserved)
  529. EXPECT_EQ(res->body, original);
  530. }
  531. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  532. string chineseCharacters = U8("中国語");
  533. string russianCharacters = U8("дом");
  534. string brazilianCharacters = U8("óculos");
  535. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  536. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  537. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  538. "%D0%B4%D0%BE%D0%BC");
  539. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  540. }
  541. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  546. string reservedCharacters = ";,/?:@&=+$";
  547. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  548. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  549. }
  550. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  551. string chineseCharacters = U8("中国語");
  552. string russianCharacters = U8("дом");
  553. string brazilianCharacters = U8("óculos");
  554. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  555. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  556. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  557. "%D0%B4%D0%BE%D0%BC");
  558. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  559. }
  560. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  561. // Issue #2082 use case: encoding path component with ampersand
  562. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  563. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  564. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  565. }
  566. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  567. string unescapedCharacters = "-_.!~*'()";
  568. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  569. }
  570. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  571. string reservedCharacters = ";,/?:@&=+$#";
  572. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  573. }
  574. TEST(EncodeUriTest, TestUTF8Characters) {
  575. string chineseCharacters = U8("中国語");
  576. string russianCharacters = U8("дом");
  577. string brazilianCharacters = U8("óculos");
  578. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  579. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  580. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  581. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  582. }
  583. TEST(EncodeUriTest, TestCompleteUri) {
  584. string uri =
  585. "https://example.com/path/to/resource?query=value&param=test#fragment";
  586. EXPECT_EQ(
  587. httplib::encode_uri(uri),
  588. "https://example.com/path/to/resource?query=value&param=test#fragment");
  589. }
  590. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  591. string uri =
  592. "https://example.com/path with spaces/file name.html?q=hello world";
  593. EXPECT_EQ(httplib::encode_uri(uri),
  594. "https://example.com/path%20with%20spaces/"
  595. "file%20name.html?q=hello%20world");
  596. }
  597. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  598. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  599. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  600. }
  601. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  602. string unescapedCharacters = "-_.!~*'()";
  603. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  604. }
  605. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  606. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  607. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  608. string encodedBrazilian = "%C3%B3culos";
  609. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  610. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  611. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  612. }
  613. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  614. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  615. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  616. "Piri Tommy Villiers - on & on");
  617. }
  618. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  619. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  620. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  621. }
  622. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  623. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  624. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  625. }
  626. TEST(DecodeUriTest, TestUTF8Characters) {
  627. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  628. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  629. string encodedBrazilian = "%C3%B3culos";
  630. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  631. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  632. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  633. }
  634. TEST(DecodeUriTest, TestCompleteUri) {
  635. string encodedUri = "https://example.com/path%20with%20spaces/"
  636. "file%20name.html?q=hello%20world";
  637. EXPECT_EQ(
  638. httplib::decode_uri(encodedUri),
  639. "https://example.com/path with spaces/file name.html?q=hello world");
  640. }
  641. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  642. string original =
  643. "https://example.com/path with spaces/file name.html?q=hello world";
  644. string encoded = httplib::encode_uri(original);
  645. string decoded = httplib::decode_uri(encoded);
  646. EXPECT_EQ(decoded, original);
  647. }
  648. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  649. // decode_uri is the inverse of encode_uri: an escaped reserved character
  650. // stays encoded so it is not promoted into a real delimiter, while
  651. // non-reserved escapes still decode (like JS decodeURI).
  652. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  653. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  654. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  655. "%3F%3A%40%26%3D%2B%24%2C%3B");
  656. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  657. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  658. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  659. "http://example.com/a%2Fb");
  660. // decode_uri_component still decodes the reserved character.
  661. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  662. }
  663. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  664. string original = "Piri Tommy Villiers - on & on";
  665. string encoded = httplib::encode_uri_component(original);
  666. string decoded = httplib::decode_uri_component(encoded);
  667. EXPECT_EQ(decoded, original);
  668. }
  669. TEST(TrimTests, TrimStringTests) {
  670. EXPECT_EQ("abc", detail::trim_copy("abc"));
  671. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  672. EXPECT_TRUE(detail::trim_copy("").empty());
  673. }
  674. TEST(AsciiTest, LocaleIndependentClassification) {
  675. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  676. // which consult the global C locale: std::isalnum(0xC5) can return true
  677. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  678. // helpers must classify every byte by the ASCII grammar alone.
  679. for (int i = 0; i < 256; i++) {
  680. auto c = static_cast<char>(i);
  681. auto is_digit = i >= '0' && i <= '9';
  682. auto is_upper = i >= 'A' && i <= 'Z';
  683. auto is_lower = i >= 'a' && i <= 'z';
  684. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  685. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  686. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  687. << "byte " << i;
  688. }
  689. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  690. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  691. // Non-ASCII bytes must be percent-encoded, never passed through as
  692. // alphanumeric.
  693. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  694. }
  695. TEST(FromCharsTest, Double) {
  696. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  697. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  698. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  699. auto parse = [](const std::string &s, double &v) {
  700. return detail::from_chars(s.data(), s.data() + s.size(), v);
  701. };
  702. double v = -1.0;
  703. // Representative quality values.
  704. EXPECT_EQ(parse("0", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 0.0);
  706. EXPECT_EQ(parse("1", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 1.0);
  708. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.8);
  710. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 0.001);
  712. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  713. EXPECT_DOUBLE_EQ(v, 1.0);
  714. // A missing integer or fractional part is tolerated.
  715. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 0.5);
  717. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  718. EXPECT_DOUBLE_EQ(v, 5.0);
  719. // Values outside [0, 1] still parse; the caller range-checks them.
  720. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  721. EXPECT_DOUBLE_EQ(v, 123.456);
  722. // Stops at the first byte that is not part of the number and reports where.
  723. std::string trailing = "0.9, text/html";
  724. auto r = parse(trailing, v);
  725. EXPECT_EQ(r.ec, std::errc{});
  726. EXPECT_DOUBLE_EQ(v, 0.9);
  727. EXPECT_EQ(*r.ptr, ',');
  728. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  729. // outright, and an 'e'/'E' simply ends the number.
  730. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  731. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  732. std::string exp_input = "1.5e3";
  733. r = parse(exp_input, v);
  734. EXPECT_EQ(r.ec, std::errc{});
  735. EXPECT_DOUBLE_EQ(v, 1.5);
  736. EXPECT_EQ(*r.ptr, 'e');
  737. // Invalid inputs.
  738. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  742. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  743. // Pathological but well-formed inputs must stay bounded (no overflow, no
  744. // out-of-bounds table access) and stay within [0, 1] for the caller.
  745. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  746. std::errc{});
  747. EXPECT_DOUBLE_EQ(v, 0.0);
  748. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  749. std::errc{});
  750. EXPECT_GE(v, 0.0);
  751. EXPECT_LE(v, 1.0);
  752. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  753. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  754. }
  755. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  756. // Simple case without quality values
  757. std::vector<std::string> result1;
  758. EXPECT_TRUE(detail::parse_accept_header(
  759. "text/html,application/json,text/plain", result1));
  760. EXPECT_EQ(result1.size(), 3U);
  761. EXPECT_EQ(result1[0], "text/html");
  762. EXPECT_EQ(result1[1], "application/json");
  763. EXPECT_EQ(result1[2], "text/plain");
  764. // With quality values
  765. std::vector<std::string> result2;
  766. EXPECT_TRUE(detail::parse_accept_header(
  767. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  768. EXPECT_EQ(result2.size(), 3U);
  769. EXPECT_EQ(result2[0], "application/json"); // highest q value
  770. EXPECT_EQ(result2[1], "text/html");
  771. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  772. }
  773. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  774. // Mixed with and without quality values
  775. std::vector<std::string> result;
  776. EXPECT_TRUE(detail::parse_accept_header(
  777. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  778. EXPECT_EQ(result.size(), 3U);
  779. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  780. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  781. EXPECT_EQ(result[2], "application/json"); // q=0.5
  782. }
  783. TEST(ParseAcceptHeaderTest, EdgeCases) {
  784. // Empty header
  785. std::vector<std::string> empty_result;
  786. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  787. EXPECT_TRUE(empty_result.empty());
  788. // Single type
  789. std::vector<std::string> single_result;
  790. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  791. EXPECT_EQ(single_result.size(), 1U);
  792. EXPECT_EQ(single_result[0], "application/json");
  793. // Wildcard types
  794. std::vector<std::string> wildcard_result;
  795. EXPECT_TRUE(detail::parse_accept_header(
  796. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  797. EXPECT_EQ(wildcard_result.size(), 3U);
  798. EXPECT_EQ(wildcard_result[0], "application/json");
  799. EXPECT_EQ(wildcard_result[1], "text/*");
  800. EXPECT_EQ(wildcard_result[2], "*/*");
  801. }
  802. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  803. // Common browser Accept header
  804. std::vector<std::string> browser_result;
  805. EXPECT_TRUE(
  806. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  807. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  808. browser_result));
  809. EXPECT_EQ(browser_result.size(), 6U);
  810. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  814. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  815. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  816. // API client header
  817. std::vector<std::string> api_result;
  818. EXPECT_TRUE(detail::parse_accept_header(
  819. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  820. api_result));
  821. EXPECT_EQ(api_result.size(), 3U);
  822. EXPECT_EQ(api_result[0], "application/json");
  823. EXPECT_EQ(api_result[1], "application/xml");
  824. EXPECT_EQ(api_result[2], "text/plain");
  825. }
  826. TEST(ParseAcceptHeaderTest, SpecialCases) {
  827. // Quality value with 3 decimal places
  828. std::vector<std::string> decimal_result;
  829. EXPECT_TRUE(detail::parse_accept_header(
  830. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  831. EXPECT_EQ(decimal_result.size(), 2U);
  832. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  833. EXPECT_EQ(decimal_result[1], "text/html");
  834. // Zero quality (should still be included but with lowest priority)
  835. std::vector<std::string> zero_q_result;
  836. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  837. zero_q_result));
  838. EXPECT_EQ(zero_q_result.size(), 2U);
  839. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  840. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  841. // No spaces around commas
  842. std::vector<std::string> no_space_result;
  843. EXPECT_TRUE(detail::parse_accept_header(
  844. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  845. no_space_result));
  846. EXPECT_EQ(no_space_result.size(), 3U);
  847. EXPECT_EQ(no_space_result[0], "text/html");
  848. EXPECT_EQ(no_space_result[1], "application/json");
  849. EXPECT_EQ(no_space_result[2], "text/plain");
  850. }
  851. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  852. // Quality values always use '.' as the decimal separator, so parsing must
  853. // not depend on the process locale. An embedding application may have
  854. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  855. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  856. std::string saved = cur ? cur : "C";
  857. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  858. "fr_FR.UTF-8"};
  859. bool switched = false;
  860. for (const auto loc : comma_locales) {
  861. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  862. std::localeconv()->decimal_point[0] == ',') {
  863. switched = true;
  864. break;
  865. }
  866. }
  867. if (!switched) {
  868. std::setlocale(LC_NUMERIC, saved.c_str());
  869. GTEST_SKIP() << "no comma-decimal locale available on this host";
  870. }
  871. // The higher-weighted type appears later in the list, so a correct parse
  872. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  873. // sensitive parse reads both weights as 0 and leaves the original order.
  874. std::vector<std::string> result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "application/json;q=0.1,text/html;q=0.9", result));
  877. ASSERT_EQ(result.size(), 2U);
  878. EXPECT_EQ(result[0], "text/html");
  879. EXPECT_EQ(result[1], "application/json");
  880. std::setlocale(LC_NUMERIC, saved.c_str());
  881. }
  882. TEST(ParseAcceptHeaderTest, InvalidCases) {
  883. std::vector<std::string> result;
  884. // Invalid quality value (> 1.0)
  885. EXPECT_FALSE(
  886. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  887. // Invalid quality value (< 0.0)
  888. EXPECT_FALSE(
  889. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  890. // Invalid quality value (not a number)
  891. EXPECT_FALSE(detail::parse_accept_header(
  892. "text/html;q=invalid,application/json", result));
  893. // A valid numeric prefix does not make the entire quality value valid.
  894. EXPECT_FALSE(detail::parse_accept_header(
  895. "text/html;q=0.5junk,application/json", result));
  896. // Empty quality value
  897. EXPECT_FALSE(
  898. detail::parse_accept_header("text/html;q=,application/json", result));
  899. // Invalid media type format (no slash and not wildcard)
  900. EXPECT_FALSE(
  901. detail::parse_accept_header("invalidtype,application/json", result));
  902. // Valid cases should still work
  903. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  904. EXPECT_EQ(result.size(), 1U);
  905. EXPECT_EQ(result[0], "*/*");
  906. EXPECT_TRUE(detail::parse_accept_header("*", result));
  907. EXPECT_EQ(result.size(), 1U);
  908. EXPECT_EQ(result[0], "*");
  909. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  910. EXPECT_EQ(result.size(), 1U);
  911. EXPECT_EQ(result[0], "text/*");
  912. }
  913. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  914. // elements, so a leading, trailing or doubled comma is a legal Accept value
  915. // and must not be answered with 400 Bad Request.
  916. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  917. struct {
  918. const char *value;
  919. std::vector<std::string> expected;
  920. } cases[] = {
  921. {",application/json", {"application/json"}},
  922. {"text/html,", {"text/html"}},
  923. {"text/html,,*/*", {"text/html", "*/*"}},
  924. // An empty element may be spelled with whitespace in it
  925. {"text/html, , application/json", {"text/html", "application/json"}},
  926. // Nothing but empty elements is an empty list, which means the same
  927. // thing as no Accept header at all
  928. {",,,", {}},
  929. // Quality values still apply across ignored empty elements
  930. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  931. };
  932. for (const auto &c : cases) {
  933. std::vector<std::string> result;
  934. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  935. << "value: " << c.value;
  936. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  937. }
  938. // An invalid entry is still rejected when empty elements surround it
  939. std::vector<std::string> result;
  940. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  941. }
  942. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  943. // or ';' inside one does not end the list element or the parameter. Section
  944. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  945. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  946. struct {
  947. const char *value;
  948. std::vector<std::string> expected;
  949. } cases[] = {
  950. {"text/html;profile=\"a,b\",application/json",
  951. {"text/html", "application/json"}},
  952. // A "q=" inside a quoted value is not the weight
  953. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  954. {"text/html", "application/json"}},
  955. // The weight after a quoted value still applies
  956. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  957. {"application/json", "text/html"}},
  958. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  959. {"application/json", "text/html"}},
  960. {"text/html;profile=\"a\\\"b\",application/json",
  961. {"text/html", "application/json"}},
  962. // An escaped backslash does not escape the '"' after it
  963. {"text/html;profile=\"a\\\\\",application/json",
  964. {"text/html", "application/json"}},
  965. };
  966. for (const auto &c : cases) {
  967. std::vector<std::string> result;
  968. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  969. << "value: " << c.value;
  970. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  971. }
  972. }
  973. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  974. Server svr;
  975. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  976. EXPECT_EQ(req.accept_content_types.size(), 3U);
  977. EXPECT_EQ(req.accept_content_types[0], "application/json");
  978. EXPECT_EQ(req.accept_content_types[1], "text/html");
  979. EXPECT_EQ(req.accept_content_types[2], "*/*");
  980. res.set_content("ok", "text/plain");
  981. });
  982. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  983. EXPECT_TRUE(false);
  984. res.set_content("bad request", "text/plain");
  985. });
  986. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  987. auto se = detail::scope_exit([&] {
  988. svr.stop();
  989. listen_thread.join();
  990. ASSERT_FALSE(svr.is_running());
  991. });
  992. svr.wait_until_ready();
  993. Client cli("localhost", PORT);
  994. {
  995. auto res = cli.Get(
  996. "/accept_ok",
  997. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  999. EXPECT_EQ(StatusCode::OK_200, res->status);
  1000. }
  1001. {
  1002. auto res = cli.Get("/accept_bad_request",
  1003. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1005. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1006. }
  1007. }
  1008. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1009. Server svr;
  1010. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1011. res.set_content("ok", "text/plain");
  1012. });
  1013. std::atomic<int> start_count{0};
  1014. std::atomic<bool> running_when_called{false};
  1015. svr.set_start_handler([&]() {
  1016. running_when_called = svr.is_running();
  1017. start_count++;
  1018. });
  1019. auto port = svr.bind_to_any_port(HOST);
  1020. std::thread t([&]() { svr.listen_after_bind(); });
  1021. auto se = detail::scope_exit([&] {
  1022. svr.stop();
  1023. t.join();
  1024. ASSERT_FALSE(svr.is_running());
  1025. });
  1026. svr.wait_until_ready();
  1027. // A successful request proves the accept loop is running, which the start
  1028. // handler precedes; so by now the handler must have run exactly once.
  1029. Client cli(HOST, port);
  1030. cli.set_connection_timeout(std::chrono::seconds(5));
  1031. auto res = cli.Get("/");
  1032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1033. EXPECT_EQ(StatusCode::OK_200, res->status);
  1034. EXPECT_EQ(1, start_count.load());
  1035. EXPECT_TRUE(running_when_called.load());
  1036. }
  1037. TEST(DivideTest, DivideStringTests) {
  1038. auto divide = [](const std::string &str, char d) {
  1039. std::string lhs;
  1040. std::string rhs;
  1041. detail::divide(str, d,
  1042. [&](const char *lhs_data, std::size_t lhs_size,
  1043. const char *rhs_data, std::size_t rhs_size) {
  1044. lhs.assign(lhs_data, lhs_size);
  1045. rhs.assign(rhs_data, rhs_size);
  1046. });
  1047. return std::make_pair(std::move(lhs), std::move(rhs));
  1048. };
  1049. {
  1050. const auto res = divide("", '=');
  1051. EXPECT_EQ(res.first, "");
  1052. EXPECT_EQ(res.second, "");
  1053. }
  1054. {
  1055. const auto res = divide("=", '=');
  1056. EXPECT_EQ(res.first, "");
  1057. EXPECT_EQ(res.second, "");
  1058. }
  1059. {
  1060. const auto res = divide(" ", '=');
  1061. EXPECT_EQ(res.first, " ");
  1062. EXPECT_EQ(res.second, "");
  1063. }
  1064. {
  1065. const auto res = divide("a", '=');
  1066. EXPECT_EQ(res.first, "a");
  1067. EXPECT_EQ(res.second, "");
  1068. }
  1069. {
  1070. const auto res = divide("a=", '=');
  1071. EXPECT_EQ(res.first, "a");
  1072. EXPECT_EQ(res.second, "");
  1073. }
  1074. {
  1075. const auto res = divide("=b", '=');
  1076. EXPECT_EQ(res.first, "");
  1077. EXPECT_EQ(res.second, "b");
  1078. }
  1079. {
  1080. const auto res = divide("a=b", '=');
  1081. EXPECT_EQ(res.first, "a");
  1082. EXPECT_EQ(res.second, "b");
  1083. }
  1084. {
  1085. const auto res = divide("a=b=", '=');
  1086. EXPECT_EQ(res.first, "a");
  1087. EXPECT_EQ(res.second, "b=");
  1088. }
  1089. {
  1090. const auto res = divide("a=b=c", '=');
  1091. EXPECT_EQ(res.first, "a");
  1092. EXPECT_EQ(res.second, "b=c");
  1093. }
  1094. }
  1095. TEST(SplitTest, ParseQueryString) {
  1096. string s = "key1=val1&key2=val2&key3=val3";
  1097. Params dic;
  1098. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1099. [&](const char *b, const char *e) {
  1100. string key, val;
  1101. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1102. if (key.empty()) {
  1103. key.assign(b2, e2);
  1104. } else {
  1105. val.assign(b2, e2);
  1106. }
  1107. });
  1108. dic.emplace(key, val);
  1109. });
  1110. EXPECT_EQ("val1", dic.find("key1")->second);
  1111. EXPECT_EQ("val2", dic.find("key2")->second);
  1112. EXPECT_EQ("val3", dic.find("key3")->second);
  1113. }
  1114. TEST(SplitTest, ParseInvalidQueryTests) {
  1115. {
  1116. string s = " ";
  1117. Params dict;
  1118. detail::parse_query_text(s, dict);
  1119. EXPECT_TRUE(dict.empty());
  1120. }
  1121. {
  1122. string s = " = =";
  1123. Params dict;
  1124. detail::parse_query_text(s, dict);
  1125. EXPECT_TRUE(dict.empty());
  1126. }
  1127. }
  1128. TEST(ParseQueryTest, ParseQueryString) {
  1129. {
  1130. std::string s = "key1=val1&key2=val2&key3=val3";
  1131. Params dic;
  1132. detail::parse_query_text(s, dic);
  1133. EXPECT_EQ("val1", dic.find("key1")->second);
  1134. EXPECT_EQ("val2", dic.find("key2")->second);
  1135. EXPECT_EQ("val3", dic.find("key3")->second);
  1136. }
  1137. {
  1138. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1139. Params dic;
  1140. detail::parse_query_text(s, dic);
  1141. EXPECT_EQ("", dic.find("key1")->second);
  1142. EXPECT_EQ("val1", dic.find("key2")->second);
  1143. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1144. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1145. }
  1146. }
  1147. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1148. Params dic;
  1149. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1150. dic.emplace("key1", "val1");
  1151. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1152. dic.emplace("key2", "val2");
  1153. dic.emplace("key3", "val3");
  1154. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1155. }
  1156. // Joins every entry of a Headers or Params into "key=value " so a whole
  1157. // traversal can be compared in one assertion. Both are instantiations of the
  1158. // same insertion-ordered container, so one helper serves both.
  1159. template <typename Map> static std::string entries_to_string(const Map &m) {
  1160. std::string s;
  1161. for (const auto &entry : m) {
  1162. s += entry.first + "=" + entry.second + " ";
  1163. }
  1164. return s;
  1165. }
  1166. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1167. // Params used to be a std::multimap, which sorted by name and handed the
  1168. // caller's query back alphabetised. A client signing its query string could
  1169. // not reproduce the order it asked for.
  1170. Params dic;
  1171. dic.emplace("zulu", "1");
  1172. dic.emplace("alpha", "2");
  1173. dic.emplace("mike", "3");
  1174. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1175. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1176. }
  1177. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1178. Params dic;
  1179. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1180. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1181. }
  1182. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1183. Request req;
  1184. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1185. req.params);
  1186. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1187. EXPECT_EQ("first", req.get_param_value("tag"));
  1188. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1189. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1190. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1191. EXPECT_EQ("", req.get_param_value("tag", 3));
  1192. }
  1193. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1194. // Params shares its container with Headers, which matches field names
  1195. // case-insensitively. Parameter names must not pick that up.
  1196. Params dic;
  1197. dic.emplace("Key", "upper");
  1198. dic.emplace("key", "lower");
  1199. EXPECT_EQ(2U, dic.size());
  1200. EXPECT_EQ(1U, dic.count("Key"));
  1201. EXPECT_EQ(1U, dic.count("key"));
  1202. EXPECT_EQ("upper", dic.find("Key")->second);
  1203. EXPECT_EQ("lower", dic.find("key")->second);
  1204. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1205. }
  1206. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1207. Server svr;
  1208. std::string order;
  1209. svr.Get("/order", [&](const Request &req, Response &res) {
  1210. order = entries_to_string(req.params);
  1211. res.set_content("ok", "text/plain");
  1212. });
  1213. auto port = svr.bind_to_any_port(HOST);
  1214. thread t = thread([&] { svr.listen_after_bind(); });
  1215. auto se = detail::scope_exit([&] {
  1216. svr.stop();
  1217. t.join();
  1218. ASSERT_FALSE(svr.is_running());
  1219. });
  1220. svr.wait_until_ready();
  1221. Client cli(HOST, port);
  1222. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1225. }
  1226. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1227. Server svr;
  1228. std::string field_order, file_order;
  1229. svr.Post("/order", [&](const Request &req, Response &res) {
  1230. for (const auto &field : req.form.fields) {
  1231. field_order += field.first + "=" + field.second.content + " ";
  1232. }
  1233. for (const auto &file : req.form.files) {
  1234. file_order += file.first + "=" + file.second.filename + " ";
  1235. }
  1236. res.set_content("ok", "text/plain");
  1237. });
  1238. auto port = svr.bind_to_any_port(HOST);
  1239. thread t = thread([&] { svr.listen_after_bind(); });
  1240. auto se = detail::scope_exit([&] {
  1241. svr.stop();
  1242. t.join();
  1243. ASSERT_FALSE(svr.is_running());
  1244. });
  1245. svr.wait_until_ready();
  1246. UploadFormDataItems items = {
  1247. {"zulu", "1", "", ""},
  1248. {"alpha", "2", "", ""},
  1249. {"mike", "3", "", ""},
  1250. {"zebra", "z", "z.txt", "text/plain"},
  1251. {"apple", "a", "a.txt", "text/plain"},
  1252. };
  1253. Client cli(HOST, port);
  1254. auto res = cli.Post("/order", items);
  1255. ASSERT_TRUE(res);
  1256. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1257. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1258. }
  1259. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1260. Server svr;
  1261. std::vector<std::string> values;
  1262. std::string first, second, out_of_range, order;
  1263. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1264. values = req.form.get_fields("tag");
  1265. first = req.form.get_field("tag", 0);
  1266. second = req.form.get_field("tag", 1);
  1267. out_of_range = req.form.get_field("tag", 2);
  1268. for (const auto &field : req.form.fields) {
  1269. order += field.first + "=" + field.second.content + " ";
  1270. }
  1271. res.set_content("ok", "text/plain");
  1272. });
  1273. auto port = svr.bind_to_any_port(HOST);
  1274. thread t = thread([&] { svr.listen_after_bind(); });
  1275. auto se = detail::scope_exit([&] {
  1276. svr.stop();
  1277. t.join();
  1278. ASSERT_FALSE(svr.is_running());
  1279. });
  1280. svr.wait_until_ready();
  1281. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1282. // not adjacent in the container.
  1283. UploadFormDataItems items = {
  1284. {"tag", "first", "", ""},
  1285. {"other", "x", "", ""},
  1286. {"tag", "second", "", ""},
  1287. };
  1288. Client cli(HOST, port);
  1289. auto res = cli.Post("/repeated", items);
  1290. ASSERT_TRUE(res);
  1291. ASSERT_EQ(2U, values.size());
  1292. EXPECT_EQ("first", values[0]);
  1293. EXPECT_EQ("second", values[1]);
  1294. EXPECT_EQ("first", first);
  1295. EXPECT_EQ("second", second);
  1296. // std::multimap already kept entries sharing a name in insertion order, so
  1297. // everything above passes without this change too. The whole traversal is
  1298. // what tells the two apart: sorting by name would hoist "other" to the front
  1299. // and the two "tag" parts would end up adjacent.
  1300. EXPECT_EQ("tag=first other=x tag=second ", order);
  1301. // Advancing past the last entry of a name used to run off the container;
  1302. // the container's saturating increment makes it return the default instead.
  1303. EXPECT_EQ("", out_of_range);
  1304. }
  1305. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1306. // Server::read_content() keeps a FormFields::iterator alive across the
  1307. // content callbacks that fill the part it points at. The container is
  1308. // vector-backed, so a later emplace can reallocate and invalidate an older
  1309. // iterator; 64 parts grow the vector through seven reallocations, which
  1310. // checks that every part's content still lands in its own entry.
  1311. const size_t part_count = 64;
  1312. // One formula for both the parts sent and the values expected back, so the
  1313. // two cannot drift apart.
  1314. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1315. auto content_of = [](size_t i) {
  1316. return std::string(64, static_cast<char>('a' + (i % 26)));
  1317. };
  1318. Server svr;
  1319. std::vector<std::pair<std::string, std::string>> received;
  1320. svr.Post("/many", [&](const Request &req, Response &res) {
  1321. for (const auto &field : req.form.fields) {
  1322. received.emplace_back(field.first, field.second.content);
  1323. }
  1324. res.set_content("ok", "text/plain");
  1325. });
  1326. auto port = svr.bind_to_any_port(HOST);
  1327. thread t = thread([&] { svr.listen_after_bind(); });
  1328. auto se = detail::scope_exit([&] {
  1329. svr.stop();
  1330. t.join();
  1331. ASSERT_FALSE(svr.is_running());
  1332. });
  1333. svr.wait_until_ready();
  1334. UploadFormDataItems items;
  1335. for (size_t i = 0; i < part_count; i++) {
  1336. items.push_back({name_of(i), content_of(i), "", ""});
  1337. }
  1338. Client cli(HOST, port);
  1339. auto res = cli.Post("/many", items);
  1340. ASSERT_TRUE(res);
  1341. ASSERT_EQ(part_count, received.size());
  1342. for (size_t i = 0; i < part_count; i++) {
  1343. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1344. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1345. }
  1346. }
  1347. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1348. string content_type = "multipart/form-data; boundary=something";
  1349. string boundary;
  1350. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1351. EXPECT_TRUE(ret);
  1352. EXPECT_EQ(boundary, "something");
  1353. }
  1354. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1355. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1356. string boundary;
  1357. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1358. EXPECT_TRUE(ret);
  1359. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1360. }
  1361. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1362. string content_type =
  1363. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1364. string boundary;
  1365. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1366. EXPECT_TRUE(ret);
  1367. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1368. }
  1369. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1370. string content_type =
  1371. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1372. string boundary;
  1373. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1374. EXPECT_TRUE(ret);
  1375. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1376. }
  1377. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1378. const string boundary(70, 'a');
  1379. string content_type = "multipart/form-data; boundary=" + boundary;
  1380. string parsed;
  1381. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1382. EXPECT_TRUE(ret);
  1383. EXPECT_EQ(parsed, boundary);
  1384. }
  1385. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1386. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1387. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1388. string parsed;
  1389. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1390. EXPECT_FALSE(ret);
  1391. }
  1392. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1393. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1394. // is 72 characters on the wire and still valid.
  1395. const string boundary(70, 'a');
  1396. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1397. string parsed;
  1398. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1399. EXPECT_EQ(parsed, boundary);
  1400. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1401. parsed.clear();
  1402. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1403. }
  1404. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1405. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1406. // The parameter parser must not treat that '=' as the key/value separator.
  1407. string content_type =
  1408. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1409. "charset=UTF-8";
  1410. string parsed;
  1411. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1412. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1413. }
  1414. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1415. // A ';' inside the quoted-string is part of the value, not a parameter
  1416. // separator, so it must not truncate the boundary.
  1417. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1418. string parsed;
  1419. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1420. EXPECT_EQ(parsed, "a;b");
  1421. }
  1422. TEST(ParseDispositionParamsTest, QuotedValues) {
  1423. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1424. // ';' and '=' are ordinary characters inside one.
  1425. struct {
  1426. const char *value;
  1427. std::vector<std::pair<const char *, const char *>> expected;
  1428. } cases[] = {
  1429. {"name=\"file1\"; filename=\"a.txt\"",
  1430. {{"name", "file1"}, {"filename", "a.txt"}}},
  1431. // Whitespace around '=' and ';' is still trimmed
  1432. {"name=\"file2\" ;filename = \"a.html\"",
  1433. {{"name", "file2"}, {"filename", "a.html"}}},
  1434. // '=' inside the value used to leave only the text after the last one
  1435. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1436. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1437. {"name=\"x=y\"", {{"name", "x=y"}}},
  1438. // ';' inside the value used to truncate the pair and leave a bogus one
  1439. {"name=\"file3\"; filename=\"a;b.txt\"",
  1440. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1441. // An unquoted value keeps working, and so does filename*
  1442. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1443. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1444. // A parameter with no key is dropped rather than turned into one whose
  1445. // key is the value
  1446. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1447. };
  1448. for (const auto &c : cases) {
  1449. Params params;
  1450. detail::parse_disposition_params(c.value, params);
  1451. for (const auto &kv : c.expected) {
  1452. auto it = params.find(kv.first);
  1453. ASSERT_NE(it, params.end())
  1454. << "value: " << c.value << ", key: " << kv.first;
  1455. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1456. }
  1457. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1458. }
  1459. }
  1460. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1461. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1462. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1463. Server svr;
  1464. std::string field_value, file_name, file_filename;
  1465. bool has_field = false, has_file = false;
  1466. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1467. has_field = req.form.has_field("x=y");
  1468. field_value = req.form.get_field("x=y");
  1469. has_file = req.form.has_file("file1");
  1470. const auto &file = req.form.get_file("file1");
  1471. file_name = file.name;
  1472. file_filename = file.filename;
  1473. res.set_content("ok", "text/plain");
  1474. });
  1475. auto port = svr.bind_to_any_port(HOST);
  1476. thread t = thread([&] { svr.listen_after_bind(); });
  1477. auto se = detail::scope_exit([&] {
  1478. svr.stop();
  1479. t.join();
  1480. ASSERT_FALSE(svr.is_running());
  1481. });
  1482. svr.wait_until_ready();
  1483. UploadFormDataItems items = {
  1484. {"x=y", "field-value", "", ""},
  1485. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1486. };
  1487. Client cli(HOST, port);
  1488. auto res = cli.Post("/quoted", items);
  1489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1490. ASSERT_EQ(StatusCode::OK_200, res->status);
  1491. EXPECT_TRUE(has_field);
  1492. EXPECT_EQ("field-value", field_value);
  1493. EXPECT_TRUE(has_file);
  1494. EXPECT_EQ("file1", file_name);
  1495. EXPECT_EQ("a;b=report.pdf", file_filename);
  1496. }
  1497. TEST(GetHeaderValueTest, DefaultValue) {
  1498. Headers headers = {{"Dummy", "Dummy"}};
  1499. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1500. EXPECT_STREQ("text/plain", val);
  1501. }
  1502. TEST(GetHeaderValueTest, DefaultValueInt) {
  1503. Headers headers = {{"Dummy", "Dummy"}};
  1504. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1505. EXPECT_EQ(100ull, val);
  1506. }
  1507. TEST(GetHeaderValueTest, RegularValue) {
  1508. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1509. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1510. EXPECT_STREQ("text/html", val);
  1511. }
  1512. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1513. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1514. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1515. EXPECT_STREQ("text/html", val);
  1516. }
  1517. TEST(GetHeaderValueTest, SetContent) {
  1518. Response res;
  1519. res.set_content("html", "text/html");
  1520. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1521. res.set_content("text", "text/plain");
  1522. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1523. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1524. }
  1525. TEST(GetHeaderValueTest, RegularValueInt) {
  1526. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1527. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1528. EXPECT_EQ(100ull, val);
  1529. }
  1530. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1531. Headers headers = {{"Content-Length", "x"}};
  1532. auto is_invalid_value = false;
  1533. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1534. is_invalid_value);
  1535. EXPECT_EQ(0ull, val);
  1536. EXPECT_TRUE(is_invalid_value);
  1537. }
  1538. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1539. // An all-digit value that overflows size_t must be reported as invalid, not
  1540. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1541. // a large length to a small one on 32-bit builds, leaving the framing length
  1542. // wrong while is_invalid_value stayed false.
  1543. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1544. auto is_invalid_value = false;
  1545. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1546. is_invalid_value);
  1547. EXPECT_TRUE(is_invalid_value);
  1548. // A well-formed length is unaffected.
  1549. Headers ok = {{"Content-Length", "1234"}};
  1550. is_invalid_value = false;
  1551. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1552. is_invalid_value);
  1553. EXPECT_EQ(1234ull, val);
  1554. EXPECT_FALSE(is_invalid_value);
  1555. }
  1556. TEST(GetHeaderValueTest, Range) {
  1557. {
  1558. Headers headers = {make_range_header({{1, -1}})};
  1559. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1560. EXPECT_STREQ("bytes=1-", val);
  1561. }
  1562. {
  1563. Headers headers = {make_range_header({{-1, 1}})};
  1564. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1565. EXPECT_STREQ("bytes=-1", val);
  1566. }
  1567. {
  1568. Headers headers = {make_range_header({{1, 10}})};
  1569. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1570. EXPECT_STREQ("bytes=1-10", val);
  1571. }
  1572. {
  1573. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1574. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1575. EXPECT_STREQ("bytes=1-10, 100-", val);
  1576. }
  1577. {
  1578. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1579. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1580. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1581. }
  1582. {
  1583. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1584. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1585. EXPECT_STREQ("bytes=0-0, -1", val);
  1586. }
  1587. }
  1588. TEST(BearerTokenAuthTest, SchemeValidation) {
  1589. // A value shorter than "Bearer " must not throw from the fixed-length
  1590. // substr, and a non-Bearer scheme must not be reported as a token.
  1591. struct {
  1592. const char *value;
  1593. const char *expected;
  1594. } cases[] = {
  1595. {"x", ""},
  1596. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1597. {"Bearer abc123", "abc123"},
  1598. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1599. };
  1600. for (const auto &c : cases) {
  1601. Request req;
  1602. req.set_header("Authorization", c.value);
  1603. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1604. }
  1605. }
  1606. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1607. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1608. // to depend on the standard library (libstdc++ handed back duplicates in
  1609. // reverse insertion order, libc++ in insertion order).
  1610. Request req;
  1611. req.set_header("Accept-Encoding", "gzip");
  1612. req.set_header("Accept-Encoding", "deflate");
  1613. req.set_header("Accept-Encoding", "br");
  1614. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1615. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1616. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1617. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1618. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1619. }
  1620. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1621. Request req;
  1622. req.set_header("X-Test", "only");
  1623. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1624. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1625. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1626. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1627. }
  1628. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1629. Headers headers;
  1630. headers.emplace("Host", "example.com");
  1631. headers.emplace("Accept-Encoding", "gzip");
  1632. headers.emplace("User-Agent", "test");
  1633. headers.emplace("Accept-Encoding", "deflate");
  1634. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1635. "Accept-Encoding=deflate ",
  1636. entries_to_string(headers));
  1637. }
  1638. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1639. Headers headers = {{"Content-Type", "text/html"},
  1640. {"CONTENT-TYPE", "text/xml"}};
  1641. EXPECT_EQ(2U, headers.count("content-type"));
  1642. auto it = headers.find("content-type");
  1643. ASSERT_TRUE(it != headers.end());
  1644. EXPECT_EQ("text/html", it->second);
  1645. }
  1646. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1647. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1648. // drop only those fields and leave everything positioned between them.
  1649. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1650. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1651. auto rng = headers.equal_range("a");
  1652. headers.erase(rng.first, rng.second);
  1653. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1654. }
  1655. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1656. Headers headers = {
  1657. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1658. EXPECT_EQ(3U, headers.erase("A"));
  1659. EXPECT_EQ(0U, headers.count("A"));
  1660. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1661. }
  1662. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1663. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1664. headers.emplace_front("Host", "example.com");
  1665. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1666. entries_to_string(headers));
  1667. }
  1668. TEST(ParseHeaderValueTest, Range) {
  1669. {
  1670. Ranges ranges;
  1671. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1672. EXPECT_TRUE(ret);
  1673. EXPECT_EQ(1u, ranges.size());
  1674. EXPECT_EQ(1u, ranges[0].first);
  1675. EXPECT_EQ(-1, ranges[0].second);
  1676. }
  1677. {
  1678. Ranges ranges;
  1679. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1680. EXPECT_TRUE(ret);
  1681. EXPECT_EQ(1u, ranges.size());
  1682. EXPECT_EQ(-1, ranges[0].first);
  1683. EXPECT_EQ(1u, ranges[0].second);
  1684. }
  1685. {
  1686. Ranges ranges;
  1687. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1688. EXPECT_TRUE(ret);
  1689. EXPECT_EQ(1u, ranges.size());
  1690. EXPECT_EQ(1u, ranges[0].first);
  1691. EXPECT_EQ(10u, ranges[0].second);
  1692. }
  1693. {
  1694. Ranges ranges;
  1695. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1696. EXPECT_FALSE(ret);
  1697. }
  1698. {
  1699. Ranges ranges;
  1700. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1701. EXPECT_TRUE(ret);
  1702. EXPECT_EQ(2u, ranges.size());
  1703. EXPECT_EQ(1u, ranges[0].first);
  1704. EXPECT_EQ(10u, ranges[0].second);
  1705. EXPECT_EQ(100u, ranges[1].first);
  1706. EXPECT_EQ(-1, ranges[1].second);
  1707. }
  1708. {
  1709. Ranges ranges;
  1710. auto ret =
  1711. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1712. EXPECT_TRUE(ret);
  1713. EXPECT_EQ(3u, ranges.size());
  1714. EXPECT_EQ(1u, ranges[0].first);
  1715. EXPECT_EQ(10u, ranges[0].second);
  1716. EXPECT_EQ(100u, ranges[1].first);
  1717. EXPECT_EQ(200u, ranges[1].second);
  1718. EXPECT_EQ(300u, ranges[2].first);
  1719. EXPECT_EQ(400u, ranges[2].second);
  1720. }
  1721. {
  1722. Ranges ranges;
  1723. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1724. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1725. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1726. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1727. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1728. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1729. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1730. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1731. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1732. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1733. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1734. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1735. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1736. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1737. EXPECT_FALSE(
  1738. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1739. EXPECT_TRUE(ranges.empty());
  1740. }
  1741. {
  1742. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1743. // remainder of the representation, so it stays accepted.
  1744. Ranges ranges;
  1745. auto ret =
  1746. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1747. EXPECT_TRUE(ret);
  1748. ASSERT_EQ(1u, ranges.size());
  1749. EXPECT_EQ(0, ranges[0].first);
  1750. EXPECT_EQ(-1, ranges[0].second);
  1751. }
  1752. // RFC 9110 14.1: range unit names are case-insensitive.
  1753. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1754. Ranges ranges;
  1755. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1756. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1757. }
  1758. }
  1759. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1760. Request req;
  1761. req.set_header("Accept-Encoding", "gzip");
  1762. Response res;
  1763. res.set_header("Content-Type", "text/plain");
  1764. auto ret = detail::encoding_type(req, res);
  1765. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1766. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1767. #else
  1768. EXPECT_TRUE(ret == detail::EncodingType::None);
  1769. #endif
  1770. }
  1771. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1772. Request req;
  1773. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1774. Response res;
  1775. res.set_header("Content-Type", "text/plain");
  1776. auto ret = detail::encoding_type(req, res);
  1777. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1778. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1779. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1780. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1781. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1782. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1783. #else
  1784. EXPECT_TRUE(ret == detail::EncodingType::None);
  1785. #endif
  1786. }
  1787. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1788. Request req;
  1789. req.set_header("Accept-Encoding",
  1790. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1791. Response res;
  1792. res.set_header("Content-Type", "text/plain");
  1793. auto ret = detail::encoding_type(req, res);
  1794. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1795. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1796. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1797. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1798. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1799. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1800. #else
  1801. EXPECT_TRUE(ret == detail::EncodingType::None);
  1802. #endif
  1803. }
  1804. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1805. // All supported encodings rejected with q=0 should return None
  1806. Request req;
  1807. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1808. Response res;
  1809. res.set_header("Content-Type", "text/plain");
  1810. auto ret = detail::encoding_type(req, res);
  1811. EXPECT_TRUE(ret == detail::EncodingType::None);
  1812. }
  1813. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1814. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1815. Request req;
  1816. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1817. Response res;
  1818. res.set_header("Content-Type", "text/plain");
  1819. auto ret = detail::encoding_type(req, res);
  1820. EXPECT_TRUE(ret == detail::EncodingType::None);
  1821. }
  1822. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1823. Request req;
  1824. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1825. Response res;
  1826. res.set_header("Content-Type", "text/plain");
  1827. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1828. }
  1829. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1830. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1831. Request req;
  1832. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1833. Response res;
  1834. res.set_header("Content-Type", "text/plain");
  1835. auto ret = detail::encoding_type(req, res);
  1836. EXPECT_TRUE(ret == detail::EncodingType::None);
  1837. }
  1838. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1839. // RFC 7231: Accept-Encoding values are case-insensitive
  1840. Request req;
  1841. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1842. Response res;
  1843. res.set_header("Content-Type", "text/plain");
  1844. auto ret = detail::encoding_type(req, res);
  1845. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1846. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1847. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1848. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1849. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1850. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1851. #else
  1852. EXPECT_TRUE(ret == detail::EncodingType::None);
  1853. #endif
  1854. }
  1855. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1856. // q value should determine priority, not hardcoded order
  1857. Request req;
  1858. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1859. Response res;
  1860. res.set_header("Content-Type", "text/plain");
  1861. auto ret = detail::encoding_type(req, res);
  1862. // gzip has highest q=1.0, so it should be selected even though
  1863. // br and zstd are also supported
  1864. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1865. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1866. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1867. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1868. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1869. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1870. #else
  1871. EXPECT_TRUE(ret == detail::EncodingType::None);
  1872. #endif
  1873. }
  1874. TEST(BufferStreamTest, read) {
  1875. detail::BufferStream strm1;
  1876. Stream &strm = strm1;
  1877. EXPECT_EQ(5, strm.write("hello"));
  1878. char buf[512];
  1879. EXPECT_EQ(2, strm.read(buf, 2));
  1880. EXPECT_EQ('h', buf[0]);
  1881. EXPECT_EQ('e', buf[1]);
  1882. EXPECT_EQ(2, strm.read(buf, 2));
  1883. EXPECT_EQ('l', buf[0]);
  1884. EXPECT_EQ('l', buf[1]);
  1885. EXPECT_EQ(1, strm.read(buf, 1));
  1886. EXPECT_EQ('o', buf[0]);
  1887. EXPECT_EQ(0, strm.read(buf, 1));
  1888. }
  1889. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1890. auto host = "www.httpwatch.com";
  1891. auto ip = hosted_at(host);
  1892. EXPECT_EQ("23.96.13.243", ip);
  1893. std::vector<std::string> addrs;
  1894. hosted_at(host, addrs);
  1895. EXPECT_EQ(1u, addrs.size());
  1896. }
  1897. #if 0 // It depends on each test environment...
  1898. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1899. auto host = "www.youtube.com";
  1900. std::vector<std::string> addrs;
  1901. hosted_at(host, addrs);
  1902. EXPECT_EQ(20u, addrs.size());
  1903. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1904. EXPECT_TRUE(it != addrs.end());
  1905. }
  1906. #endif
  1907. class ChunkedEncodingTest : public ::testing::Test {
  1908. protected:
  1909. ChunkedEncodingTest()
  1910. : cli_(HOST, PORT)
  1911. #ifdef CPPHTTPLIB_SSL_ENABLED
  1912. ,
  1913. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1914. #endif
  1915. {
  1916. cli_.set_connection_timeout(2);
  1917. #ifdef CPPHTTPLIB_SSL_ENABLED
  1918. cli_.enable_server_certificate_verification(false);
  1919. #endif
  1920. }
  1921. virtual void SetUp() {
  1922. read_file("./image.jpg", image_data_);
  1923. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1924. res.set_content("Hello World!", "text/plain");
  1925. });
  1926. svr_.Get(
  1927. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1928. res.set_chunked_content_provider(
  1929. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1930. size_t remaining = image_data_.size() - offset;
  1931. if (remaining == 0) {
  1932. sink.done();
  1933. } else {
  1934. constexpr size_t CHUNK_SIZE = 1024;
  1935. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1936. sink.write(&image_data_[offset], send_size);
  1937. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1938. }
  1939. return true;
  1940. });
  1941. });
  1942. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1943. svr_.wait_until_ready();
  1944. }
  1945. virtual void TearDown() {
  1946. svr_.stop();
  1947. if (!request_threads_.empty()) {
  1948. std::this_thread::sleep_for(std::chrono::seconds(1));
  1949. for (auto &t : request_threads_) {
  1950. t.join();
  1951. }
  1952. }
  1953. t_.join();
  1954. }
  1955. #ifdef CPPHTTPLIB_SSL_ENABLED
  1956. SSLClient cli_;
  1957. SSLServer svr_;
  1958. #else
  1959. Client cli_;
  1960. Server svr_;
  1961. #endif
  1962. thread t_;
  1963. std::vector<thread> request_threads_;
  1964. std::string image_data_;
  1965. };
  1966. TEST_F(ChunkedEncodingTest, NormalGet) {
  1967. auto res = cli_.Get("/chunked");
  1968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1969. std::string out;
  1970. read_file("./image.jpg", out);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. EXPECT_EQ(out, res->body);
  1973. }
  1974. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1975. std::string body;
  1976. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1977. body.append(data, data_length);
  1978. return true;
  1979. });
  1980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1981. std::string out;
  1982. read_file("./image.jpg", out);
  1983. EXPECT_EQ(StatusCode::OK_200, res->status);
  1984. EXPECT_EQ(out, body);
  1985. }
  1986. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1987. std::string body;
  1988. auto res = cli_.Get(
  1989. "/chunked",
  1990. [&](const Response &response) {
  1991. EXPECT_EQ(StatusCode::OK_200, response.status);
  1992. return true;
  1993. },
  1994. [&](const char *data, size_t data_length) {
  1995. body.append(data, data_length);
  1996. return true;
  1997. });
  1998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1999. std::string out;
  2000. read_file("./image.jpg", out);
  2001. EXPECT_EQ(StatusCode::OK_200, res->status);
  2002. EXPECT_EQ(out, body);
  2003. }
  2004. TEST(RangeTest, FromHTTPBin_Online) {
  2005. auto host = "httpbingo.org";
  2006. auto path = std::string{"/range/32"};
  2007. #ifdef CPPHTTPLIB_SSL_ENABLED
  2008. auto port = 443;
  2009. SSLClient cli(host, port);
  2010. #else
  2011. auto port = 80;
  2012. Client cli(host, port);
  2013. #endif
  2014. cli.set_connection_timeout(5);
  2015. {
  2016. auto res = cli.Get(path);
  2017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2018. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2019. EXPECT_EQ(StatusCode::OK_200, res->status);
  2020. }
  2021. {
  2022. Headers headers = {make_range_header({{1, -1}})};
  2023. auto res = cli.Get(path, headers);
  2024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2025. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2027. }
  2028. {
  2029. Headers headers = {make_range_header({{1, 10}})};
  2030. auto res = cli.Get(path, headers);
  2031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2032. EXPECT_EQ("bcdefghijk", res->body);
  2033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2034. }
  2035. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2036. // entire resource, while the original httpbin returned 200. Both are
  2037. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2038. {
  2039. Headers headers = {make_range_header({{0, 31}})};
  2040. auto res = cli.Get(path, headers);
  2041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2042. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2043. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2044. res->status == StatusCode::PartialContent_206);
  2045. }
  2046. {
  2047. Headers headers = {make_range_header({{0, -1}})};
  2048. auto res = cli.Get(path, headers);
  2049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2050. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2051. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2052. res->status == StatusCode::PartialContent_206);
  2053. }
  2054. // go-httpbin returns 206 with clamped range for over-range requests,
  2055. // while the original httpbin returned 416. Both behaviors are observed
  2056. // in real servers, so we only verify the request succeeds.
  2057. {
  2058. Headers headers = {make_range_header({{0, 32}})};
  2059. auto res = cli.Get(path, headers);
  2060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2061. }
  2062. }
  2063. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2064. auto host = "unresolvableaddress.local";
  2065. auto path = std::string{"/"};
  2066. #ifdef CPPHTTPLIB_SSL_ENABLED
  2067. auto port = 443;
  2068. SSLClient cli(host, port);
  2069. #else
  2070. auto port = 80;
  2071. Client cli(host, port);
  2072. #endif
  2073. cli.set_connection_timeout(1);
  2074. {
  2075. auto res = cli.Get(path);
  2076. ASSERT_FALSE(res);
  2077. }
  2078. std::this_thread::sleep_for(std::chrono::seconds(8));
  2079. }
  2080. #if defined(__linux__) && defined(__GLIBC__) && \
  2081. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2082. // Forward declaration: in split builds split.py strips `inline` and moves the
  2083. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2084. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2085. // against the symbol in both header-only and split builds.
  2086. namespace httplib {
  2087. namespace detail {
  2088. int getaddrinfo_with_timeout(const char *node, const char *service,
  2089. const struct addrinfo *hints,
  2090. struct addrinfo **res, time_t timeout_sec);
  2091. } // namespace detail
  2092. } // namespace httplib
  2093. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2094. //
  2095. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2096. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2097. // gai_suspend() call hits the connection timeout the function calls
  2098. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2099. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2100. // still alive and still references the now-destroyed stack frame.
  2101. //
  2102. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2103. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2104. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2105. // and runs them in a container.
  2106. namespace {
  2107. bool should_run_issue_2431_tests() {
  2108. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2109. return v && *v && std::string(v) != "0";
  2110. }
  2111. std::string unique_unresolvable_host(int n) {
  2112. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2113. // glibc still asks the configured nameserver — which is exactly the path
  2114. // we want to exercise. A unique label per call avoids the resolver cache.
  2115. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2116. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2117. std::to_string(n) + ".invalid";
  2118. }
  2119. } // namespace
  2120. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2121. if (!should_run_issue_2431_tests()) {
  2122. GTEST_SKIP()
  2123. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2124. }
  2125. for (int i = 0; i < 8; ++i) {
  2126. struct addrinfo hints;
  2127. memset(&hints, 0, sizeof(hints));
  2128. hints.ai_family = AF_UNSPEC;
  2129. hints.ai_socktype = SOCK_STREAM;
  2130. auto host = unique_unresolvable_host(i);
  2131. struct addrinfo *result = nullptr;
  2132. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2133. &result, /*timeout_sec=*/1);
  2134. if (rc == 0 && result) { freeaddrinfo(result); }
  2135. }
  2136. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2137. // stack region they still believe holds their gaicb.
  2138. std::this_thread::sleep_for(std::chrono::seconds(3));
  2139. }
  2140. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2141. if (!should_run_issue_2431_tests()) {
  2142. GTEST_SKIP()
  2143. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2144. }
  2145. std::atomic<bool> stop{false};
  2146. std::vector<std::thread> threads;
  2147. for (int t = 0; t < 8; ++t) {
  2148. threads.emplace_back([t, &stop] {
  2149. int i = 0;
  2150. while (!stop.load(std::memory_order_relaxed)) {
  2151. struct addrinfo hints;
  2152. memset(&hints, 0, sizeof(hints));
  2153. hints.ai_family = AF_UNSPEC;
  2154. hints.ai_socktype = SOCK_STREAM;
  2155. auto host = unique_unresolvable_host(t * 100000 + i++);
  2156. struct addrinfo *result = nullptr;
  2157. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2158. &result, /*timeout_sec=*/1);
  2159. if (rc == 0 && result) { freeaddrinfo(result); }
  2160. }
  2161. });
  2162. }
  2163. std::this_thread::sleep_for(std::chrono::seconds(8));
  2164. stop.store(true, std::memory_order_relaxed);
  2165. for (auto &th : threads) {
  2166. th.join();
  2167. }
  2168. std::this_thread::sleep_for(std::chrono::seconds(3));
  2169. }
  2170. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2171. if (!should_run_issue_2431_tests()) {
  2172. GTEST_SKIP()
  2173. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2174. }
  2175. std::atomic<bool> stop{false};
  2176. std::vector<std::thread> threads;
  2177. for (int t = 0; t < 8; ++t) {
  2178. threads.emplace_back([t, &stop] {
  2179. int i = 0;
  2180. while (!stop.load(std::memory_order_relaxed)) {
  2181. auto host = unique_unresolvable_host(t * 100000 + i++);
  2182. Client cli(host, 80);
  2183. cli.set_connection_timeout(1, 0);
  2184. cli.set_read_timeout(1, 0);
  2185. cli.set_write_timeout(1, 0);
  2186. (void)cli.Get("/");
  2187. }
  2188. });
  2189. }
  2190. std::this_thread::sleep_for(std::chrono::seconds(8));
  2191. stop.store(true, std::memory_order_relaxed);
  2192. for (auto &th : threads) {
  2193. th.join();
  2194. }
  2195. std::this_thread::sleep_for(std::chrono::seconds(3));
  2196. }
  2197. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2198. TEST(ConnectionErrorTest, InvalidHost) {
  2199. auto host = "-abcde.com";
  2200. #ifdef CPPHTTPLIB_SSL_ENABLED
  2201. auto port = 443;
  2202. SSLClient cli(host, port);
  2203. #else
  2204. auto port = 80;
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_EQ(Error::Connection, res.error());
  2211. }
  2212. TEST(ConnectionErrorTest, InvalidHost2) {
  2213. auto host = "httpcan.org/";
  2214. #ifdef CPPHTTPLIB_SSL_ENABLED
  2215. SSLClient cli(host);
  2216. #else
  2217. Client cli(host);
  2218. #endif
  2219. cli.set_connection_timeout(std::chrono::seconds(2));
  2220. auto res = cli.Get("/");
  2221. ASSERT_TRUE(!res);
  2222. EXPECT_EQ(Error::Connection, res.error());
  2223. }
  2224. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2225. auto host = "httpcan.org/";
  2226. #ifdef CPPHTTPLIB_SSL_ENABLED
  2227. SSLClient cli(host);
  2228. #else
  2229. Client cli(host);
  2230. #endif
  2231. cli.set_connection_timeout(std::chrono::seconds(2));
  2232. auto res = cli.Get("/");
  2233. ASSERT_TRUE(!res);
  2234. stringstream s;
  2235. s << "error code: " << res.error();
  2236. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2237. }
  2238. TEST(ConnectionErrorTest, InvalidPort) {
  2239. auto host = "localhost";
  2240. auto port = 44380;
  2241. #ifdef CPPHTTPLIB_SSL_ENABLED
  2242. SSLClient cli(host, port);
  2243. #else
  2244. Client cli(host, port);
  2245. #endif
  2246. cli.set_connection_timeout(std::chrono::seconds(2));
  2247. auto res = cli.Get("/");
  2248. ASSERT_TRUE(!res);
  2249. EXPECT_TRUE(Error::Connection == res.error() ||
  2250. Error::ConnectionTimeout == res.error());
  2251. }
  2252. TEST(ConnectionErrorTest, Timeout_Online) {
  2253. auto host = "google.com";
  2254. #ifdef CPPHTTPLIB_SSL_ENABLED
  2255. auto port = 44380;
  2256. SSLClient cli(host, port);
  2257. #else
  2258. auto port = 8080;
  2259. Client cli(host, port);
  2260. #endif
  2261. cli.set_connection_timeout(std::chrono::seconds(2));
  2262. // only probe one address type so that the error reason
  2263. // correlates to the timed-out IPv4, not the unsupported
  2264. // IPv6 connection attempt
  2265. cli.set_address_family(AF_INET);
  2266. auto res = cli.Get("/");
  2267. ASSERT_TRUE(!res);
  2268. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2269. }
  2270. TEST(CancelTest, NoCancel_Online) {
  2271. auto host = "httpbingo.org";
  2272. auto path = std::string{"/range/32"};
  2273. #ifdef CPPHTTPLIB_SSL_ENABLED
  2274. auto port = 443;
  2275. SSLClient cli(host, port);
  2276. #else
  2277. auto port = 80;
  2278. Client cli(host, port);
  2279. #endif
  2280. cli.set_connection_timeout(std::chrono::seconds(5));
  2281. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2283. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2284. EXPECT_EQ(StatusCode::OK_200, res->status);
  2285. }
  2286. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2287. // Use /bytes with a large payload so that the DownloadProgress callback
  2288. // (which only fires for Content-Length responses) is invoked before the
  2289. // entire body is received, giving cancellation a chance to fire.
  2290. auto host = "httpbingo.org";
  2291. auto path = std::string{"/bytes/524288"};
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. auto port = 443;
  2294. SSLClient cli(host, port);
  2295. #else
  2296. auto port = 80;
  2297. Client cli(host, port);
  2298. #endif
  2299. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2300. cli.set_connection_timeout(std::chrono::seconds(5));
  2301. ASSERT_TRUE(!res);
  2302. EXPECT_EQ(Error::Canceled, res.error());
  2303. }
  2304. TEST(CancelTest, WithCancelLargePayload_Online) {
  2305. auto host = "httpbingo.org";
  2306. auto path = std::string{"/bytes/524288"};
  2307. #ifdef CPPHTTPLIB_SSL_ENABLED
  2308. auto port = 443;
  2309. SSLClient cli(host, port);
  2310. #else
  2311. auto port = 80;
  2312. Client cli(host, port);
  2313. #endif
  2314. cli.set_connection_timeout(std::chrono::seconds(5));
  2315. uint32_t count = 0;
  2316. auto res =
  2317. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2318. ASSERT_TRUE(!res);
  2319. EXPECT_EQ(Error::Canceled, res.error());
  2320. }
  2321. TEST(CancelTest, NoCancelPost) {
  2322. Server svr;
  2323. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content("Hello World!", "text/plain");
  2325. });
  2326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2327. auto se = detail::scope_exit([&] {
  2328. svr.stop();
  2329. thread.join();
  2330. ASSERT_FALSE(svr.is_running());
  2331. });
  2332. svr.wait_until_ready();
  2333. Client cli(HOST, PORT);
  2334. cli.set_connection_timeout(std::chrono::seconds(5));
  2335. auto res =
  2336. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2337. "application/json", [](uint64_t, uint64_t) { return true; });
  2338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2339. EXPECT_EQ("Hello World!", res->body);
  2340. EXPECT_EQ(StatusCode::OK_200, res->status);
  2341. }
  2342. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2343. Server svr;
  2344. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2345. res.set_content("Hello World!", "text/plain");
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. cli.set_connection_timeout(std::chrono::seconds(5));
  2356. auto res =
  2357. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2358. "application/json", [](uint64_t, uint64_t) { return false; });
  2359. ASSERT_TRUE(!res);
  2360. EXPECT_EQ(Error::Canceled, res.error());
  2361. }
  2362. TEST(CancelTest, WithCancelLargePayloadPost) {
  2363. Server svr;
  2364. svr.set_payload_max_length(200 * 1024 * 1024);
  2365. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2366. res.set_content(LARGE_DATA, "text/plain");
  2367. });
  2368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2369. auto se = detail::scope_exit([&] {
  2370. svr.stop();
  2371. thread.join();
  2372. ASSERT_FALSE(svr.is_running());
  2373. });
  2374. svr.wait_until_ready();
  2375. Client cli(HOST, PORT);
  2376. cli.set_payload_max_length(200 * 1024 * 1024);
  2377. cli.set_connection_timeout(std::chrono::seconds(5));
  2378. auto res =
  2379. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2380. "application/json", [](uint64_t, uint64_t) { return false; });
  2381. ASSERT_TRUE(!res);
  2382. EXPECT_EQ(Error::Canceled, res.error());
  2383. }
  2384. TEST(CancelTest, NoCancelPut) {
  2385. Server svr;
  2386. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content("Hello World!", "text/plain");
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. Client cli(HOST, PORT);
  2397. cli.set_connection_timeout(std::chrono::seconds(5));
  2398. auto res =
  2399. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2400. "application/json", [](uint64_t, uint64_t) { return true; });
  2401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2402. EXPECT_EQ("Hello World!", res->body);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. }
  2405. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2406. Server svr;
  2407. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2408. res.set_content("Hello World!", "text/plain");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, PORT);
  2418. cli.set_connection_timeout(std::chrono::seconds(5));
  2419. auto res =
  2420. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2421. "application/json", [](uint64_t, uint64_t) { return false; });
  2422. ASSERT_TRUE(!res);
  2423. EXPECT_EQ(Error::Canceled, res.error());
  2424. }
  2425. TEST(CancelTest, WithCancelLargePayloadPut) {
  2426. Server svr;
  2427. svr.set_payload_max_length(200 * 1024 * 1024);
  2428. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2429. res.set_content(LARGE_DATA, "text/plain");
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. cli.set_payload_max_length(200 * 1024 * 1024);
  2440. cli.set_connection_timeout(std::chrono::seconds(5));
  2441. auto res =
  2442. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2443. "application/json", [](uint64_t, uint64_t) { return false; });
  2444. ASSERT_TRUE(!res);
  2445. EXPECT_EQ(Error::Canceled, res.error());
  2446. }
  2447. TEST(CancelTest, NoCancelPatch) {
  2448. Server svr;
  2449. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2450. res.set_content("Hello World!", "text/plain");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. Client cli(HOST, PORT);
  2460. cli.set_connection_timeout(std::chrono::seconds(5));
  2461. auto res =
  2462. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2463. "application/json", [](uint64_t, uint64_t) { return true; });
  2464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2465. EXPECT_EQ("Hello World!", res->body);
  2466. EXPECT_EQ(StatusCode::OK_200, res->status);
  2467. }
  2468. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2469. Server svr;
  2470. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  2480. Client cli(HOST, PORT);
  2481. cli.set_connection_timeout(std::chrono::seconds(5));
  2482. auto res =
  2483. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2484. "application/json", [](uint64_t, uint64_t) { return false; });
  2485. ASSERT_TRUE(!res);
  2486. EXPECT_EQ(Error::Canceled, res.error());
  2487. }
  2488. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2489. Server svr;
  2490. svr.set_payload_max_length(200 * 1024 * 1024);
  2491. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2492. res.set_content(LARGE_DATA, "text/plain");
  2493. });
  2494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2495. auto se = detail::scope_exit([&] {
  2496. svr.stop();
  2497. thread.join();
  2498. ASSERT_FALSE(svr.is_running());
  2499. });
  2500. svr.wait_until_ready();
  2501. Client cli(HOST, PORT);
  2502. cli.set_payload_max_length(200 * 1024 * 1024);
  2503. cli.set_connection_timeout(std::chrono::seconds(5));
  2504. auto res =
  2505. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2506. "application/json", [](uint64_t, uint64_t) { return false; });
  2507. ASSERT_TRUE(!res);
  2508. EXPECT_EQ(Error::Canceled, res.error());
  2509. }
  2510. TEST(CancelTest, NoCancelDelete) {
  2511. Server svr;
  2512. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2513. res.set_content("Hello World!", "text/plain");
  2514. });
  2515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2516. auto se = detail::scope_exit([&] {
  2517. svr.stop();
  2518. thread.join();
  2519. ASSERT_FALSE(svr.is_running());
  2520. });
  2521. svr.wait_until_ready();
  2522. Client cli(HOST, PORT);
  2523. cli.set_connection_timeout(std::chrono::seconds(5));
  2524. auto res =
  2525. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2526. "application/json", [](uint64_t, uint64_t) { return true; });
  2527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2528. EXPECT_EQ("Hello World!", res->body);
  2529. EXPECT_EQ(StatusCode::OK_200, res->status);
  2530. }
  2531. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2532. Server svr;
  2533. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2534. res.set_content("Hello World!", "text/plain");
  2535. });
  2536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2537. auto se = detail::scope_exit([&] {
  2538. svr.stop();
  2539. thread.join();
  2540. ASSERT_FALSE(svr.is_running());
  2541. });
  2542. svr.wait_until_ready();
  2543. Client cli(HOST, PORT);
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. auto res =
  2546. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2547. "application/json", [](uint64_t, uint64_t) { return false; });
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_EQ(Error::Canceled, res.error());
  2550. }
  2551. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2552. Server svr;
  2553. svr.set_payload_max_length(200 * 1024 * 1024);
  2554. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2555. res.set_content(LARGE_DATA, "text/plain");
  2556. });
  2557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2558. auto se = detail::scope_exit([&] {
  2559. svr.stop();
  2560. thread.join();
  2561. ASSERT_FALSE(svr.is_running());
  2562. });
  2563. svr.wait_until_ready();
  2564. Client cli(HOST, PORT);
  2565. cli.set_payload_max_length(200 * 1024 * 1024);
  2566. cli.set_connection_timeout(std::chrono::seconds(5));
  2567. auto res =
  2568. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2569. "application/json", [](uint64_t, uint64_t) { return false; });
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Canceled, res.error());
  2572. }
  2573. static std::string remove_whitespace(const std::string &input) {
  2574. std::string output;
  2575. output.reserve(input.size());
  2576. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2577. [](unsigned char c) { return !std::isspace(c); });
  2578. return output;
  2579. }
  2580. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2581. auto host = "httpbingo.org";
  2582. auto path = std::string{"/basic-auth/hello/world"};
  2583. #ifdef CPPHTTPLIB_SSL_ENABLED
  2584. auto port = 443;
  2585. SSLClient cli(host, port);
  2586. #else
  2587. auto port = 80;
  2588. Client cli(host, port);
  2589. #endif
  2590. {
  2591. auto res = cli.Get(path);
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2594. }
  2595. {
  2596. auto res = cli.Get(
  2597. path, Headers{make_basic_authentication_header("hello", "world")});
  2598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2599. auto body = remove_whitespace(res->body);
  2600. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2601. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2602. EXPECT_EQ(StatusCode::OK_200, res->status);
  2603. }
  2604. {
  2605. cli.set_basic_auth("hello", "world");
  2606. auto res = cli.Get(path);
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. auto body = remove_whitespace(res->body);
  2609. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2610. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2611. EXPECT_EQ(StatusCode::OK_200, res->status);
  2612. }
  2613. {
  2614. cli.set_basic_auth("hello", "bad");
  2615. auto res = cli.Get(path);
  2616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2617. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2618. }
  2619. {
  2620. cli.set_basic_auth("bad", "world");
  2621. auto res = cli.Get(path);
  2622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2623. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2624. }
  2625. }
  2626. #ifdef CPPHTTPLIB_SSL_ENABLED
  2627. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2628. auto host = "httpbingo.org";
  2629. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2630. auto paths = std::vector<std::string>{
  2631. "/digest-auth/auth/hello/world/MD5",
  2632. "/digest-auth/auth/hello/world/SHA-256",
  2633. };
  2634. auto port = 443;
  2635. SSLClient cli(host, port);
  2636. {
  2637. auto res = cli.Get(unauth_path);
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2640. }
  2641. {
  2642. cli.set_digest_auth("hello", "world");
  2643. for (const auto &path : paths) {
  2644. auto res = cli.Get(path.c_str());
  2645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2646. auto body = remove_whitespace(res->body);
  2647. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2648. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2649. EXPECT_EQ(StatusCode::OK_200, res->status);
  2650. }
  2651. cli.set_digest_auth("hello", "bad");
  2652. for (const auto &path : paths) {
  2653. auto res = cli.Get(path.c_str());
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2656. }
  2657. }
  2658. }
  2659. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2660. // comma-separated list of challenges, and each challenge may itself carry a
  2661. // comma-separated auth-param list, so a server can legally offer Basic
  2662. // before Digest, either as two field lines or packed into one. Runs one 401
  2663. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2664. // value() joins them in receipt order) and checks that the retry carries a
  2665. // well-formed Digest Authorization header naming expected_realm.
  2666. static void
  2667. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2668. const std::string &expected_realm) {
  2669. std::atomic<int> hits{0};
  2670. Server svr;
  2671. svr.Get("/x", [&](const Request &req, Response &res) {
  2672. if (++hits == 1) {
  2673. res.status = StatusCode::Unauthorized_401;
  2674. for (const auto &challenge : challenges) {
  2675. res.set_header("WWW-Authenticate", challenge);
  2676. }
  2677. } else {
  2678. auto authorization = req.get_header_value("Authorization");
  2679. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2680. EXPECT_NE(std::string::npos,
  2681. authorization.find("realm=\"" + expected_realm + "\""));
  2682. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2683. res.set_content("ok", "text/plain");
  2684. }
  2685. });
  2686. auto port = svr.bind_to_any_port(HOST);
  2687. std::thread t([&]() { svr.listen_after_bind(); });
  2688. auto se = detail::scope_exit([&] {
  2689. svr.stop();
  2690. t.join();
  2691. });
  2692. svr.wait_until_ready();
  2693. Client cli(HOST, port);
  2694. cli.set_digest_auth("hello", "world");
  2695. auto res = cli.Get("/x");
  2696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2697. EXPECT_EQ(2, hits.load());
  2698. }
  2699. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2700. static const char *kDigestChallenge =
  2701. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2702. "algorithm=MD5";
  2703. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2704. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2705. "testrealm");
  2706. }
  2707. // Same challenge list with the schemes in the opposite order, to make sure
  2708. // the fix above didn't just special-case "Basic first".
  2709. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2710. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2711. "testrealm");
  2712. }
  2713. // A comma inside a quoted auth-param value must not be mistaken for the
  2714. // separator between two challenges (or two auth-params).
  2715. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2716. run_digest_challenge_list_test(
  2717. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2718. "algorithm=MD5"},
  2719. "test,realm");
  2720. }
  2721. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2722. // make_digest_authentication_header() dereferences both unconditionally, so
  2723. // a server sending a challenge missing either one must not be treated as
  2724. // usable -- doing so used to crash the client with std::out_of_range.
  2725. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2726. Server svr;
  2727. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2728. res.status = StatusCode::Unauthorized_401;
  2729. res.set_header("WWW-Authenticate", challenge);
  2730. });
  2731. auto port = svr.bind_to_any_port(HOST);
  2732. std::thread t([&]() { svr.listen_after_bind(); });
  2733. auto se = detail::scope_exit([&] {
  2734. svr.stop();
  2735. t.join();
  2736. });
  2737. svr.wait_until_ready();
  2738. Client cli(HOST, port);
  2739. cli.set_digest_auth("hello", "world");
  2740. auto res = cli.Get("/x");
  2741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2742. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2743. }
  2744. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2745. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2746. }
  2747. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2748. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2749. }
  2750. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2751. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2752. }
  2753. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2754. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2755. // when storing the values, so the header builder has to re-escape them (and
  2756. // keep algorithm a bare token); otherwise the value breaks out of its
  2757. // quoted-string and injects extra auth-params into the client's Authorization.
  2758. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2759. std::atomic<int> hits{0};
  2760. std::string authorization;
  2761. Server svr;
  2762. svr.Get("/x", [&](const Request &req, Response &res) {
  2763. if (++hits == 1) {
  2764. res.status = StatusCode::Unauthorized_401;
  2765. // On the wire the quotes embedded in the values are backslash-escaped.
  2766. res.set_header("WWW-Authenticate",
  2767. "Digest realm=\"testrealm\", "
  2768. "nonce=\"n\\\"; injected=\\\"x\", "
  2769. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2770. } else {
  2771. authorization = req.get_header_value("Authorization");
  2772. res.set_content("ok", "text/plain");
  2773. }
  2774. });
  2775. auto port = svr.bind_to_any_port(HOST);
  2776. std::thread t([&]() { svr.listen_after_bind(); });
  2777. auto se = detail::scope_exit([&] {
  2778. svr.stop();
  2779. t.join();
  2780. });
  2781. svr.wait_until_ready();
  2782. Client cli(HOST, port);
  2783. cli.set_digest_auth("hello", "world");
  2784. auto res = cli.Get("/x");
  2785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2786. EXPECT_EQ(2, hits.load());
  2787. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2788. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2789. // inside its quoted-string rather than starting an "injected" auth-param.
  2790. EXPECT_NE(std::string::npos,
  2791. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2792. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2793. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2794. }
  2795. #endif
  2796. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2797. auto host = "google.com";
  2798. auto another_host = "example.com";
  2799. auto wrong_ip = "0.0.0.0";
  2800. #ifdef CPPHTTPLIB_SSL_ENABLED
  2801. SSLClient cli(host);
  2802. #else
  2803. Client cli(host);
  2804. #endif
  2805. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2806. auto res = cli.Get("/");
  2807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2808. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2809. }
  2810. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2811. auto host = "google.com";
  2812. auto wrong_ip = "0.0.0.0";
  2813. #ifdef CPPHTTPLIB_SSL_ENABLED
  2814. SSLClient cli(host);
  2815. #else
  2816. Client cli(host);
  2817. #endif
  2818. cli.set_hostname_addr_map({{host, wrong_ip}});
  2819. auto res = cli.Get("/");
  2820. ASSERT_TRUE(!res);
  2821. EXPECT_EQ(Error::Connection, res.error());
  2822. }
  2823. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2824. // A mapped value that is not an IP literal must be resolved. "localhost"
  2825. // resolves from the hosts file, so this test needs no external DNS.
  2826. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2827. auto host = "target.invalid";
  2828. Server svr;
  2829. std::string received_host;
  2830. svr.Get("/hi", [&](const Request &req, Response &res) {
  2831. received_host = req.get_header_value("Host");
  2832. res.set_content("Hello World!", "text/plain");
  2833. });
  2834. auto port = svr.bind_to_any_port(HOST);
  2835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2836. auto se = detail::scope_exit([&] {
  2837. svr.stop();
  2838. thread.join();
  2839. ASSERT_FALSE(svr.is_running());
  2840. });
  2841. svr.wait_until_ready();
  2842. Client cli(host, port);
  2843. cli.set_hostname_addr_map({{host, HOST}});
  2844. auto res = cli.Get("/hi");
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(StatusCode::OK_200, res->status);
  2847. // The mapping only redirects the connection; the identity stays host_.
  2848. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2849. }
  2850. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2851. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2852. auto host = "target.invalid";
  2853. Server svr;
  2854. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2855. res.set_content("Hello World!", "text/plain");
  2856. });
  2857. auto port = svr.bind_to_any_port("127.0.0.1");
  2858. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2859. auto se = detail::scope_exit([&] {
  2860. svr.stop();
  2861. thread.join();
  2862. ASSERT_FALSE(svr.is_running());
  2863. });
  2864. svr.wait_until_ready();
  2865. Client cli(host, port);
  2866. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2867. auto res = cli.Get("/hi");
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2872. // An empty mapped value must leave host_ as the connection target. Without
  2873. // that guard the empty value would become the host argument, getaddrinfo
  2874. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2875. // loopback - silently connecting somewhere the caller never asked for.
  2876. // The server listens on loopback, so such a fallback would succeed and is
  2877. // therefore observable as a failure of this test.
  2878. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2879. Server svr;
  2880. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2881. res.set_content("Hello World!", "text/plain");
  2882. });
  2883. auto port = svr.bind_to_any_port(HOST);
  2884. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2885. auto se = detail::scope_exit([&] {
  2886. svr.stop();
  2887. thread.join();
  2888. ASSERT_FALSE(svr.is_running());
  2889. });
  2890. svr.wait_until_ready();
  2891. Client cli(blackhole, port);
  2892. cli.set_hostname_addr_map({{blackhole, ""}});
  2893. cli.set_connection_timeout(1);
  2894. auto res = cli.Get("/hi");
  2895. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2896. }
  2897. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2898. auto host = "httpbingo.org";
  2899. auto path = std::string{"/absolute-redirect/3"};
  2900. #ifdef CPPHTTPLIB_SSL_ENABLED
  2901. SSLClient cli(host);
  2902. #else
  2903. Client cli(host);
  2904. #endif
  2905. cli.set_follow_location(true);
  2906. auto res = cli.Get(path);
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. }
  2910. TEST(RedirectTest, Redirect_Online) {
  2911. auto host = "httpbingo.org";
  2912. auto path = std::string{"/redirect/3"};
  2913. #ifdef CPPHTTPLIB_SSL_ENABLED
  2914. SSLClient cli(host);
  2915. #else
  2916. Client cli(host);
  2917. #endif
  2918. cli.set_follow_location(true);
  2919. auto res = cli.Get(path);
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::OK_200, res->status);
  2922. }
  2923. TEST(RelativeRedirectTest, Redirect_Online) {
  2924. auto host = "httpbingo.org";
  2925. auto path = std::string{"/relative-redirect/3"};
  2926. #ifdef CPPHTTPLIB_SSL_ENABLED
  2927. SSLClient cli(host);
  2928. #else
  2929. Client cli(host);
  2930. #endif
  2931. cli.set_follow_location(true);
  2932. auto res = cli.Get(path);
  2933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2934. EXPECT_EQ(StatusCode::OK_200, res->status);
  2935. }
  2936. TEST(TooManyRedirectTest, Redirect_Online) {
  2937. auto host = "httpbingo.org";
  2938. auto path = std::string{"/redirect/21"};
  2939. #ifdef CPPHTTPLIB_SSL_ENABLED
  2940. SSLClient cli(host);
  2941. #else
  2942. Client cli(host);
  2943. #endif
  2944. cli.set_follow_location(true);
  2945. auto res = cli.Get(path);
  2946. ASSERT_TRUE(!res);
  2947. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2948. }
  2949. #ifdef CPPHTTPLIB_SSL_ENABLED
  2950. TEST(YahooRedirectTest, Redirect_Online) {
  2951. Client cli("yahoo.com");
  2952. auto res = cli.Get("/");
  2953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2954. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2955. cli.set_follow_location(true);
  2956. res = cli.Get("/");
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2960. }
  2961. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2962. #define REDIR_HOST "httpbingo.org"
  2963. #define REDIR_PATH "/redirect-to"
  2964. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2965. SSLClient cli(REDIR_HOST);
  2966. cli.set_follow_location(true);
  2967. auto res =
  2968. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2970. EXPECT_EQ(StatusCode::OK_200, res->status);
  2971. }
  2972. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2973. SSLClient cli(REDIR_HOST);
  2974. cli.set_follow_location(true);
  2975. Params params;
  2976. params.emplace("url", "http://example.com");
  2977. params.emplace("status_code", "302");
  2978. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2980. EXPECT_EQ(StatusCode::OK_200, res->status);
  2981. }
  2982. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2983. SSLClient cli(REDIR_HOST);
  2984. cli.set_follow_location(true);
  2985. Params params;
  2986. params.emplace("url", "http://example.com");
  2987. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2989. EXPECT_EQ(StatusCode::OK_200, res->status);
  2990. }
  2991. TEST(UrlWithSpace, Redirect_Online) {
  2992. SSLClient cli("edge.forgecdn.net");
  2993. cli.set_follow_location(true);
  2994. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2996. EXPECT_EQ(StatusCode::OK_200, res->status);
  2997. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2998. }
  2999. #endif
  3000. #if !defined(_WIN32) && !defined(_WIN64)
  3001. TEST(ReceiveSignals, Signal) {
  3002. auto setupSignalHandlers = []() {
  3003. struct sigaction act;
  3004. sigemptyset(&act.sa_mask);
  3005. act.sa_flags = SA_SIGINFO;
  3006. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3007. switch (sig) {
  3008. case SIGINT:
  3009. default: break;
  3010. }
  3011. };
  3012. ::sigaction(SIGINT, &act, nullptr);
  3013. };
  3014. Server svr;
  3015. int port = 0;
  3016. auto thread = std::thread([&]() {
  3017. setupSignalHandlers();
  3018. port = svr.bind_to_any_port(HOST);
  3019. svr.listen_after_bind();
  3020. });
  3021. auto se = detail::scope_exit([&] {
  3022. svr.stop();
  3023. thread.join();
  3024. ASSERT_FALSE(svr.is_running());
  3025. });
  3026. svr.wait_until_ready();
  3027. ASSERT_TRUE(svr.is_running());
  3028. pthread_kill(thread.native_handle(), SIGINT);
  3029. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3030. ASSERT_TRUE(svr.is_running());
  3031. }
  3032. #endif
  3033. TEST(RedirectToDifferentPort, Redirect) {
  3034. Server svr1;
  3035. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3036. res.set_content("Hello World!", "text/plain");
  3037. });
  3038. int svr1_port = 0;
  3039. auto thread1 = std::thread([&]() {
  3040. svr1_port = svr1.bind_to_any_port(HOST);
  3041. svr1.listen_after_bind();
  3042. });
  3043. Server svr2;
  3044. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3045. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3046. });
  3047. int svr2_port = 0;
  3048. auto thread2 = std::thread([&]() {
  3049. svr2_port = svr2.bind_to_any_port(HOST);
  3050. svr2.listen_after_bind();
  3051. });
  3052. auto se = detail::scope_exit([&] {
  3053. svr2.stop();
  3054. thread2.join();
  3055. svr1.stop();
  3056. thread1.join();
  3057. ASSERT_FALSE(svr2.is_running());
  3058. ASSERT_FALSE(svr1.is_running());
  3059. });
  3060. svr1.wait_until_ready();
  3061. svr2.wait_until_ready();
  3062. Client cli("localhost", svr2_port);
  3063. cli.set_follow_location(true);
  3064. auto res = cli.Get("/2");
  3065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3066. EXPECT_EQ(StatusCode::OK_200, res->status);
  3067. EXPECT_EQ("Hello World!", res->body);
  3068. }
  3069. static void
  3070. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3071. Server svr1;
  3072. std::string captured_authorization;
  3073. svr1.Get("/target", [&](const Request &req, Response &res) {
  3074. captured_authorization = req.get_header_value("Authorization");
  3075. res.set_content("OK", "text/plain");
  3076. });
  3077. int svr1_port = 0;
  3078. auto thread1 = std::thread([&]() {
  3079. svr1_port = svr1.bind_to_any_port(HOST);
  3080. svr1.listen_after_bind();
  3081. });
  3082. Server svr2;
  3083. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3084. res.set_redirect(
  3085. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3086. });
  3087. int svr2_port = 0;
  3088. auto thread2 = std::thread([&]() {
  3089. svr2_port = svr2.bind_to_any_port(HOST);
  3090. svr2.listen_after_bind();
  3091. });
  3092. auto se = detail::scope_exit([&] {
  3093. svr2.stop();
  3094. thread2.join();
  3095. svr1.stop();
  3096. thread1.join();
  3097. ASSERT_FALSE(svr2.is_running());
  3098. ASSERT_FALSE(svr1.is_running());
  3099. });
  3100. svr1.wait_until_ready();
  3101. svr2.wait_until_ready();
  3102. Client cli("localhost", svr2_port);
  3103. cli.set_follow_location(true);
  3104. set_auth(cli);
  3105. auto res = cli.Get("/redir");
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3109. EXPECT_TRUE(captured_authorization.empty());
  3110. }
  3111. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3112. TestDoNotForwardCredentialsOnRedirect(
  3113. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3114. }
  3115. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3116. TestDoNotForwardCredentialsOnRedirect(
  3117. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3118. }
  3119. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3120. Server svr1;
  3121. std::string captured_cookie;
  3122. bool target_hit = false;
  3123. svr1.Get("/target", [&](const Request &req, Response &res) {
  3124. captured_cookie = req.get_header_value("Cookie");
  3125. target_hit = true;
  3126. res.set_content("OK", "text/plain");
  3127. });
  3128. int svr1_port = 0;
  3129. auto thread1 = std::thread([&]() {
  3130. svr1_port = svr1.bind_to_any_port(HOST);
  3131. svr1.listen_after_bind();
  3132. });
  3133. Server svr2;
  3134. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3135. res.set_redirect(
  3136. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3137. });
  3138. int svr2_port = 0;
  3139. auto thread2 = std::thread([&]() {
  3140. svr2_port = svr2.bind_to_any_port(HOST);
  3141. svr2.listen_after_bind();
  3142. });
  3143. auto se = detail::scope_exit([&] {
  3144. svr2.stop();
  3145. thread2.join();
  3146. svr1.stop();
  3147. thread1.join();
  3148. ASSERT_FALSE(svr2.is_running());
  3149. ASSERT_FALSE(svr1.is_running());
  3150. });
  3151. svr1.wait_until_ready();
  3152. svr2.wait_until_ready();
  3153. Client cli("localhost", svr2_port);
  3154. cli.set_follow_location(true);
  3155. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3156. auto res = cli.Get("/redir", headers);
  3157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3158. EXPECT_EQ(StatusCode::OK_200, res->status);
  3159. EXPECT_TRUE(target_hit);
  3160. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3161. EXPECT_TRUE(captured_cookie.empty());
  3162. }
  3163. TEST(RedirectToSamePort, ForwardCookie) {
  3164. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3165. // header so that ordinary session flows keep working.
  3166. Server svr;
  3167. std::string captured_cookie;
  3168. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3169. res.set_redirect("/target", 302);
  3170. });
  3171. svr.Get("/target", [&](const Request &req, Response &res) {
  3172. captured_cookie = req.get_header_value("Cookie");
  3173. res.set_content("OK", "text/plain");
  3174. });
  3175. auto port = svr.bind_to_any_port(HOST);
  3176. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3177. auto se = detail::scope_exit([&] {
  3178. svr.stop();
  3179. thread.join();
  3180. ASSERT_FALSE(svr.is_running());
  3181. });
  3182. svr.wait_until_ready();
  3183. Client cli(HOST, port);
  3184. cli.set_follow_location(true);
  3185. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3186. auto res = cli.Get("/redir", headers);
  3187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3188. EXPECT_EQ(StatusCode::OK_200, res->status);
  3189. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3190. }
  3191. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3192. Server svr;
  3193. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3194. // Port number that overflows int — should not crash
  3195. res.set_redirect("http://localhost:99999999999999999999/target");
  3196. });
  3197. auto port = svr.bind_to_any_port(HOST);
  3198. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3199. auto se = detail::scope_exit([&] {
  3200. svr.stop();
  3201. thread.join();
  3202. ASSERT_FALSE(svr.is_running());
  3203. });
  3204. svr.wait_until_ready();
  3205. Client cli(HOST, port);
  3206. cli.set_follow_location(true);
  3207. auto res = cli.Get("/redir");
  3208. // Should fail gracefully, not crash (no valid response due to bad port)
  3209. EXPECT_FALSE(res);
  3210. }
  3211. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3212. Server svr;
  3213. auto port = svr.bind_to_any_port(HOST);
  3214. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3215. // The server's own port followed by junk must not be followed
  3216. res.set_redirect("http://" + std::string(HOST) + ":" +
  3217. std::to_string(port) + "junk/target");
  3218. });
  3219. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3220. res.set_content("target", "text/plain");
  3221. });
  3222. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3223. auto se = detail::scope_exit([&] {
  3224. svr.stop();
  3225. thread.join();
  3226. ASSERT_FALSE(svr.is_running());
  3227. });
  3228. svr.wait_until_ready();
  3229. Client cli(HOST, port);
  3230. cli.set_follow_location(true);
  3231. auto res = cli.Get("/redir");
  3232. EXPECT_FALSE(res);
  3233. }
  3234. TEST(RedirectFromPageWithContent, Redirect) {
  3235. Server svr;
  3236. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3237. res.set_content("___", "text/plain");
  3238. res.set_redirect("/2");
  3239. });
  3240. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3241. res.set_content("Hello World!", "text/plain");
  3242. });
  3243. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3244. auto se = detail::scope_exit([&] {
  3245. svr.stop();
  3246. th.join();
  3247. ASSERT_FALSE(svr.is_running());
  3248. });
  3249. svr.wait_until_ready();
  3250. {
  3251. Client cli("localhost", PORT);
  3252. cli.set_follow_location(true);
  3253. std::string body;
  3254. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3255. body.append(data, data_length);
  3256. return true;
  3257. });
  3258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3259. EXPECT_EQ(StatusCode::OK_200, res->status);
  3260. EXPECT_EQ("Hello World!", body);
  3261. }
  3262. {
  3263. Client cli("localhost", PORT);
  3264. std::string body;
  3265. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3266. body.append(data, data_length);
  3267. return true;
  3268. });
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::Found_302, res->status);
  3271. EXPECT_EQ("___", body);
  3272. }
  3273. }
  3274. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3275. Server svr;
  3276. auto port_str = std::to_string(PORT);
  3277. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3278. auto expected_host = "[::1]:" + port_str;
  3279. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3280. res.set_content("___", "text/plain");
  3281. // res.set_redirect("/2");
  3282. res.set_redirect(redirect_url);
  3283. });
  3284. svr.Get("/2", [&](const Request &req, Response &res) {
  3285. auto host_header = req.headers.find("Host");
  3286. ASSERT_TRUE(host_header != req.headers.end());
  3287. EXPECT_EQ(expected_host, host_header->second);
  3288. res.set_content("Hello World!", "text/plain");
  3289. });
  3290. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3291. auto se = detail::scope_exit([&] {
  3292. svr.stop();
  3293. th.join();
  3294. ASSERT_FALSE(svr.is_running());
  3295. });
  3296. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3297. // actually starts anything, so the condition !svr.is_running() will
  3298. // always remain true, and the loop never stops.
  3299. // This basically counts how many milliseconds have passed since the
  3300. // call to svr.listen(), and if after 5 seconds nothing started yet
  3301. // aborts the test.
  3302. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3303. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3304. ASSERT_LT(milliseconds, 5000U);
  3305. }
  3306. {
  3307. Client cli("::1", PORT);
  3308. cli.set_follow_location(true);
  3309. std::string body;
  3310. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3311. body.append(data, data_length);
  3312. return true;
  3313. });
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. EXPECT_EQ("Hello World!", body);
  3317. }
  3318. {
  3319. Client cli("::1", PORT);
  3320. std::string body;
  3321. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3322. body.append(data, data_length);
  3323. return true;
  3324. });
  3325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3326. EXPECT_EQ(StatusCode::Found_302, res->status);
  3327. EXPECT_EQ("___", body);
  3328. }
  3329. }
  3330. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3331. Server svr;
  3332. svr.Get("/foo", [](const Request &req, Response &res) {
  3333. auto a = req.params.find("a");
  3334. if (a != req.params.end()) {
  3335. res.set_content((*a).second, "text/plain");
  3336. res.status = StatusCode::OK_200;
  3337. } else {
  3338. res.status = StatusCode::BadRequest_400;
  3339. }
  3340. });
  3341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3342. auto se = detail::scope_exit([&] {
  3343. svr.stop();
  3344. thread.join();
  3345. ASSERT_FALSE(svr.is_running());
  3346. });
  3347. svr.wait_until_ready();
  3348. {
  3349. Client cli(HOST, PORT);
  3350. cli.set_path_encode(false);
  3351. auto res = cli.Get("/foo?a=explicitly+encoded");
  3352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3353. EXPECT_EQ(StatusCode::OK_200, res->status);
  3354. // This expects it back with a space, as the `+` won't have been
  3355. // url-encoded, and server-side the params get decoded turning `+`
  3356. // into spaces.
  3357. EXPECT_EQ("explicitly encoded", res->body);
  3358. }
  3359. }
  3360. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3361. // When path encoding is disabled the client must transmit the supplied
  3362. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3363. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3364. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3365. // than a space (0x20). Assert on the raw wire target to catch this.
  3366. Server svr;
  3367. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3368. svr.Get("/foo", [&](const Request &req, Response &res) {
  3369. EXPECT_EQ(expected_target, req.target);
  3370. res.status = StatusCode::OK_200;
  3371. });
  3372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3373. auto se = detail::scope_exit([&] {
  3374. svr.stop();
  3375. thread.join();
  3376. ASSERT_FALSE(svr.is_running());
  3377. });
  3378. svr.wait_until_ready();
  3379. {
  3380. Client cli(HOST, PORT);
  3381. cli.set_path_encode(false);
  3382. auto res = cli.Get(expected_target.c_str());
  3383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3384. EXPECT_EQ(StatusCode::OK_200, res->status);
  3385. }
  3386. }
  3387. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3388. // `open_stream()` used to skip the path encoding that the buffered send
  3389. // path applies, so the same `path` produced different bytes in the request
  3390. // line depending on which API was used. Assert the two agree.
  3391. Server svr;
  3392. std::string target;
  3393. svr.Get(".*", [&](const Request &req, Response &res) {
  3394. target = req.target;
  3395. res.status = StatusCode::OK_200;
  3396. });
  3397. auto port = svr.bind_to_any_port(HOST);
  3398. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3399. auto se = detail::scope_exit([&] {
  3400. svr.stop();
  3401. thread.join();
  3402. ASSERT_FALSE(svr.is_running());
  3403. });
  3404. svr.wait_until_ready();
  3405. struct {
  3406. const char *path;
  3407. const char *expected;
  3408. } cases[] = {
  3409. {"/a b?x=1", "/a%20b?x=1"},
  3410. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3411. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3412. };
  3413. for (const auto &c : cases) {
  3414. Client cli(HOST, port);
  3415. target.clear();
  3416. auto res = cli.Get(c.path);
  3417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3418. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3419. auto buffered_target = target;
  3420. target.clear();
  3421. auto handle = cli.open_stream("GET", c.path);
  3422. EXPECT_TRUE(handle.is_valid())
  3423. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3424. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3425. }
  3426. }
  3427. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3428. // The `set_path_encode(false)` contract — transmit the supplied target
  3429. // verbatim — must hold for the streaming API too.
  3430. Server svr;
  3431. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3432. std::string target;
  3433. svr.Get("/foo", [&](const Request &req, Response &res) {
  3434. target = req.target;
  3435. res.status = StatusCode::OK_200;
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. {
  3446. Client cli(HOST, port);
  3447. cli.set_path_encode(false);
  3448. auto handle = cli.open_stream("GET", expected_target);
  3449. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3450. EXPECT_EQ(expected_target, target);
  3451. }
  3452. }
  3453. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3454. // With path encoding enabled a CR/LF in the target is percent-encoded
  3455. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3456. // write_request_line still backstops `set_path_encode(false)`, which is
  3457. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3458. Server svr;
  3459. // Captured before routing: the decoded path contains a newline, which a
  3460. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3461. std::string target;
  3462. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3463. target = req.target;
  3464. res.status = StatusCode::OK_200;
  3465. return Server::HandlerResponse::Handled;
  3466. });
  3467. auto port = svr.bind_to_any_port(HOST);
  3468. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3469. auto se = detail::scope_exit([&] {
  3470. svr.stop();
  3471. thread.join();
  3472. ASSERT_FALSE(svr.is_running());
  3473. });
  3474. svr.wait_until_ready();
  3475. {
  3476. Client cli(HOST, port);
  3477. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3478. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3479. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3480. }
  3481. }
  3482. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3483. // Every control character is percent-encoded, not just CR/LF, so the target
  3484. // passes the request-target check in write_request_line.
  3485. Server svr;
  3486. std::string target;
  3487. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3488. target = req.target;
  3489. res.status = StatusCode::OK_200;
  3490. return Server::HandlerResponse::Handled;
  3491. });
  3492. auto port = svr.bind_to_any_port(HOST);
  3493. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3494. auto se = detail::scope_exit([&] {
  3495. svr.stop();
  3496. thread.join();
  3497. ASSERT_FALSE(svr.is_running());
  3498. });
  3499. svr.wait_until_ready();
  3500. {
  3501. Client cli(HOST, port);
  3502. auto res = cli.Get("/a\tb\x1b\x7f");
  3503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3504. EXPECT_EQ("/a%09b%1B%7F", target);
  3505. }
  3506. }
  3507. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3508. // Nothing may reach the wire: a raw CR/LF target would split the request
  3509. // line and inject headers.
  3510. Server svr;
  3511. // Pre-routing so that "not called" means nothing reached the server at all,
  3512. // rather than merely failing to match a handler pattern.
  3513. auto handler_called = false;
  3514. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3515. handler_called = true;
  3516. res.status = StatusCode::OK_200;
  3517. return Server::HandlerResponse::Handled;
  3518. });
  3519. auto port = svr.bind_to_any_port(HOST);
  3520. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3521. auto se = detail::scope_exit([&] {
  3522. svr.stop();
  3523. thread.join();
  3524. ASSERT_FALSE(svr.is_running());
  3525. });
  3526. svr.wait_until_ready();
  3527. {
  3528. Client cli(HOST, port);
  3529. cli.set_path_encode(false);
  3530. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3531. EXPECT_FALSE(handle.is_valid());
  3532. EXPECT_EQ(Error::Write, handle.error);
  3533. EXPECT_FALSE(handler_called);
  3534. }
  3535. }
  3536. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3537. // Which of the two branches runs is decided by whether the query component
  3538. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3539. // an empty query and must still fall back to building one from
  3540. // `req.params`, while a non-empty query must win over `req.params`.
  3541. Server svr;
  3542. std::string target;
  3543. svr.Get("/foo", [&](const Request &req, Response &res) {
  3544. target = req.target;
  3545. res.status = StatusCode::OK_200;
  3546. });
  3547. auto port = svr.bind_to_any_port(HOST);
  3548. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3549. auto se = detail::scope_exit([&] {
  3550. svr.stop();
  3551. thread.join();
  3552. ASSERT_FALSE(svr.is_running());
  3553. });
  3554. svr.wait_until_ready();
  3555. {
  3556. // Trailing `?` -> empty query component -> `req.params` is used.
  3557. Client cli(HOST, port);
  3558. Request req;
  3559. req.method = "GET";
  3560. req.path = "/foo?";
  3561. req.params.emplace("a", "1");
  3562. target.clear();
  3563. auto res = cli.send(req);
  3564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3565. EXPECT_EQ("/foo?a=1", target);
  3566. }
  3567. {
  3568. // Non-empty query in `req.path` -> `req.params` is not appended.
  3569. Client cli(HOST, port);
  3570. Request req;
  3571. req.method = "GET";
  3572. req.path = "/foo?b=2";
  3573. req.params.emplace("a", "1");
  3574. target.clear();
  3575. auto res = cli.send(req);
  3576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3577. EXPECT_EQ("/foo?b=2", target);
  3578. }
  3579. }
  3580. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3581. Server svr;
  3582. svr.Get("/", [](const Request &req, Response &) {
  3583. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3584. });
  3585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3586. auto se = detail::scope_exit([&] {
  3587. svr.stop();
  3588. thread.join();
  3589. ASSERT_FALSE(svr.is_running());
  3590. });
  3591. svr.wait_until_ready();
  3592. {
  3593. Client cli(HOST, PORT);
  3594. cli.set_path_encode(false);
  3595. auto res = cli.Get("/?something=%0A");
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ(StatusCode::OK_200, res->status);
  3598. }
  3599. }
  3600. TEST(BindServerTest, BindDualStack) {
  3601. Server svr;
  3602. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3603. res.set_content("Hello World!", "text/plain");
  3604. });
  3605. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. thread.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. svr.wait_until_ready();
  3612. {
  3613. Client cli("127.0.0.1", PORT);
  3614. auto res = cli.Get("/1");
  3615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3616. EXPECT_EQ(StatusCode::OK_200, res->status);
  3617. EXPECT_EQ("Hello World!", res->body);
  3618. }
  3619. {
  3620. Client cli("::1", PORT);
  3621. auto res = cli.Get("/1");
  3622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3623. EXPECT_EQ(StatusCode::OK_200, res->status);
  3624. EXPECT_EQ("Hello World!", res->body);
  3625. }
  3626. }
  3627. TEST(BindServerTest, BindAndListenSeparately) {
  3628. Server svr;
  3629. int port = svr.bind_to_any_port("0.0.0.0");
  3630. ASSERT_TRUE(svr.is_valid());
  3631. ASSERT_TRUE(port > 0);
  3632. svr.stop();
  3633. }
  3634. // Reports whether anything is still listening on a loopback port. A plain
  3635. // connect() is used instead of a Client request because a socket left bound by
  3636. // mistake accepts the connection into its backlog and never answers, which
  3637. // would hang the test instead of failing it.
  3638. static bool is_loopback_port_accepting(int port) {
  3639. sockaddr_in addr{};
  3640. addr.sin_family = AF_INET;
  3641. addr.sin_port = htons(static_cast<uint16_t>(port));
  3642. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3643. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3644. EXPECT_NE(sock, INVALID_SOCKET);
  3645. if (sock == INVALID_SOCKET) { return false; }
  3646. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3647. static_cast<socklen_t>(sizeof(addr)));
  3648. detail::close_socket(sock);
  3649. return ret == 0;
  3650. }
  3651. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3652. Server svr;
  3653. auto port = svr.bind_to_any_port("127.0.0.1");
  3654. ASSERT_TRUE(port > 0);
  3655. svr.stop();
  3656. // bind_to_any_port() already called listen(2), so until stop() closed the
  3657. // descriptor the port kept accepting connections into the backlog. ASSERT
  3658. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3659. // below blocks forever in the accept loop.
  3660. ASSERT_FALSE(is_loopback_port_accepting(port));
  3661. // Nothing is left to accept on, so listen_after_bind() must report failure
  3662. // instead of returning success without ever serving.
  3663. EXPECT_FALSE(svr.listen_after_bind());
  3664. // The failed listen marks the server decommissioned, so a waiter returns
  3665. // instead of spinning forever.
  3666. svr.wait_until_ready();
  3667. }
  3668. #ifdef CPPHTTPLIB_SSL_ENABLED
  3669. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3671. CLIENT_CA_CERT_DIR);
  3672. int port = svr.bind_to_any_port("0.0.0.0");
  3673. ASSERT_TRUE(svr.is_valid());
  3674. ASSERT_TRUE(port > 0);
  3675. svr.stop();
  3676. }
  3677. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3678. // or a rejected CustomRoute() registration would not stop the server binding.
  3679. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3681. CLIENT_CA_CERT_DIR);
  3682. ASSERT_TRUE(svr.is_valid());
  3683. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3684. EXPECT_FALSE(svr.is_valid());
  3685. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3686. }
  3687. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3688. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3689. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3690. int port = svr.bind_to_any_port("0.0.0.0");
  3691. ASSERT_TRUE(svr.is_valid());
  3692. ASSERT_TRUE(port > 0);
  3693. svr.stop();
  3694. }
  3695. TEST(BindServerTest, UpdateCertsPem) {
  3696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3697. int port = svr.bind_to_any_port("0.0.0.0");
  3698. ASSERT_TRUE(svr.is_valid());
  3699. ASSERT_TRUE(port > 0);
  3700. // Read PEM files
  3701. std::string cert_pem, key_pem, ca_pem;
  3702. read_file(SERVER_CERT_FILE, cert_pem);
  3703. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3704. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3705. // Update server certificates using PEM API
  3706. ASSERT_TRUE(
  3707. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3708. ASSERT_TRUE(svr.is_valid());
  3709. svr.stop();
  3710. }
  3711. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3712. // Start server with client CA (enables client auth)
  3713. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3714. ASSERT_TRUE(svr.is_valid());
  3715. bool handler_called = false;
  3716. svr.Get("/test", [&](const Request &req, Response &res) {
  3717. handler_called = true;
  3718. // Verify client certificate is present
  3719. auto cert = req.peer_cert();
  3720. EXPECT_TRUE(static_cast<bool>(cert));
  3721. res.set_content("ok", "text/plain");
  3722. });
  3723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3724. auto se = detail::scope_exit([&] {
  3725. svr.stop();
  3726. t.join();
  3727. ASSERT_FALSE(svr.is_running());
  3728. });
  3729. svr.wait_until_ready();
  3730. // Read PEM files
  3731. std::string cert_pem, key_pem, ca_pem;
  3732. read_file(SERVER_CERT_FILE, cert_pem);
  3733. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3734. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3735. // Update server certificates and client CA using PEM API while server running
  3736. ASSERT_TRUE(
  3737. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3738. // Connect with client certificate
  3739. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3740. cli.enable_server_certificate_verification(false);
  3741. cli.set_connection_timeout(30);
  3742. auto res = cli.Get("/test");
  3743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3744. ASSERT_EQ(StatusCode::OK_200, res->status);
  3745. ASSERT_TRUE(handler_called);
  3746. EXPECT_EQ("ok", res->body);
  3747. }
  3748. #endif
  3749. TEST(ErrorHandlerTest, ContentLength) {
  3750. Server svr;
  3751. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3752. res.status = StatusCode::OK_200;
  3753. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3754. "text/html"); // <= Content-Length still 13
  3755. });
  3756. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3757. res.set_content("Hello World!\n", "text/plain");
  3758. res.status = 524;
  3759. });
  3760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3761. auto se = detail::scope_exit([&] {
  3762. svr.stop();
  3763. thread.join();
  3764. ASSERT_FALSE(svr.is_running());
  3765. });
  3766. svr.wait_until_ready();
  3767. {
  3768. Client cli(HOST, PORT);
  3769. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3771. EXPECT_EQ(StatusCode::OK_200, res->status);
  3772. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3773. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3774. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3775. }
  3776. }
  3777. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3778. TEST(ExceptionTest, WithoutExceptionHandler) {
  3779. Server svr;
  3780. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3781. throw std::runtime_error("exception...");
  3782. });
  3783. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3784. throw std::runtime_error("exception\r\n...");
  3785. });
  3786. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. listen_thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. Client cli("localhost", PORT);
  3794. {
  3795. auto res = cli.Get("/exception");
  3796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3797. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3798. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3799. }
  3800. {
  3801. auto res = cli.Get("/unknown");
  3802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3803. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3804. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3805. }
  3806. }
  3807. TEST(ExceptionTest, WithExceptionHandler) {
  3808. Server svr;
  3809. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3810. std::exception_ptr ep) {
  3811. EXPECT_FALSE(ep == nullptr);
  3812. try {
  3813. std::rethrow_exception(ep);
  3814. } catch (std::exception &e) {
  3815. EXPECT_EQ("abc", std::string(e.what()));
  3816. } catch (...) {}
  3817. res.status = StatusCode::InternalServerError_500;
  3818. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3819. "text/html"); // <= Content-Length still 13 at this point
  3820. });
  3821. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3822. res.set_content("Hello World!\n", "text/plain");
  3823. throw std::runtime_error("abc");
  3824. });
  3825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3826. auto se = detail::scope_exit([&] {
  3827. svr.stop();
  3828. thread.join();
  3829. ASSERT_FALSE(svr.is_running());
  3830. });
  3831. svr.wait_until_ready();
  3832. for (size_t i = 0; i < 10; i++) {
  3833. Client cli(HOST, PORT);
  3834. for (size_t j = 0; j < 100; j++) {
  3835. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3837. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3838. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3839. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3840. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3841. }
  3842. cli.set_keep_alive(true);
  3843. for (size_t j = 0; j < 100; j++) {
  3844. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3846. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3849. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3850. }
  3851. }
  3852. }
  3853. TEST(ExceptionTest, AndErrorHandler) {
  3854. Server svr;
  3855. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3856. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3857. });
  3858. svr.set_exception_handler(
  3859. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3860. EXPECT_FALSE(ep == nullptr);
  3861. try {
  3862. std::rethrow_exception(ep);
  3863. } catch (std::exception &e) {
  3864. res.set_content(e.what(), "text/html");
  3865. } catch (...) {}
  3866. res.status = StatusCode::InternalServerError_500;
  3867. });
  3868. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3869. throw std::runtime_error("EXCEPTION");
  3870. });
  3871. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3872. res.set_content("ERROR", "text/html");
  3873. res.status = StatusCode::InternalServerError_500;
  3874. });
  3875. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3876. auto se = detail::scope_exit([&] {
  3877. svr.stop();
  3878. thread.join();
  3879. ASSERT_FALSE(svr.is_running());
  3880. });
  3881. svr.wait_until_ready();
  3882. Client cli(HOST, PORT);
  3883. {
  3884. auto res = cli.Get("/exception");
  3885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3886. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3887. EXPECT_EQ("EXCEPTION", res->body);
  3888. }
  3889. {
  3890. auto res = cli.Get("/error");
  3891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3892. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3893. EXPECT_EQ("ERROR", res->body);
  3894. }
  3895. {
  3896. auto res = cli.Get("/invalid");
  3897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3898. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3899. EXPECT_EQ("NOT_FOUND", res->body);
  3900. }
  3901. }
  3902. #endif
  3903. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3904. // process_request() wraps only routing() in a try/catch, so an exception from
  3905. // any other user callback used to unwind into the task queue - which does not
  3906. // catch - and terminate the process. Each test below runs the server on a
  3907. // single worker thread: a guard that catches the exception but still loses the
  3908. // thread would otherwise be hidden by a spare worker serving the follow-up
  3909. // request. Note that a regression here aborts the whole test binary rather
  3910. // than failing one test.
  3911. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3912. Server svr;
  3913. svr.new_task_queue = [] { return new ThreadPool(1); };
  3914. std::atomic<int> reported{0};
  3915. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3916. if (err == Error::UserCallbackException) { reported++; }
  3917. });
  3918. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3919. res.set_content_provider(
  3920. 1024, "text/plain",
  3921. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3922. sink.write("hello", 5);
  3923. throw std::runtime_error("from the content provider");
  3924. });
  3925. });
  3926. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3927. res.set_content("ok", "text/plain");
  3928. });
  3929. auto port = svr.bind_to_any_port(HOST);
  3930. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3931. auto se = detail::scope_exit([&] {
  3932. svr.stop();
  3933. listen_thread.join();
  3934. ASSERT_FALSE(svr.is_running());
  3935. });
  3936. svr.wait_until_ready();
  3937. {
  3938. Client cli(HOST, port);
  3939. cli.set_read_timeout(5, 0);
  3940. EXPECT_FALSE(cli.Get("/throw"));
  3941. }
  3942. EXPECT_TRUE(svr.is_running());
  3943. EXPECT_EQ(1, reported.load());
  3944. // A request on a fresh connection is still served.
  3945. {
  3946. Client cli(HOST, port);
  3947. auto res = cli.Get("/ok");
  3948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3949. EXPECT_EQ(StatusCode::OK_200, res->status);
  3950. EXPECT_EQ("ok", res->body);
  3951. }
  3952. }
  3953. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3954. Server svr;
  3955. svr.new_task_queue = [] { return new ThreadPool(1); };
  3956. std::atomic<bool> should_throw{true};
  3957. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3958. res.set_content("hi", "text/plain");
  3959. });
  3960. svr.set_post_routing_handler(
  3961. [&](const Request & /*req*/, Response & /*res*/) {
  3962. if (should_throw) {
  3963. throw std::runtime_error("from the post-routing handler");
  3964. }
  3965. });
  3966. auto port = svr.bind_to_any_port(HOST);
  3967. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3968. auto se = detail::scope_exit([&] {
  3969. svr.stop();
  3970. listen_thread.join();
  3971. ASSERT_FALSE(svr.is_running());
  3972. });
  3973. svr.wait_until_ready();
  3974. {
  3975. Client cli(HOST, port);
  3976. cli.set_read_timeout(5, 0);
  3977. EXPECT_FALSE(cli.Get("/hi"));
  3978. }
  3979. EXPECT_TRUE(svr.is_running());
  3980. should_throw = false;
  3981. {
  3982. Client cli(HOST, port);
  3983. auto res = cli.Get("/hi");
  3984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3985. EXPECT_EQ(StatusCode::OK_200, res->status);
  3986. EXPECT_EQ("hi", res->body);
  3987. }
  3988. }
  3989. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3990. // The guard reports the caught exception through the error logger, which is
  3991. // a user callback too. A logger that throws has to be contained as well, or
  3992. // the process would terminate from inside the catch.
  3993. Server svr;
  3994. svr.new_task_queue = [] { return new ThreadPool(1); };
  3995. std::atomic<int> reported{0};
  3996. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3997. if (err == Error::UserCallbackException) {
  3998. reported++;
  3999. throw std::runtime_error("from the error logger");
  4000. }
  4001. });
  4002. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4003. res.set_content_provider(
  4004. 1024, "text/plain",
  4005. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4006. sink.write("hello", 5);
  4007. throw std::runtime_error("from the content provider");
  4008. });
  4009. });
  4010. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4011. res.set_content("ok", "text/plain");
  4012. });
  4013. auto port = svr.bind_to_any_port(HOST);
  4014. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4015. auto se = detail::scope_exit([&] {
  4016. svr.stop();
  4017. listen_thread.join();
  4018. ASSERT_FALSE(svr.is_running());
  4019. });
  4020. svr.wait_until_ready();
  4021. {
  4022. Client cli(HOST, port);
  4023. cli.set_read_timeout(5, 0);
  4024. EXPECT_FALSE(cli.Get("/throw"));
  4025. }
  4026. EXPECT_TRUE(svr.is_running());
  4027. EXPECT_EQ(1, reported.load());
  4028. {
  4029. Client cli(HOST, port);
  4030. auto res = cli.Get("/ok");
  4031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4032. EXPECT_EQ(StatusCode::OK_200, res->status);
  4033. EXPECT_EQ("ok", res->body);
  4034. }
  4035. }
  4036. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4037. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4038. // so the exception unwinds through the ws::WebSocket object on its way to
  4039. // the guard. None of the HTTP cases above cross that.
  4040. Server svr;
  4041. svr.new_task_queue = [] { return new ThreadPool(1); };
  4042. std::atomic<int> reported{0};
  4043. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4044. if (err == Error::UserCallbackException) { reported++; }
  4045. });
  4046. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4047. throw std::runtime_error("from the WebSocket handler");
  4048. });
  4049. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4050. res.set_content("ok", "text/plain");
  4051. });
  4052. auto port = svr.bind_to_any_port(HOST);
  4053. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4054. auto se = detail::scope_exit([&] {
  4055. svr.stop();
  4056. listen_thread.join();
  4057. ASSERT_FALSE(svr.is_running());
  4058. });
  4059. svr.wait_until_ready();
  4060. {
  4061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4062. "/ws");
  4063. auto res = client.connect();
  4064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4065. // The server dropped the connection instead of dying.
  4066. std::string msg;
  4067. EXPECT_FALSE(client.read(msg));
  4068. client.close();
  4069. }
  4070. EXPECT_TRUE(svr.is_running());
  4071. EXPECT_EQ(1, reported.load());
  4072. {
  4073. Client cli(HOST, port);
  4074. auto res = cli.Get("/ok");
  4075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4076. EXPECT_EQ(StatusCode::OK_200, res->status);
  4077. EXPECT_EQ("ok", res->body);
  4078. }
  4079. }
  4080. #ifdef CPPHTTPLIB_SSL_ENABLED
  4081. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4082. // SSLServer::process_and_close_socket() is a separate overload with its own
  4083. // guard, so it is exercised on its own.
  4084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4085. ASSERT_TRUE(svr.is_valid());
  4086. svr.new_task_queue = [] { return new ThreadPool(1); };
  4087. std::atomic<int> reported{0};
  4088. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4089. if (err == Error::UserCallbackException) { reported++; }
  4090. });
  4091. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4092. res.set_content_provider(
  4093. 1024, "text/plain",
  4094. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4095. sink.write("hello", 5);
  4096. throw std::runtime_error("from the content provider");
  4097. });
  4098. });
  4099. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4100. res.set_content("ok", "text/plain");
  4101. });
  4102. auto port = svr.bind_to_any_port(HOST);
  4103. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4104. auto se = detail::scope_exit([&] {
  4105. svr.stop();
  4106. listen_thread.join();
  4107. ASSERT_FALSE(svr.is_running());
  4108. });
  4109. svr.wait_until_ready();
  4110. {
  4111. SSLClient cli(HOST, port);
  4112. cli.enable_server_certificate_verification(false);
  4113. cli.set_read_timeout(5, 0);
  4114. EXPECT_FALSE(cli.Get("/throw"));
  4115. }
  4116. EXPECT_TRUE(svr.is_running());
  4117. EXPECT_EQ(1, reported.load());
  4118. {
  4119. SSLClient cli(HOST, port);
  4120. cli.enable_server_certificate_verification(false);
  4121. auto res = cli.Get("/ok");
  4122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4123. EXPECT_EQ(StatusCode::OK_200, res->status);
  4124. EXPECT_EQ("ok", res->body);
  4125. }
  4126. }
  4127. #endif
  4128. #endif
  4129. TEST(NoContentTest, ContentLength) {
  4130. Server svr;
  4131. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4132. res.status = StatusCode::NoContent_204;
  4133. });
  4134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4135. auto se = detail::scope_exit([&] {
  4136. svr.stop();
  4137. thread.join();
  4138. ASSERT_FALSE(svr.is_running());
  4139. });
  4140. svr.wait_until_ready();
  4141. {
  4142. Client cli(HOST, PORT);
  4143. auto res = cli.Get("/hi");
  4144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4145. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4146. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4147. }
  4148. }
  4149. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4150. #ifdef CPPHTTPLIB_SSL_ENABLED
  4151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4152. ASSERT_TRUE(svr.is_valid());
  4153. #else
  4154. Server svr;
  4155. #endif
  4156. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4157. if (req.path == "/routing_handler") {
  4158. res.set_header("PRE_ROUTING", "on");
  4159. res.set_content("Routing Handler", "text/plain");
  4160. return httplib::Server::HandlerResponse::Handled;
  4161. }
  4162. return httplib::Server::HandlerResponse::Unhandled;
  4163. });
  4164. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4165. res.set_content("Error", "text/html");
  4166. });
  4167. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4168. if (req.path == "/routing_handler") {
  4169. res.set_header("POST_ROUTING", "on");
  4170. }
  4171. });
  4172. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4173. res.set_content("Hello World!\n", "text/plain");
  4174. });
  4175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4176. auto se = detail::scope_exit([&] {
  4177. svr.stop();
  4178. thread.join();
  4179. ASSERT_FALSE(svr.is_running());
  4180. });
  4181. svr.wait_until_ready();
  4182. {
  4183. #ifdef CPPHTTPLIB_SSL_ENABLED
  4184. SSLClient cli(HOST, PORT);
  4185. cli.enable_server_certificate_verification(false);
  4186. #else
  4187. Client cli(HOST, PORT);
  4188. #endif
  4189. auto res = cli.Get("/routing_handler");
  4190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. EXPECT_EQ("Routing Handler", res->body);
  4193. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4194. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4195. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4196. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4197. }
  4198. {
  4199. #ifdef CPPHTTPLIB_SSL_ENABLED
  4200. SSLClient cli(HOST, PORT);
  4201. cli.enable_server_certificate_verification(false);
  4202. #else
  4203. Client cli(HOST, PORT);
  4204. #endif
  4205. auto res = cli.Get("/hi");
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ(StatusCode::OK_200, res->status);
  4208. EXPECT_EQ("Hello World!\n", res->body);
  4209. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4210. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4211. }
  4212. {
  4213. #ifdef CPPHTTPLIB_SSL_ENABLED
  4214. SSLClient cli(HOST, PORT);
  4215. cli.enable_server_certificate_verification(false);
  4216. #else
  4217. Client cli(HOST, PORT);
  4218. #endif
  4219. auto res = cli.Get("/aaa");
  4220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4222. EXPECT_EQ("Error", res->body);
  4223. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4224. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4225. }
  4226. }
  4227. TEST(RequestHandlerTest, PreRequestHandler) {
  4228. auto route_path = "/user/:user";
  4229. Server svr;
  4230. svr.Get("/hi", [](const Request &, Response &res) {
  4231. res.set_content("hi", "text/plain");
  4232. });
  4233. svr.Get(route_path, [](const Request &req, Response &res) {
  4234. res.set_content(req.path_params.at("user"), "text/plain");
  4235. });
  4236. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4237. if (req.matched_route == route_path) {
  4238. auto user = req.path_params.at("user");
  4239. if (user != "john") {
  4240. res.status = StatusCode::Forbidden_403;
  4241. res.set_content("error", "text/html");
  4242. return Server::HandlerResponse::Handled;
  4243. }
  4244. }
  4245. return Server::HandlerResponse::Unhandled;
  4246. });
  4247. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4248. auto se = detail::scope_exit([&] {
  4249. svr.stop();
  4250. thread.join();
  4251. ASSERT_FALSE(svr.is_running());
  4252. });
  4253. svr.wait_until_ready();
  4254. Client cli(HOST, PORT);
  4255. {
  4256. auto res = cli.Get("/hi");
  4257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("hi", res->body);
  4260. }
  4261. {
  4262. auto res = cli.Get("/user/john");
  4263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4264. EXPECT_EQ(StatusCode::OK_200, res->status);
  4265. EXPECT_EQ("john", res->body);
  4266. }
  4267. {
  4268. auto res = cli.Get("/user/invalid-user");
  4269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4270. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4271. EXPECT_EQ("error", res->body);
  4272. }
  4273. }
  4274. // The pre-request handler must run before the request body is read, so a
  4275. // rejected request never forces the server to buffer a (potentially large)
  4276. // body. Here the posted body is larger than the payload limit: if the body
  4277. // were read first the server would answer 413, but because the pre-request
  4278. // handler runs first it answers 403 and the body is never read.
  4279. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4280. Server svr;
  4281. svr.set_payload_max_length(8);
  4282. auto handler_ran = false;
  4283. svr.Post("/reject", [&](const Request &req, Response &res) {
  4284. handler_ran = true;
  4285. res.set_content(req.body, "text/plain");
  4286. });
  4287. svr.Post("/accept", [](const Request &req, Response &res) {
  4288. res.set_content(req.body, "text/plain");
  4289. });
  4290. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4291. if (req.matched_route == "/reject") {
  4292. res.status = StatusCode::Forbidden_403;
  4293. res.set_content("denied", "text/plain");
  4294. return Server::HandlerResponse::Handled;
  4295. }
  4296. return Server::HandlerResponse::Unhandled;
  4297. });
  4298. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4299. auto se = detail::scope_exit([&] {
  4300. svr.stop();
  4301. thread.join();
  4302. ASSERT_FALSE(svr.is_running());
  4303. });
  4304. svr.wait_until_ready();
  4305. Client cli(HOST, PORT);
  4306. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4307. // rejects with 403 before the body is read, so 413 is never reached.
  4308. {
  4309. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4311. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4312. EXPECT_EQ("denied", res->body);
  4313. EXPECT_FALSE(handler_ran);
  4314. }
  4315. // An approved route still reads the body and enforces the payload limit.
  4316. {
  4317. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4320. }
  4321. }
  4322. TEST(UserDataTest, BasicOperations) {
  4323. httplib::UserData ud;
  4324. // Initially empty
  4325. EXPECT_FALSE(ud.has("key"));
  4326. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4327. // set and get
  4328. ud.set("key", 42);
  4329. EXPECT_TRUE(ud.has("key"));
  4330. auto *p = ud.get<int>("key");
  4331. ASSERT_NE(nullptr, p);
  4332. EXPECT_EQ(42, *p);
  4333. // Type mismatch → nullptr
  4334. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4335. // Overwrite with different type
  4336. ud.set("key", std::string("hello"));
  4337. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4338. auto *s = ud.get<std::string>("key");
  4339. ASSERT_NE(nullptr, s);
  4340. EXPECT_EQ("hello", *s);
  4341. // erase
  4342. ud.erase("key");
  4343. EXPECT_FALSE(ud.has("key"));
  4344. // clear
  4345. ud.set("a", 1);
  4346. ud.set("b", 2);
  4347. ud.clear();
  4348. EXPECT_FALSE(ud.has("a"));
  4349. EXPECT_FALSE(ud.has("b"));
  4350. }
  4351. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4352. struct AuthCtx {
  4353. std::string user_id;
  4354. };
  4355. Server svr;
  4356. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4357. res.user_data.set("auth", AuthCtx{"alice"});
  4358. return Server::HandlerResponse::Unhandled;
  4359. });
  4360. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4361. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4362. ASSERT_NE(nullptr, ctx);
  4363. res.set_content("Hello " + ctx->user_id, "text/plain");
  4364. });
  4365. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4366. auto se = detail::scope_exit([&] {
  4367. svr.stop();
  4368. thread.join();
  4369. ASSERT_FALSE(svr.is_running());
  4370. });
  4371. svr.wait_until_ready();
  4372. Client cli(HOST, PORT);
  4373. auto res = cli.Get("/me");
  4374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4375. EXPECT_EQ(StatusCode::OK_200, res->status);
  4376. EXPECT_EQ("Hello alice", res->body);
  4377. }
  4378. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4379. struct RoleCtx {
  4380. std::string role;
  4381. };
  4382. Server svr;
  4383. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4384. res.user_data.set("role", RoleCtx{"admin"});
  4385. return Server::HandlerResponse::Unhandled;
  4386. });
  4387. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4388. auto *ctx = res.user_data.get<RoleCtx>("role");
  4389. ASSERT_NE(nullptr, ctx);
  4390. res.set_content(ctx->role, "text/plain");
  4391. });
  4392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4393. auto se = detail::scope_exit([&] {
  4394. svr.stop();
  4395. thread.join();
  4396. ASSERT_FALSE(svr.is_running());
  4397. });
  4398. svr.wait_until_ready();
  4399. Client cli(HOST, PORT);
  4400. auto res = cli.Get("/role");
  4401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. EXPECT_EQ("admin", res->body);
  4404. }
  4405. TEST(InvalidFormatTest, StatusCode) {
  4406. Server svr;
  4407. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4408. res.set_content("Hello World!\n", "text/plain");
  4409. res.status = 9999; // Status should be a three-digit code...
  4410. });
  4411. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4412. auto se = detail::scope_exit([&] {
  4413. svr.stop();
  4414. thread.join();
  4415. ASSERT_FALSE(svr.is_running());
  4416. });
  4417. svr.wait_until_ready();
  4418. {
  4419. Client cli(HOST, PORT);
  4420. auto res = cli.Get("/hi");
  4421. ASSERT_FALSE(res);
  4422. }
  4423. }
  4424. TEST(URLFragmentTest, WithFragment) {
  4425. Server svr;
  4426. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4427. EXPECT_TRUE(req.target == "/hi");
  4428. });
  4429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4430. auto se = detail::scope_exit([&] {
  4431. svr.stop();
  4432. thread.join();
  4433. ASSERT_FALSE(svr.is_running());
  4434. });
  4435. svr.wait_until_ready();
  4436. {
  4437. Client cli(HOST, PORT);
  4438. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4439. EXPECT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::OK_200, res->status);
  4441. res = cli.Get("/hi%23key1=val1=key2=val2");
  4442. EXPECT_TRUE(res);
  4443. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4444. }
  4445. }
  4446. TEST(HeaderWriter, SetHeaderWriter) {
  4447. Server svr;
  4448. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4449. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4450. return detail::write_headers(strm, hdrs);
  4451. });
  4452. svr.Get("/hi", [](const Request &req, Response &res) {
  4453. auto it = req.headers.find("CustomClientHeader");
  4454. EXPECT_TRUE(it != req.headers.end());
  4455. EXPECT_EQ(it->second, "CustomClientValue");
  4456. res.set_content("Hello World!\n", "text/plain");
  4457. });
  4458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4459. auto se = detail::scope_exit([&] {
  4460. svr.stop();
  4461. thread.join();
  4462. ASSERT_FALSE(svr.is_running());
  4463. });
  4464. svr.wait_until_ready();
  4465. {
  4466. Client cli(HOST, PORT);
  4467. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4468. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4469. return detail::write_headers(strm, hdrs);
  4470. });
  4471. auto res = cli.Get("/hi");
  4472. EXPECT_TRUE(res);
  4473. EXPECT_EQ(StatusCode::OK_200, res->status);
  4474. auto it = res->headers.find("CustomServerHeader");
  4475. EXPECT_TRUE(it != res->headers.end());
  4476. EXPECT_EQ(it->second, "CustomServerValue");
  4477. }
  4478. }
  4479. class ServerTest : public ::testing::Test {
  4480. protected:
  4481. ServerTest()
  4482. : cli_(HOST, PORT)
  4483. #ifdef CPPHTTPLIB_SSL_ENABLED
  4484. ,
  4485. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4486. #endif
  4487. {
  4488. #ifdef CPPHTTPLIB_SSL_ENABLED
  4489. cli_.enable_server_certificate_verification(false);
  4490. #endif
  4491. // Allow LARGE_DATA (100MB) responses
  4492. cli_.set_payload_max_length(200 * 1024 * 1024);
  4493. }
  4494. virtual void SetUp() {
  4495. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4496. svr_.set_payload_max_length(200 * 1024 * 1024);
  4497. svr_.set_mount_point("/", "./www");
  4498. svr_.set_mount_point("/mount", "./www2");
  4499. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4500. svr_.Get("/hi",
  4501. [&](const Request & /*req*/, Response &res) {
  4502. res.set_content("Hello World!", "text/plain");
  4503. })
  4504. .Get("/file_content",
  4505. [&](const Request & /*req*/, Response &res) {
  4506. res.set_file_content("./www/dir/test.html");
  4507. })
  4508. .Get("/file_content_with_content_type",
  4509. [&](const Request & /*req*/, Response &res) {
  4510. res.set_file_content("./www/file", "text/plain");
  4511. })
  4512. .Get("/invalid_file_content",
  4513. [&](const Request & /*req*/, Response &res) {
  4514. res.set_file_content("./www/dir/invalid_file_path");
  4515. })
  4516. .Get("/http_response_splitting",
  4517. [&](const Request & /*req*/, Response &res) {
  4518. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4519. EXPECT_EQ(0U, res.headers.size());
  4520. EXPECT_FALSE(res.has_header("a"));
  4521. res.set_header("a", "1\nSet-Cookie: a=1");
  4522. EXPECT_EQ(0U, res.headers.size());
  4523. EXPECT_FALSE(res.has_header("a"));
  4524. res.set_header("a", "1\rSet-Cookie: a=1");
  4525. EXPECT_EQ(0U, res.headers.size());
  4526. EXPECT_FALSE(res.has_header("a"));
  4527. res.set_header("a\r\nb", "0");
  4528. EXPECT_EQ(0U, res.headers.size());
  4529. EXPECT_FALSE(res.has_header("a"));
  4530. res.set_header("a\rb", "0");
  4531. EXPECT_EQ(0U, res.headers.size());
  4532. EXPECT_FALSE(res.has_header("a"));
  4533. res.set_header("a\nb", "0");
  4534. EXPECT_EQ(0U, res.headers.size());
  4535. EXPECT_FALSE(res.has_header("a"));
  4536. res.set_redirect("1\r\nSet-Cookie: a=1");
  4537. EXPECT_EQ(0U, res.headers.size());
  4538. EXPECT_FALSE(res.has_header("Location"));
  4539. })
  4540. .Get("/slow",
  4541. [&](const Request & /*req*/, Response &res) {
  4542. std::this_thread::sleep_for(std::chrono::seconds(4));
  4543. res.set_content("slow", "text/plain");
  4544. })
  4545. #if 0
  4546. .Post("/slowpost",
  4547. [&](const Request & /*req*/, Response &res) {
  4548. std::this_thread::sleep_for(std::chrono::seconds(2));
  4549. res.set_content("slow", "text/plain");
  4550. })
  4551. #endif
  4552. .Get("/remote_addr",
  4553. [&](const Request &req, Response &res) {
  4554. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4555. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4556. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4557. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4558. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4559. #endif
  4560. res.set_content(req.remote_addr, "text/plain");
  4561. })
  4562. .Get("/local_addr",
  4563. [&](const Request &req, Response &res) {
  4564. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4565. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4566. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4567. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4568. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4569. #endif
  4570. auto local_addr = req.local_addr;
  4571. auto local_port = std::to_string(req.local_port);
  4572. res.set_content(local_addr.append(":").append(local_port),
  4573. "text/plain");
  4574. })
  4575. .Get("/endwith%",
  4576. [&](const Request & /*req*/, Response &res) {
  4577. res.set_content("Hello World!", "text/plain");
  4578. })
  4579. .Get("/a\\+\\+b",
  4580. [&](const Request &req, Response &res) {
  4581. ASSERT_TRUE(req.has_param("a +b"));
  4582. auto val = req.get_param_value("a +b");
  4583. res.set_content(val, "text/plain");
  4584. })
  4585. .Get("/", [&](const Request & /*req*/,
  4586. Response &res) { res.set_redirect("/hi"); })
  4587. .Post("/1",
  4588. [](const Request & /*req*/, Response &res) {
  4589. res.set_redirect("/2", StatusCode::SeeOther_303);
  4590. })
  4591. .Get("/2",
  4592. [](const Request & /*req*/, Response &res) {
  4593. res.set_content("redirected.", "text/plain");
  4594. res.status = StatusCode::OK_200;
  4595. })
  4596. .Post("/person",
  4597. [&](const Request &req, Response &res) {
  4598. if (req.has_param("name") && req.has_param("note")) {
  4599. persons_[req.get_param_value("name")] =
  4600. req.get_param_value("note");
  4601. } else {
  4602. res.status = StatusCode::BadRequest_400;
  4603. }
  4604. })
  4605. .Put("/person",
  4606. [&](const Request &req, Response &res) {
  4607. if (req.has_param("name") && req.has_param("note")) {
  4608. persons_[req.get_param_value("name")] =
  4609. req.get_param_value("note");
  4610. } else {
  4611. res.status = StatusCode::BadRequest_400;
  4612. }
  4613. })
  4614. .Get("/person/(.*)",
  4615. [&](const Request &req, Response &res) {
  4616. string name = req.matches[1];
  4617. if (persons_.find(name) != persons_.end()) {
  4618. auto note = persons_[name];
  4619. res.set_content(note, "text/plain");
  4620. } else {
  4621. res.status = StatusCode::NotFound_404;
  4622. }
  4623. })
  4624. .Delete("/person",
  4625. [&](const Request &req, Response &res) {
  4626. if (req.has_param("name")) {
  4627. string name = req.get_param_value("name");
  4628. if (persons_.find(name) != persons_.end()) {
  4629. persons_.erase(name);
  4630. res.set_content("DELETED", "text/plain");
  4631. } else {
  4632. res.status = StatusCode::NotFound_404;
  4633. }
  4634. } else {
  4635. res.status = StatusCode::BadRequest_400;
  4636. }
  4637. })
  4638. .Post("/x-www-form-urlencoded-json",
  4639. [&](const Request &req, Response &res) {
  4640. auto json = req.get_param_value("json");
  4641. ASSERT_EQ(JSON_DATA, json);
  4642. res.set_content(json, "appliation/json");
  4643. res.status = StatusCode::OK_200;
  4644. })
  4645. .Get("/streamed-chunked",
  4646. [&](const Request & /*req*/, Response &res) {
  4647. res.set_chunked_content_provider(
  4648. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4649. sink.os << "123";
  4650. sink.os << "456";
  4651. sink.os << "789";
  4652. sink.done();
  4653. return true;
  4654. });
  4655. })
  4656. .Get("/streamed-chunked-with-prohibited-trailer",
  4657. [&](const Request & /*req*/, Response &res) {
  4658. auto i = new int(0);
  4659. // Declare both a prohibited trailer (Content-Length) and an
  4660. // allowed one
  4661. res.set_header("Trailer", "Content-Length, X-Allowed");
  4662. res.set_chunked_content_provider(
  4663. "text/plain",
  4664. [i](size_t /*offset*/, DataSink &sink) {
  4665. switch (*i) {
  4666. case 0: sink.os << "123"; break;
  4667. case 1: sink.os << "456"; break;
  4668. case 2: sink.os << "789"; break;
  4669. case 3: {
  4670. sink.done_with_trailer(
  4671. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4672. } break;
  4673. }
  4674. (*i)++;
  4675. return true;
  4676. },
  4677. [i](bool success) {
  4678. EXPECT_TRUE(success);
  4679. delete i;
  4680. });
  4681. })
  4682. .Get("/streamed-chunked2",
  4683. [&](const Request & /*req*/, Response &res) {
  4684. auto i = new int(0);
  4685. res.set_chunked_content_provider(
  4686. "text/plain",
  4687. [i](size_t /*offset*/, DataSink &sink) {
  4688. switch (*i) {
  4689. case 0: sink.os << "123"; break;
  4690. case 1: sink.os << "456"; break;
  4691. case 2: sink.os << "789"; break;
  4692. case 3: sink.done(); break;
  4693. }
  4694. (*i)++;
  4695. return true;
  4696. },
  4697. [i](bool success) {
  4698. EXPECT_TRUE(success);
  4699. delete i;
  4700. });
  4701. })
  4702. .Get("/streamed-chunked-with-trailer",
  4703. [&](const Request & /*req*/, Response &res) {
  4704. auto i = new int(0);
  4705. res.set_header("Trailer", "Dummy1, Dummy2");
  4706. res.set_chunked_content_provider(
  4707. "text/plain",
  4708. [i](size_t /*offset*/, DataSink &sink) {
  4709. switch (*i) {
  4710. case 0: sink.os << "123"; break;
  4711. case 1: sink.os << "456"; break;
  4712. case 2: sink.os << "789"; break;
  4713. case 3: {
  4714. sink.done_with_trailer(
  4715. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4716. } break;
  4717. }
  4718. (*i)++;
  4719. return true;
  4720. },
  4721. [i](bool success) {
  4722. EXPECT_TRUE(success);
  4723. delete i;
  4724. });
  4725. })
  4726. .Get("/streamed",
  4727. [&](const Request & /*req*/, Response &res) {
  4728. res.set_content_provider(
  4729. 6, "text/plain",
  4730. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4731. sink.os << (offset < 3 ? "a" : "b");
  4732. return true;
  4733. });
  4734. })
  4735. .Get("/streamed-without-length",
  4736. [&](const Request & /*req*/, Response &res) {
  4737. auto data = new std::string("abcdefg");
  4738. res.set_content_provider(
  4739. "text/plain",
  4740. [data](size_t offset, DataSink &sink) {
  4741. if (offset < data->size()) {
  4742. sink.os << data->substr(offset);
  4743. }
  4744. sink.done();
  4745. return true;
  4746. },
  4747. [data](bool success) {
  4748. EXPECT_TRUE(success);
  4749. delete data;
  4750. });
  4751. })
  4752. .Get("/streamed-with-range",
  4753. [&](const Request &req, Response &res) {
  4754. auto data = new std::string("abcdefg");
  4755. // An explicit status keeps the server from picking the 206 it
  4756. // would otherwise choose for a ranged request, so the response
  4757. // is not a partial representation.
  4758. auto status = req.get_param_value("status");
  4759. if (status == "200") {
  4760. res.status = StatusCode::OK_200;
  4761. } else if (status == "403") {
  4762. res.status = StatusCode::Forbidden_403;
  4763. }
  4764. res.set_content_provider(
  4765. data->size(), "text/plain",
  4766. [data](size_t offset, size_t length, DataSink &sink) {
  4767. size_t DATA_CHUNK_SIZE = 4;
  4768. const auto &d = *data;
  4769. auto out_len =
  4770. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4771. auto ret =
  4772. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4773. EXPECT_TRUE(ret);
  4774. return true;
  4775. },
  4776. [data, &req](bool success) {
  4777. EXPECT_EQ(success, !req.has_param("error"));
  4778. delete data;
  4779. });
  4780. })
  4781. .Get("/streamed-cancel",
  4782. [&](const Request & /*req*/, Response &res) {
  4783. res.set_content_provider(
  4784. size_t(-1), "text/plain",
  4785. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4786. sink.os << "data_chunk";
  4787. return true;
  4788. });
  4789. })
  4790. .Get("/regex-with-delimiter",
  4791. [&](const Request &req, Response & /*res*/) {
  4792. ASSERT_TRUE(req.has_param("key"));
  4793. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4794. })
  4795. .Get("/with-range",
  4796. [&](const Request & /*req*/, Response &res) {
  4797. res.set_content("abcdefg", "text/plain");
  4798. })
  4799. .Get("/test-start-time",
  4800. [&](const Request &req, Response & /*res*/) {
  4801. EXPECT_NE(req.start_time_,
  4802. std::chrono::steady_clock::time_point::min());
  4803. })
  4804. .Get("/with-range-customized-response",
  4805. [&](const Request & /*req*/, Response &res) {
  4806. res.status = StatusCode::BadRequest_400;
  4807. res.set_content(JSON_DATA, "application/json");
  4808. })
  4809. .Post("/chunked",
  4810. [&](const Request &req, Response & /*res*/) {
  4811. EXPECT_EQ(req.body, "dechunked post body");
  4812. })
  4813. .Post("/large-chunked",
  4814. [&](const Request &req, Response & /*res*/) {
  4815. std::string expected(6 * 30 * 1024u, 'a');
  4816. EXPECT_EQ(req.body, expected);
  4817. })
  4818. .Post("/multipart",
  4819. [&](const Request &req, Response & /*res*/) {
  4820. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4821. req.form.get_field_count("text2") +
  4822. req.form.get_field_count("file3") +
  4823. req.form.get_field_count("file4"));
  4824. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4825. req.form.get_file_count("file2"));
  4826. ASSERT_TRUE(!req.form.has_file("???"));
  4827. ASSERT_TRUE(!req.form.has_field("???"));
  4828. ASSERT_TRUE(req.body.empty());
  4829. {
  4830. const auto &text = req.form.get_field("text1");
  4831. EXPECT_EQ("text default", text);
  4832. }
  4833. {
  4834. const auto &text = req.form.get_field("text2");
  4835. EXPECT_EQ("aωb", text);
  4836. }
  4837. {
  4838. const auto &file = req.form.get_file("file1");
  4839. EXPECT_EQ("hello.txt", file.filename);
  4840. EXPECT_EQ("text/plain", file.content_type);
  4841. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4842. }
  4843. {
  4844. const auto &file = req.form.get_file("file2");
  4845. EXPECT_EQ("world.json", file.filename);
  4846. EXPECT_EQ("application/json", file.content_type);
  4847. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4848. }
  4849. {
  4850. const auto &text = req.form.get_field("file3");
  4851. EXPECT_EQ(0u, text.size());
  4852. }
  4853. {
  4854. const auto &text = req.form.get_field("file4");
  4855. EXPECT_EQ(0u, text.size());
  4856. }
  4857. })
  4858. .Post("/multipart/multi_file_values",
  4859. [&](const Request &req, Response & /*res*/) {
  4860. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4861. req.form.get_field_count("multi_text1"));
  4862. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4863. ASSERT_TRUE(!req.form.has_file("???"));
  4864. ASSERT_TRUE(!req.form.has_field("???"));
  4865. ASSERT_TRUE(req.body.empty());
  4866. {
  4867. const auto &text = req.form.get_field("text");
  4868. EXPECT_EQ("default text", text);
  4869. }
  4870. {
  4871. const auto &text1_values = req.form.get_fields("multi_text1");
  4872. EXPECT_EQ(2u, text1_values.size());
  4873. EXPECT_EQ("aaaaa", text1_values[0]);
  4874. EXPECT_EQ("bbbbb", text1_values[1]);
  4875. }
  4876. {
  4877. const auto &file1_values = req.form.get_files("multi_file1");
  4878. EXPECT_EQ(2u, file1_values.size());
  4879. auto file1 = file1_values[0];
  4880. EXPECT_EQ(file1.filename, "hello.txt");
  4881. EXPECT_EQ(file1.content_type, "text/plain");
  4882. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4883. auto file2 = file1_values[1];
  4884. EXPECT_EQ(file2.filename, "world.json");
  4885. EXPECT_EQ(file2.content_type, "application/json");
  4886. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4887. }
  4888. })
  4889. .Post("/empty",
  4890. [&](const Request &req, Response &res) {
  4891. EXPECT_EQ(req.body, "");
  4892. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4893. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4894. res.set_content("empty", "text/plain");
  4895. })
  4896. .Post("/empty-no-content-type",
  4897. [&](const Request &req, Response &res) {
  4898. EXPECT_EQ(req.body, "");
  4899. EXPECT_FALSE(req.has_header("Content-Type"));
  4900. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4901. res.set_content("empty-no-content-type", "text/plain");
  4902. })
  4903. .Post("/path-only",
  4904. [&](const Request &req, Response &res) {
  4905. EXPECT_EQ(req.body, "");
  4906. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4907. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4908. res.set_content("path-only", "text/plain");
  4909. })
  4910. .Post("/path-headers-only",
  4911. [&](const Request &req, Response &res) {
  4912. EXPECT_EQ(req.body, "");
  4913. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4914. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4915. EXPECT_EQ("world", req.get_header_value("hello"));
  4916. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4917. res.set_content("path-headers-only", "text/plain");
  4918. })
  4919. .Post("/post-large",
  4920. [&](const Request &req, Response &res) {
  4921. EXPECT_EQ(req.body, LARGE_DATA);
  4922. res.set_content(req.body, "text/plain");
  4923. })
  4924. .Post("/post-loopback",
  4925. [&](const Request &, Response &res,
  4926. ContentReader const &content_reader) {
  4927. std::string body;
  4928. content_reader([&](const char *data, size_t data_length) {
  4929. body.append(data, data_length);
  4930. return true;
  4931. });
  4932. res.set_content(body, "text/plain");
  4933. })
  4934. .Put("/put-loopback",
  4935. [&](const Request &, Response &res,
  4936. ContentReader const &content_reader) {
  4937. std::string body;
  4938. content_reader([&](const char *data, size_t data_length) {
  4939. body.append(data, data_length);
  4940. return true;
  4941. });
  4942. res.set_content(body, "text/plain");
  4943. })
  4944. .Patch("/patch-loopback",
  4945. [&](const Request &, Response &res,
  4946. ContentReader const &content_reader) {
  4947. std::string body;
  4948. content_reader([&](const char *data, size_t data_length) {
  4949. body.append(data, data_length);
  4950. return true;
  4951. });
  4952. res.set_content(body, "text/plain");
  4953. })
  4954. .Put("/empty-no-content-type",
  4955. [&](const Request &req, Response &res) {
  4956. EXPECT_EQ(req.body, "");
  4957. EXPECT_FALSE(req.has_header("Content-Type"));
  4958. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4959. res.set_content("empty-no-content-type", "text/plain");
  4960. })
  4961. .Put("/put",
  4962. [&](const Request &req, Response &res) {
  4963. EXPECT_EQ(req.body, "PUT");
  4964. res.set_content(req.body, "text/plain");
  4965. })
  4966. .Put("/put-large",
  4967. [&](const Request &req, Response &res) {
  4968. EXPECT_EQ(req.body, LARGE_DATA);
  4969. res.set_content(req.body, "text/plain");
  4970. })
  4971. .Patch("/patch",
  4972. [&](const Request &req, Response &res) {
  4973. EXPECT_EQ(req.body, "PATCH");
  4974. res.set_content(req.body, "text/plain");
  4975. })
  4976. .Delete("/delete",
  4977. [&](const Request & /*req*/, Response &res) {
  4978. res.set_content("DELETE", "text/plain");
  4979. })
  4980. .Delete("/delete-body",
  4981. [&](const Request &req, Response &res) {
  4982. EXPECT_EQ(req.body, "content");
  4983. res.set_content(req.body, "text/plain");
  4984. })
  4985. .Options(R"(\*)",
  4986. [&](const Request & /*req*/, Response &res) {
  4987. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4988. })
  4989. .CustomRoute("PROPFIND", "/dav/:id",
  4990. [&](const Request &req, Response &res) {
  4991. res.set_header("x-body-size",
  4992. std::to_string(req.body.size()));
  4993. res.set_header("x-matched-route", req.matched_route);
  4994. res.set_header("x-dav-id", req.path_params.at("id"));
  4995. res.status = StatusCode::MultiStatus_207;
  4996. res.set_content(req.body, "application/xml");
  4997. })
  4998. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4999. [&](const Request &req, Response &res) {
  5000. res.set_header("x-dav-match", req.matches[1]);
  5001. res.status = StatusCode::MultiStatus_207;
  5002. })
  5003. .CustomRoute("MKCOL", "/dav-mkcol",
  5004. [&](const Request &req, Response &res) {
  5005. EXPECT_TRUE(req.body.empty());
  5006. res.status = StatusCode::Created_201;
  5007. })
  5008. .CustomRoute(
  5009. "REPORT", "/dav-report",
  5010. [&](const Request & /*req*/, Response &res,
  5011. const ContentReader &content_reader) {
  5012. std::string body;
  5013. content_reader([&](const char *data, size_t data_length) {
  5014. body.append(data, data_length);
  5015. return true;
  5016. });
  5017. res.set_header("x-body-size", std::to_string(body.size()));
  5018. res.status = StatusCode::MultiStatus_207;
  5019. res.set_content(body, "application/xml");
  5020. })
  5021. .Get("/request-target",
  5022. [&](const Request &req, Response & /*res*/) {
  5023. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5024. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5025. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5026. })
  5027. .Get("/long-query-value",
  5028. [&](const Request &req, Response & /*res*/) {
  5029. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5030. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5031. })
  5032. .Get("/too-long-query-value",
  5033. [&](const Request &req, Response & /*res*/) {
  5034. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5035. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5036. })
  5037. .Get("/array-param",
  5038. [&](const Request &req, Response & /*res*/) {
  5039. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5040. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5041. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5042. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5043. })
  5044. .Get("/array-param-values",
  5045. [&](const Request &req, Response & /*res*/) {
  5046. auto values = req.get_param_values("array");
  5047. EXPECT_EQ(3u, values.size());
  5048. EXPECT_EQ("value1", values[0]);
  5049. EXPECT_EQ("value2", values[1]);
  5050. EXPECT_EQ("value3", values[2]);
  5051. auto empty = req.get_param_values("nonexistent");
  5052. EXPECT_TRUE(empty.empty());
  5053. })
  5054. .Post("/validate-no-multiple-headers",
  5055. [&](const Request &req, Response & /*res*/) {
  5056. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5057. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5058. })
  5059. .Post("/content_receiver",
  5060. [&](const Request &req, Response &res,
  5061. const ContentReader &content_reader) {
  5062. if (req.is_multipart_form_data()) {
  5063. std::vector<FormData> items;
  5064. content_reader(
  5065. [&](const FormData &file) {
  5066. items.push_back(file);
  5067. return true;
  5068. },
  5069. [&](const char *data, size_t data_length) {
  5070. items.back().content.append(data, data_length);
  5071. return true;
  5072. });
  5073. EXPECT_EQ(5u, items.size());
  5074. {
  5075. const auto &file = get_file_value(items, "text1");
  5076. EXPECT_TRUE(file.filename.empty());
  5077. EXPECT_EQ("text default", file.content);
  5078. }
  5079. {
  5080. const auto &file = get_file_value(items, "text2");
  5081. EXPECT_TRUE(file.filename.empty());
  5082. EXPECT_EQ("aωb", file.content);
  5083. }
  5084. {
  5085. const auto &file = get_file_value(items, "file1");
  5086. EXPECT_EQ("hello.txt", file.filename);
  5087. EXPECT_EQ("text/plain", file.content_type);
  5088. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5089. }
  5090. {
  5091. const auto &file = get_file_value(items, "file2");
  5092. EXPECT_EQ("world.json", file.filename);
  5093. EXPECT_EQ("application/json", file.content_type);
  5094. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5095. }
  5096. {
  5097. const auto &file = get_file_value(items, "file3");
  5098. EXPECT_TRUE(file.filename.empty());
  5099. EXPECT_EQ("application/octet-stream", file.content_type);
  5100. EXPECT_EQ(0u, file.content.size());
  5101. }
  5102. } else {
  5103. std::string body;
  5104. content_reader([&](const char *data, size_t data_length) {
  5105. EXPECT_EQ(7U, data_length);
  5106. body.append(data, data_length);
  5107. return true;
  5108. });
  5109. EXPECT_EQ(body, "content");
  5110. res.set_content(body, "text/plain");
  5111. }
  5112. })
  5113. .Put("/content_receiver",
  5114. [&](const Request & /*req*/, Response &res,
  5115. const ContentReader &content_reader) {
  5116. std::string body;
  5117. content_reader([&](const char *data, size_t data_length) {
  5118. body.append(data, data_length);
  5119. return true;
  5120. });
  5121. EXPECT_EQ(body, "content");
  5122. res.set_content(body, "text/plain");
  5123. })
  5124. .Patch("/content_receiver",
  5125. [&](const Request & /*req*/, Response &res,
  5126. const ContentReader &content_reader) {
  5127. std::string body;
  5128. content_reader([&](const char *data, size_t data_length) {
  5129. body.append(data, data_length);
  5130. return true;
  5131. });
  5132. EXPECT_EQ(body, "content");
  5133. res.set_content(body, "text/plain");
  5134. })
  5135. .Post("/query-string-and-body",
  5136. [&](const Request &req, Response & /*res*/) {
  5137. ASSERT_TRUE(req.has_param("key"));
  5138. EXPECT_EQ(req.get_param_value("key"), "value");
  5139. EXPECT_EQ(req.body, "content");
  5140. })
  5141. .Get("/last-request",
  5142. [&](const Request &req, Response & /*res*/) {
  5143. EXPECT_EQ("close", req.get_header_value("Connection"));
  5144. })
  5145. .Get(R"(/redirect/(\d+))",
  5146. [&](const Request &req, Response &res) {
  5147. auto num = std::stoi(req.matches[1]) + 1;
  5148. std::string url = "/redirect/" + std::to_string(num);
  5149. res.set_redirect(url);
  5150. })
  5151. .Post("/binary",
  5152. [&](const Request &req, Response &res) {
  5153. EXPECT_EQ(4U, req.body.size());
  5154. EXPECT_EQ("application/octet-stream",
  5155. req.get_header_value("Content-Type"));
  5156. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5157. res.set_content(req.body, "application/octet-stream");
  5158. })
  5159. .Put("/binary",
  5160. [&](const Request &req, Response &res) {
  5161. EXPECT_EQ(4U, req.body.size());
  5162. EXPECT_EQ("application/octet-stream",
  5163. req.get_header_value("Content-Type"));
  5164. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5165. res.set_content(req.body, "application/octet-stream");
  5166. })
  5167. .Patch("/binary",
  5168. [&](const Request &req, Response &res) {
  5169. EXPECT_EQ(4U, req.body.size());
  5170. EXPECT_EQ("application/octet-stream",
  5171. req.get_header_value("Content-Type"));
  5172. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5173. res.set_content(req.body, "application/octet-stream");
  5174. })
  5175. .Delete("/binary",
  5176. [&](const Request &req, Response &res) {
  5177. EXPECT_EQ(4U, req.body.size());
  5178. EXPECT_EQ("application/octet-stream",
  5179. req.get_header_value("Content-Type"));
  5180. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5181. res.set_content(req.body, "application/octet-stream");
  5182. })
  5183. .Get("/issue1772",
  5184. [&](const Request & /*req*/, Response &res) {
  5185. res.status = 401;
  5186. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5187. })
  5188. .Delete("/issue609",
  5189. [](const httplib::Request &, httplib::Response &res,
  5190. const httplib::ContentReader &) {
  5191. res.set_content("ok", "text/plain");
  5192. })
  5193. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5194. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5195. .Get("/compress",
  5196. [&](const Request & /*req*/, Response &res) {
  5197. res.set_content(
  5198. "12345678901234567890123456789012345678901234567890123456789"
  5199. "01234567890123456789012345678901234567890",
  5200. "text/plain");
  5201. })
  5202. .Get("/compress-with-charset",
  5203. [&](const Request & /*req*/, Response &res) {
  5204. res.set_content(
  5205. "12345678901234567890123456789012345678901234567890123456789"
  5206. "01234567890123456789012345678901234567890",
  5207. "application/json; charset=utf-8");
  5208. })
  5209. .Get("/nocompress",
  5210. [&](const Request & /*req*/, Response &res) {
  5211. res.set_content(
  5212. "12345678901234567890123456789012345678901234567890123456789"
  5213. "01234567890123456789012345678901234567890",
  5214. "application/octet-stream");
  5215. })
  5216. .Post("/compress-multipart",
  5217. [&](const Request &req, Response & /*res*/) {
  5218. EXPECT_EQ(2u, req.form.fields.size());
  5219. ASSERT_TRUE(!req.form.has_field("???"));
  5220. {
  5221. const auto &text = req.form.get_field("key1");
  5222. EXPECT_EQ("test", text);
  5223. }
  5224. {
  5225. const auto &text = req.form.get_field("key2");
  5226. EXPECT_EQ("--abcdefg123", text);
  5227. }
  5228. })
  5229. #endif
  5230. ;
  5231. persons_["john"] = "programmer";
  5232. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5233. svr_.wait_until_ready();
  5234. }
  5235. virtual void TearDown() {
  5236. svr_.stop();
  5237. if (!request_threads_.empty()) {
  5238. std::this_thread::sleep_for(std::chrono::seconds(1));
  5239. for (auto &t : request_threads_) {
  5240. t.join();
  5241. }
  5242. }
  5243. t_.join();
  5244. }
  5245. map<string, string> persons_;
  5246. #ifdef CPPHTTPLIB_SSL_ENABLED
  5247. SSLClient cli_;
  5248. SSLServer svr_;
  5249. #else
  5250. Client cli_;
  5251. Server svr_;
  5252. #endif
  5253. thread t_;
  5254. std::vector<thread> request_threads_;
  5255. };
  5256. TEST_F(ServerTest, GetMethod200) {
  5257. auto res = cli_.Get("/hi");
  5258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5259. EXPECT_EQ("HTTP/1.1", res->version);
  5260. EXPECT_EQ(StatusCode::OK_200, res->status);
  5261. EXPECT_EQ("OK", res->reason);
  5262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5263. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5264. EXPECT_EQ("Hello World!", res->body);
  5265. }
  5266. TEST_F(ServerTest, GetEmptyFile) {
  5267. auto res = cli_.Get("/empty_file");
  5268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5271. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5272. EXPECT_EQ("", res->body);
  5273. }
  5274. TEST_F(ServerTest, GetFileContent) {
  5275. auto res = cli_.Get("/file_content");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::OK_200, res->status);
  5278. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5279. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5280. EXPECT_EQ("test.html", res->body);
  5281. }
  5282. TEST_F(ServerTest, GetFileContentWithRange) {
  5283. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5286. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5287. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5288. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5289. EXPECT_EQ("est", res->body);
  5290. }
  5291. TEST_F(ServerTest, GetFileContentWithContentType) {
  5292. auto res = cli_.Get("/file_content_with_content_type");
  5293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5294. EXPECT_EQ(StatusCode::OK_200, res->status);
  5295. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5296. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5297. EXPECT_EQ("file\n", res->body);
  5298. }
  5299. TEST_F(ServerTest, GetInvalidFileContent) {
  5300. auto res = cli_.Get("/invalid_file_content");
  5301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5302. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5303. }
  5304. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5305. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5307. EXPECT_EQ("HTTP/1.1", res->version);
  5308. EXPECT_EQ(StatusCode::OK_200, res->status);
  5309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5310. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5311. EXPECT_EQ("Hello World!", res->body);
  5312. }
  5313. TEST_F(ServerTest, GetMethod302) {
  5314. auto res = cli_.Get("/");
  5315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5316. EXPECT_EQ(StatusCode::Found_302, res->status);
  5317. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5318. }
  5319. TEST_F(ServerTest, GetMethod302Redirect) {
  5320. cli_.set_follow_location(true);
  5321. auto res = cli_.Get("/");
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. EXPECT_EQ(StatusCode::OK_200, res->status);
  5324. EXPECT_EQ("Hello World!", res->body);
  5325. EXPECT_EQ("/hi", res->location);
  5326. }
  5327. TEST_F(ServerTest, GetMethod404) {
  5328. auto res = cli_.Get("/invalid");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5331. }
  5332. TEST_F(ServerTest, HeadMethod200) {
  5333. auto res = cli_.Head("/hi");
  5334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5335. EXPECT_EQ(StatusCode::OK_200, res->status);
  5336. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5337. EXPECT_TRUE(res->body.empty());
  5338. }
  5339. TEST_F(ServerTest, HeadMethod200Static) {
  5340. auto res = cli_.Head("/mount/dir/index.html");
  5341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5344. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5345. EXPECT_TRUE(res->body.empty());
  5346. }
  5347. TEST_F(ServerTest, HeadMethod404) {
  5348. auto res = cli_.Head("/invalid");
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5351. EXPECT_TRUE(res->body.empty());
  5352. }
  5353. TEST_F(ServerTest, GetMethodPersonJohn) {
  5354. auto res = cli_.Get("/person/john");
  5355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("programmer", res->body);
  5359. }
  5360. TEST_F(ServerTest, PostMethod1) {
  5361. auto res = cli_.Get("/person/john1");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5364. res = cli_.Post("/person", "name=john1&note=coder",
  5365. "application/x-www-form-urlencoded");
  5366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5367. ASSERT_EQ(StatusCode::OK_200, res->status);
  5368. res = cli_.Get("/person/john1");
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. ASSERT_EQ(StatusCode::OK_200, res->status);
  5371. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5372. ASSERT_EQ("coder", res->body);
  5373. }
  5374. TEST_F(ServerTest, PostMethod2) {
  5375. auto res = cli_.Get("/person/john2");
  5376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5377. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5378. Params params;
  5379. params.emplace("name", "john2");
  5380. params.emplace("note", "coder");
  5381. res = cli_.Post("/person", params);
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. ASSERT_EQ(StatusCode::OK_200, res->status);
  5384. res = cli_.Get("/person/john2");
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5388. ASSERT_EQ("coder", res->body);
  5389. }
  5390. TEST_F(ServerTest, PutMethod3) {
  5391. auto res = cli_.Get("/person/john3");
  5392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5393. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5394. Params params;
  5395. params.emplace("name", "john3");
  5396. params.emplace("note", "coder");
  5397. res = cli_.Put("/person", params);
  5398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5399. ASSERT_EQ(StatusCode::OK_200, res->status);
  5400. res = cli_.Get("/person/john3");
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. ASSERT_EQ(StatusCode::OK_200, res->status);
  5403. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5404. ASSERT_EQ("coder", res->body);
  5405. }
  5406. TEST_F(ServerTest, DeleteMethod1) {
  5407. auto res = cli_.Get("/person/john4");
  5408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5410. Params params;
  5411. params.emplace("name", "john4");
  5412. params.emplace("note", "coder");
  5413. res = cli_.Post("/person", params);
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. ASSERT_EQ(StatusCode::OK_200, res->status);
  5416. res = cli_.Get("/person/john4");
  5417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5418. ASSERT_EQ(StatusCode::OK_200, res->status);
  5419. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5420. ASSERT_EQ("coder", res->body);
  5421. Params delete_params;
  5422. delete_params.emplace("name", "john4");
  5423. res = cli_.Delete("/person", delete_params);
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. ASSERT_EQ(StatusCode::OK_200, res->status);
  5426. ASSERT_EQ("DELETED", res->body);
  5427. res = cli_.Get("/person/john4");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5430. }
  5431. TEST_F(ServerTest, DeleteMethod2) {
  5432. auto res = cli_.Get("/person/john5");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5435. Params params;
  5436. params.emplace("name", "john5");
  5437. params.emplace("note", "developer");
  5438. res = cli_.Post("/person", params);
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. res = cli_.Get("/person/john5");
  5442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5443. ASSERT_EQ(StatusCode::OK_200, res->status);
  5444. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5445. ASSERT_EQ("developer", res->body);
  5446. Params delete_params;
  5447. delete_params.emplace("name", "john5");
  5448. Headers headers;
  5449. headers.emplace("Custom-Header", "test-value");
  5450. res = cli_.Delete("/person", headers, delete_params);
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. ASSERT_EQ(StatusCode::OK_200, res->status);
  5453. ASSERT_EQ("DELETED", res->body);
  5454. res = cli_.Get("/person/john5");
  5455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5456. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5457. }
  5458. TEST_F(ServerTest, DeleteMethod3) {
  5459. auto res = cli_.Get("/person/john6");
  5460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5461. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5462. Params params;
  5463. params.emplace("name", "john6");
  5464. params.emplace("note", "tester");
  5465. res = cli_.Post("/person", params);
  5466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5467. ASSERT_EQ(StatusCode::OK_200, res->status);
  5468. res = cli_.Get("/person/john6");
  5469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5470. ASSERT_EQ(StatusCode::OK_200, res->status);
  5471. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5472. ASSERT_EQ("tester", res->body);
  5473. Params delete_params;
  5474. delete_params.emplace("name", "john6");
  5475. Headers headers;
  5476. headers.emplace("Custom-Header", "test-value");
  5477. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5479. ASSERT_EQ(StatusCode::OK_200, res->status);
  5480. ASSERT_EQ("DELETED", res->body);
  5481. res = cli_.Get("/person/john6");
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5484. }
  5485. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5486. Params params;
  5487. params.emplace("json", JSON_DATA);
  5488. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. ASSERT_EQ(StatusCode::OK_200, res->status);
  5491. ASSERT_EQ(JSON_DATA, res->body);
  5492. }
  5493. TEST_F(ServerTest, PostEmptyContent) {
  5494. auto res = cli_.Post("/empty", "", "text/plain");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. ASSERT_EQ(StatusCode::OK_200, res->status);
  5497. ASSERT_EQ("empty", res->body);
  5498. }
  5499. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5500. auto res = cli_.Post("/empty-no-content-type");
  5501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5502. ASSERT_EQ(StatusCode::OK_200, res->status);
  5503. ASSERT_EQ("empty-no-content-type", res->body);
  5504. }
  5505. TEST_F(ServerTest, PostPathOnly) {
  5506. auto res = cli_.Post("/path-only");
  5507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5508. ASSERT_EQ(StatusCode::OK_200, res->status);
  5509. ASSERT_EQ("path-only", res->body);
  5510. }
  5511. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5512. auto res = cli_.Post("/path-headers-only",
  5513. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5515. ASSERT_EQ(StatusCode::OK_200, res->status);
  5516. ASSERT_EQ("path-headers-only", res->body);
  5517. }
  5518. TEST_F(ServerTest, PostLarge) {
  5519. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. ASSERT_EQ(StatusCode::OK_200, res->status);
  5522. EXPECT_EQ(LARGE_DATA, res->body);
  5523. }
  5524. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5525. auto res = cli_.Put("/empty-no-content-type");
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. ASSERT_EQ(StatusCode::OK_200, res->status);
  5528. ASSERT_EQ("empty-no-content-type", res->body);
  5529. }
  5530. TEST_F(ServerTest, GetMethodDir) {
  5531. auto res = cli_.Get("/dir/");
  5532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5533. EXPECT_EQ(StatusCode::OK_200, res->status);
  5534. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5535. auto body = R"(<html>
  5536. <head>
  5537. </head>
  5538. <body>
  5539. <a href="/dir/test.html">Test</a>
  5540. <a href="/hi">hi</a>
  5541. </body>
  5542. </html>
  5543. )";
  5544. EXPECT_EQ(body, res->body);
  5545. }
  5546. TEST_F(ServerTest, GetMethodDirTest) {
  5547. auto res = cli_.Get("/dir/test.html");
  5548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5549. EXPECT_EQ(StatusCode::OK_200, res->status);
  5550. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5551. EXPECT_EQ("test.html", res->body);
  5552. }
  5553. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5554. auto res = cli_.Get("/dir/../dir/test.html");
  5555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5556. EXPECT_EQ(StatusCode::OK_200, res->status);
  5557. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5558. EXPECT_EQ("test.html", res->body);
  5559. }
  5560. TEST_F(ServerTest, GetMethodInvalidPath) {
  5561. auto res = cli_.Get("/dir/../test.html");
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5564. }
  5565. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5566. auto res = cli_.Get("/../www/dir/test.html");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5571. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5574. }
  5575. TEST_F(ServerTest, GetMethodDirMountTest) {
  5576. auto res = cli_.Get("/mount/dir/test.html");
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::OK_200, res->status);
  5579. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5580. EXPECT_EQ("test.html", res->body);
  5581. }
  5582. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5583. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5587. EXPECT_EQ("test.html", res->body);
  5588. }
  5589. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5590. auto res = cli_.Get("/mount/dir/../test.html");
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5593. }
  5594. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5595. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5598. }
  5599. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5600. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5603. }
  5604. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5605. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5608. }
  5609. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5610. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5613. }
  5614. TEST_F(ServerTest, PostMethod303) {
  5615. auto res = cli_.Post("/1", "body", "text/plain");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5618. EXPECT_EQ("/2", res->get_header_value("Location"));
  5619. }
  5620. TEST_F(ServerTest, PostMethod303Redirect) {
  5621. cli_.set_follow_location(true);
  5622. auto res = cli_.Post("/1", "body", "text/plain");
  5623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5624. EXPECT_EQ(StatusCode::OK_200, res->status);
  5625. EXPECT_EQ("redirected.", res->body);
  5626. EXPECT_EQ("/2", res->location);
  5627. }
  5628. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5629. auto res = cli_.Get("/dir/test.abcde");
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::OK_200, res->status);
  5632. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5633. EXPECT_EQ("abcde", res->body);
  5634. }
  5635. TEST_F(ServerTest, StaticFileRange) {
  5636. auto res =
  5637. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5640. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5641. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5642. EXPECT_EQ(true, res->has_header("Content-Range"));
  5643. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5644. EXPECT_EQ(std::string("cd"), res->body);
  5645. }
  5646. TEST_F(ServerTest, StaticFileRanges) {
  5647. auto res = cli_.Get("/dir/test.abcde",
  5648. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5651. EXPECT_TRUE(
  5652. res->get_header_value("Content-Type")
  5653. .find(
  5654. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5655. 0);
  5656. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5657. }
  5658. TEST_F(ServerTest, StaticFileRangeHead) {
  5659. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5662. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5663. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5664. EXPECT_EQ(true, res->has_header("Content-Range"));
  5665. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5666. }
  5667. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5668. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5671. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5672. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5673. EXPECT_EQ(true, res->has_header("Content-Range"));
  5674. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5675. res->get_header_value("Content-Range"));
  5676. EXPECT_EQ("LAST\n", res->body);
  5677. }
  5678. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5679. auto res =
  5680. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5683. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5684. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5685. EXPECT_EQ(true, res->has_header("Content-Range"));
  5686. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5687. }
  5688. TEST_F(ServerTest, StaticFileBigFile) {
  5689. auto res = cli_.Get("/dir/1MB.txt");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. EXPECT_EQ(StatusCode::OK_200, res->status);
  5692. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5693. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5694. }
  5695. TEST_F(ServerTest, InvalidBaseDirMount) {
  5696. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5697. }
  5698. TEST_F(ServerTest, Binary) {
  5699. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5700. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5701. "application/octet-stream");
  5702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5703. ASSERT_EQ(StatusCode::OK_200, res->status);
  5704. ASSERT_EQ(4U, res->body.size());
  5705. res = cli_.Put("/binary", binary.data(), binary.size(),
  5706. "application/octet-stream");
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. ASSERT_EQ(StatusCode::OK_200, res->status);
  5709. ASSERT_EQ(4U, res->body.size());
  5710. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5711. "application/octet-stream");
  5712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5713. ASSERT_EQ(StatusCode::OK_200, res->status);
  5714. ASSERT_EQ(4U, res->body.size());
  5715. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5716. "application/octet-stream");
  5717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5718. ASSERT_EQ(StatusCode::OK_200, res->status);
  5719. ASSERT_EQ(4U, res->body.size());
  5720. }
  5721. TEST_F(ServerTest, BinaryString) {
  5722. auto binary = std::string("\x00\x01\x02\x03", 4);
  5723. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5725. ASSERT_EQ(StatusCode::OK_200, res->status);
  5726. ASSERT_EQ(4U, res->body.size());
  5727. res = cli_.Put("/binary", binary, "application/octet-stream");
  5728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5729. ASSERT_EQ(StatusCode::OK_200, res->status);
  5730. ASSERT_EQ(4U, res->body.size());
  5731. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. ASSERT_EQ(StatusCode::OK_200, res->status);
  5734. ASSERT_EQ(4U, res->body.size());
  5735. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. ASSERT_EQ(StatusCode::OK_200, res->status);
  5738. ASSERT_EQ(4U, res->body.size());
  5739. }
  5740. TEST_F(ServerTest, EmptyRequest) {
  5741. auto res = cli_.Get("");
  5742. ASSERT_TRUE(!res);
  5743. EXPECT_EQ(Error::Connection, res.error());
  5744. }
  5745. TEST_F(ServerTest, LongRequest) {
  5746. std::string request;
  5747. for (size_t i = 0; i < 545; i++) {
  5748. request += "/TooLongRequest";
  5749. }
  5750. request += "OK";
  5751. auto res = cli_.Get(request.c_str());
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5754. }
  5755. TEST_F(ServerTest, TooLongRequest) {
  5756. std::string request;
  5757. for (size_t i = 0; i < 546; i++) {
  5758. request += "/TooLongRequest";
  5759. }
  5760. request += "_NG";
  5761. auto start = std::chrono::high_resolution_clock::now();
  5762. cli_.set_keep_alive(true);
  5763. auto res = cli_.Get(request.c_str());
  5764. auto end = std::chrono::high_resolution_clock::now();
  5765. auto elapsed =
  5766. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5767. .count();
  5768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5769. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5770. EXPECT_LE(elapsed, 1000);
  5771. EXPECT_EQ("close", res->get_header_value("Connection"));
  5772. EXPECT_FALSE(cli_.is_socket_open());
  5773. }
  5774. TEST_F(ServerTest, AlmostTooLongRequest) {
  5775. // test for #2046 - URI length check shouldn't include other content on req
  5776. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5777. // leading /, space, HTTP/1.1)
  5778. std::string request =
  5779. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5780. auto res = cli_.Get(request.c_str());
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5783. }
  5784. TEST_F(ServerTest, LongHeader) {
  5785. Request req;
  5786. req.method = "GET";
  5787. req.path = "/hi";
  5788. std::string host_and_port;
  5789. host_and_port += HOST;
  5790. host_and_port += ":";
  5791. host_and_port += std::to_string(PORT);
  5792. req.headers.emplace("Host", host_and_port.c_str());
  5793. req.headers.emplace("Accept", "*/*");
  5794. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5795. req.headers.emplace(
  5796. "Header-Name",
  5797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5825. "@@@@@@@@@@@@@@@@");
  5826. auto res = std::make_shared<Response>();
  5827. auto error = Error::Success;
  5828. auto ret = cli_.send(req, *res, error);
  5829. ASSERT_TRUE(ret);
  5830. EXPECT_EQ(StatusCode::OK_200, res->status);
  5831. }
  5832. TEST_F(ServerTest, LongQueryValue) {
  5833. auto start = std::chrono::high_resolution_clock::now();
  5834. cli_.set_keep_alive(true);
  5835. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5836. auto end = std::chrono::high_resolution_clock::now();
  5837. auto elapsed =
  5838. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5839. .count();
  5840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5841. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5842. EXPECT_LE(elapsed, 1000);
  5843. EXPECT_EQ("close", res->get_header_value("Connection"));
  5844. EXPECT_FALSE(cli_.is_socket_open());
  5845. }
  5846. TEST_F(ServerTest, TooLongQueryValue) {
  5847. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5848. ASSERT_FALSE(res);
  5849. EXPECT_EQ(Error::Read, res.error());
  5850. }
  5851. TEST_F(ServerTest, TooLongHeader) {
  5852. Request req;
  5853. req.method = "GET";
  5854. req.path = "/hi";
  5855. std::string host_and_port;
  5856. host_and_port += HOST;
  5857. host_and_port += ":";
  5858. host_and_port += std::to_string(PORT);
  5859. req.headers.emplace("Host", host_and_port.c_str());
  5860. req.headers.emplace("Accept", "*/*");
  5861. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5862. req.headers.emplace(
  5863. "Header-Name",
  5864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5888. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5889. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5890. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5892. "@@@@@@@@@@@@@@@@@");
  5893. auto res = std::make_shared<Response>();
  5894. auto error = Error::Success;
  5895. auto ret = cli_.send(req, *res, error);
  5896. ASSERT_TRUE(ret);
  5897. EXPECT_EQ(StatusCode::OK_200, res->status);
  5898. }
  5899. TEST_F(ServerTest, HeaderCountAtLimit) {
  5900. // Test with headers just under the 100 limit
  5901. httplib::Headers headers;
  5902. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5903. // This should keep us just under the 100 header limit
  5904. for (int i = 0; i < 95; i++) {
  5905. std::string name = "X-Test-Header-" + std::to_string(i);
  5906. std::string value = "value" + std::to_string(i);
  5907. headers.emplace(name, value);
  5908. }
  5909. // This should work fine as we're under the limit
  5910. auto res = cli_.Get("/hi", headers);
  5911. EXPECT_TRUE(res);
  5912. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5913. }
  5914. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5915. // Test with many headers to exceed the 100 limit
  5916. httplib::Headers headers;
  5917. // Add 150 headers to definitely exceed the 100 limit
  5918. for (int i = 0; i < 150; i++) {
  5919. std::string name = "X-Test-Header-" + std::to_string(i);
  5920. std::string value = "value" + std::to_string(i);
  5921. headers.emplace(name, value);
  5922. }
  5923. // This should fail due to exceeding header count limit
  5924. cli_.set_keep_alive(true);
  5925. auto res = cli_.Get("/hi", headers);
  5926. // The server should respond with 400 Bad Request
  5927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5928. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5929. EXPECT_EQ("close", res->get_header_value("Connection"));
  5930. EXPECT_FALSE(cli_.is_socket_open());
  5931. }
  5932. TEST_F(ServerTest, PercentEncoding) {
  5933. auto res = cli_.Get("/e%6edwith%");
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. EXPECT_EQ(StatusCode::OK_200, res->status);
  5936. }
  5937. TEST_F(ServerTest, PercentEncodingUnicode) {
  5938. auto res = cli_.Get("/e%u006edwith%");
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. EXPECT_EQ(StatusCode::OK_200, res->status);
  5941. }
  5942. TEST_F(ServerTest, InvalidPercentEncoding) {
  5943. auto res = cli_.Get("/%endwith%");
  5944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5945. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5946. }
  5947. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5948. auto res = cli_.Get("/%uendwith%");
  5949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5950. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5951. }
  5952. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5953. auto res = cli_.Get("/hello?aaa=bbb%");
  5954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5955. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5956. }
  5957. TEST_F(ServerTest, PlusSignEncoding) {
  5958. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::OK_200, res->status);
  5961. EXPECT_EQ("a +b", res->body);
  5962. }
  5963. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5964. // This test simulates a potential DoS attack using many headers
  5965. // to verify our security fix prevents memory exhaustion
  5966. httplib::Headers attack_headers;
  5967. // Attempt to add many headers like an attacker would (200 headers to far
  5968. // exceed limit)
  5969. for (int i = 0; i < 200; i++) {
  5970. std::string name = "X-Attack-Header-" + std::to_string(i);
  5971. std::string value = "attack_payload_" + std::to_string(i);
  5972. attack_headers.emplace(name, value);
  5973. }
  5974. // Try to POST with excessive headers
  5975. cli_.set_keep_alive(true);
  5976. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5977. // Should either fail or return 400 Bad Request due to security limit
  5978. if (res) {
  5979. // If we get a response, it should be 400 Bad Request
  5980. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5981. EXPECT_EQ("close", res->get_header_value("Connection"));
  5982. }
  5983. EXPECT_FALSE(cli_.is_socket_open());
  5984. }
  5985. TEST_F(ServerTest, MultipartFormData) {
  5986. UploadFormDataItems items = {
  5987. {"text1", "text default", "", ""},
  5988. {"text2", "aωb", "", ""},
  5989. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5990. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5991. {"file3", "", "", "application/octet-stream"},
  5992. {"file4", "", "", " application/json tmp-string "}};
  5993. auto res = cli_.Post("/multipart", items);
  5994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5995. EXPECT_EQ(StatusCode::OK_200, res->status);
  5996. }
  5997. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5998. UploadFormDataItems items = {
  5999. {"text", "default text", "", ""},
  6000. {"multi_text1", "aaaaa", "", ""},
  6001. {"multi_text1", "bbbbb", "", ""},
  6002. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6003. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6004. "application/json"},
  6005. };
  6006. auto res = cli_.Post("/multipart/multi_file_values", items);
  6007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6008. EXPECT_EQ(StatusCode::OK_200, res->status);
  6009. }
  6010. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6011. auto res = cli_.Get("/hi");
  6012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6015. EXPECT_EQ("Hello World!", res->body);
  6016. }
  6017. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6018. Request req;
  6019. req.method = "POST";
  6020. req.path = "/chunked";
  6021. std::string host_and_port;
  6022. host_and_port += HOST;
  6023. host_and_port += ":";
  6024. host_and_port += std::to_string(PORT);
  6025. req.headers.emplace("Host", host_and_port.c_str());
  6026. req.headers.emplace("Accept", "*/*");
  6027. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6028. req.headers.emplace("Content-Type", "text/plain");
  6029. req.headers.emplace("Content-Length", "0");
  6030. req.headers.emplace(
  6031. "Transfer-Encoding",
  6032. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6033. // Client does not chunk, so make a chunked body manually.
  6034. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6035. auto res = std::make_shared<Response>();
  6036. auto error = Error::Success;
  6037. auto ret = cli_.send(req, *res, error);
  6038. ASSERT_TRUE(ret);
  6039. EXPECT_EQ(StatusCode::OK_200, res->status);
  6040. }
  6041. template <typename ClientT>
  6042. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6043. int expected_status) {
  6044. Request req;
  6045. req.method = "POST";
  6046. req.path = "/chunked";
  6047. std::string host_and_port;
  6048. host_and_port += HOST;
  6049. host_and_port += ":";
  6050. host_and_port += std::to_string(PORT);
  6051. req.headers.emplace("Host", host_and_port.c_str());
  6052. req.headers.emplace("Content-Length", "0");
  6053. req.headers.emplace("Transfer-Encoding", "chunked");
  6054. req.body = body;
  6055. auto res = std::make_shared<Response>();
  6056. auto error = Error::Success;
  6057. ASSERT_TRUE(cli.send(req, *res, error));
  6058. EXPECT_EQ(expected_status, res->status);
  6059. }
  6060. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6061. // rather than treat them as valid lengths.
  6062. template <typename ClientT>
  6063. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6064. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6065. }
  6066. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6067. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6068. }
  6069. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6070. expect_chunked_body_rejected(
  6071. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6072. }
  6073. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6074. // chunk-size line carries no CR, LF or other control character ahead of its
  6075. // terminator. Such a line must be refused rather than read as extension text.
  6076. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6077. expect_chunked_body_rejected(
  6078. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6079. }
  6080. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6081. expect_chunked_body_rejected(
  6082. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6083. }
  6084. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6085. expect_chunked_body_rejected(
  6086. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6087. }
  6088. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6089. // The literal stays split: a hex escape consumes every hex digit that
  6090. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6091. expect_chunked_body_rejected(
  6092. cli_, "4;a\x01"
  6093. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6094. }
  6095. TEST_F(ServerTest, AcceptsChunkExtension) {
  6096. expect_chunked_body_status(cli_,
  6097. "4;name=value\r\ndech\r\n"
  6098. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6099. "0;last\r\n\r\n",
  6100. StatusCode::OK_200);
  6101. }
  6102. TEST_F(ServerTest, GetStreamed2) {
  6103. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6106. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6107. EXPECT_EQ(true, res->has_header("Content-Range"));
  6108. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6109. EXPECT_EQ(std::string("ab"), res->body);
  6110. }
  6111. TEST_F(ServerTest, GetStreamed) {
  6112. auto res = cli_.Get("/streamed");
  6113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6114. EXPECT_EQ(StatusCode::OK_200, res->status);
  6115. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6116. EXPECT_EQ(std::string("aaabbb"), res->body);
  6117. }
  6118. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6119. auto res = cli_.Get("/streamed-without-length",
  6120. Headers{make_range_header({{0, -1}})});
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::OK_200, res->status);
  6123. EXPECT_EQ(false, res->has_header("Content-Length"));
  6124. EXPECT_EQ(false, res->has_header("Content-Range"));
  6125. EXPECT_EQ(std::string("abcdefg"), res->body);
  6126. }
  6127. TEST_F(ServerTest, GetStreamedWithRange1) {
  6128. auto res =
  6129. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6131. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6132. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6133. EXPECT_EQ(true, res->has_header("Content-Range"));
  6134. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6135. EXPECT_EQ(std::string("def"), res->body);
  6136. }
  6137. TEST_F(ServerTest, GetStreamedWithRange2) {
  6138. auto res =
  6139. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6142. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6143. EXPECT_EQ(true, res->has_header("Content-Range"));
  6144. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6145. EXPECT_EQ(std::string("bcdefg"), res->body);
  6146. }
  6147. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6148. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6151. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6152. EXPECT_EQ(true, res->has_header("Content-Range"));
  6153. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6154. EXPECT_EQ(std::string("efg"), res->body);
  6155. }
  6156. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6157. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6158. // the entire representation.
  6159. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6160. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6162. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6163. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6164. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6165. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6166. }
  6167. }
  6168. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6169. auto res =
  6170. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6172. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6173. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6174. EXPECT_EQ(false, res->has_header("Content-Range"));
  6175. EXPECT_EQ(0U, res->body.size());
  6176. }
  6177. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6178. // Only a 206 is served as a partial representation. Under any other status
  6179. // `apply_ranges()` reported the full content length, so the body must match
  6180. // that header, and the content provider must never be asked for an offset
  6181. // outside the representation.
  6182. auto check = [&](int status, const char *range) {
  6183. auto path =
  6184. std::string("/streamed-with-range?status=") + std::to_string(status);
  6185. auto ctx = path + " Range: " + range;
  6186. auto res = cli_.Get(path, Headers{{"Range", range}});
  6187. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6188. EXPECT_EQ(status, res->status) << ctx;
  6189. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6190. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6191. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6192. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6193. };
  6194. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6195. check(403, "bytes=3-5");
  6196. // The offset is far past the representation.
  6197. check(403, "bytes=100000-100200");
  6198. // `first_pos` is still -1 here, and the bounds asserts in
  6199. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6200. check(403, "bytes=-3");
  6201. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6202. // multipart branch would have written one that is empty.
  6203. check(403, "bytes=1-2, 4-5");
  6204. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6205. // covers the whole representation.
  6206. check(200, "bytes=3-5");
  6207. check(200, "bytes=1-2, 4-5");
  6208. }
  6209. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6210. auto res =
  6211. cli_.Get("/streamed-with-range",
  6212. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6213. "92233720368547758079223372036854775807"}});
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6216. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6217. EXPECT_EQ(false, res->has_header("Content-Range"));
  6218. EXPECT_EQ(0U, res->body.size());
  6219. }
  6220. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6221. auto res = cli_.Get(
  6222. "/with-range",
  6223. Headers{{"Range",
  6224. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6225. {"Accept-Encoding", ""}});
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6228. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6229. EXPECT_EQ(true, res->has_header("Content-Range"));
  6230. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6231. EXPECT_EQ(std::string("abcdefg"), res->body);
  6232. }
  6233. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6234. auto res = cli_.Get("/with-range", Headers{
  6235. {"Range", "bytes=0-"},
  6236. {"Accept-Encoding", ""},
  6237. });
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6240. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6241. EXPECT_EQ(true, res->has_header("Content-Range"));
  6242. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6243. EXPECT_EQ(std::string("abcdefg"), res->body);
  6244. }
  6245. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6246. auto res = cli_.Get("/streamed-with-range",
  6247. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6250. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6251. EXPECT_EQ(false, res->has_header("Content-Range"));
  6252. EXPECT_EQ(267U, res->body.size());
  6253. // Check that both range contents are present
  6254. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6255. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6256. // Check that Content-Range headers are present for both ranges
  6257. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6258. std::string::npos);
  6259. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6260. std::string::npos);
  6261. }
  6262. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6263. Ranges ranges;
  6264. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6265. ranges.emplace_back(0, -1);
  6266. }
  6267. auto res = cli_.Get("/streamed-with-range?error",
  6268. Headers{{make_range_header(ranges)}});
  6269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6270. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6271. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6272. EXPECT_EQ(false, res->has_header("Content-Range"));
  6273. EXPECT_EQ(0U, res->body.size());
  6274. }
  6275. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6276. auto res = cli_.Get("/streamed-with-range",
  6277. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6280. EXPECT_EQ(5U, res->body.size());
  6281. // Check that overlapping ranges are coalesced into a single range
  6282. EXPECT_EQ("bcdef", res->body);
  6283. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6284. // Should be single range, not multipart
  6285. EXPECT_TRUE(res->has_header("Content-Range"));
  6286. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6287. }
  6288. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6289. auto res = cli_.Get("/streamed-with-range",
  6290. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6293. EXPECT_EQ(268U, res->body.size());
  6294. // Check that both range contents are present
  6295. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6296. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6297. // Check that Content-Range headers are present for both ranges
  6298. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6299. std::string::npos);
  6300. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6301. std::string::npos);
  6302. }
  6303. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6304. auto res = cli_.Get("/streamed-with-range",
  6305. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6307. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6308. EXPECT_EQ(269U, res->body.size());
  6309. // Check that both duplicate range contents are present
  6310. size_t first_abc = res->body.find("abc\r\n");
  6311. EXPECT_TRUE(first_abc != std::string::npos);
  6312. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6313. EXPECT_TRUE(second_abc != std::string::npos);
  6314. // Check that Content-Range headers are present for both ranges
  6315. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6316. EXPECT_TRUE(first_range != std::string::npos);
  6317. size_t second_range =
  6318. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6319. EXPECT_TRUE(second_range != std::string::npos);
  6320. }
  6321. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6322. auto res =
  6323. cli_.Get("/streamed-with-range?error",
  6324. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6327. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6328. EXPECT_EQ(false, res->has_header("Content-Range"));
  6329. EXPECT_EQ(0U, res->body.size());
  6330. }
  6331. TEST_F(ServerTest, GetStreamedEndless) {
  6332. uint64_t offset = 0;
  6333. auto res = cli_.Get("/streamed-cancel",
  6334. [&](const char * /*data*/, uint64_t data_length) {
  6335. if (offset < 100) {
  6336. offset += data_length;
  6337. return true;
  6338. }
  6339. return false;
  6340. });
  6341. ASSERT_TRUE(!res);
  6342. EXPECT_EQ(Error::Canceled, res.error());
  6343. }
  6344. TEST_F(ServerTest, ClientStop) {
  6345. std::atomic_size_t count{4};
  6346. std::vector<std::thread> threads;
  6347. for (auto i = count.load(); i != 0; --i) {
  6348. threads.emplace_back([&]() {
  6349. auto res = cli_.Get("/streamed-cancel",
  6350. [&](const char *, uint64_t) { return true; });
  6351. --count;
  6352. ASSERT_TRUE(!res);
  6353. EXPECT_TRUE(res.error() == Error::Canceled ||
  6354. res.error() == Error::Read || res.error() == Error::Write);
  6355. });
  6356. }
  6357. std::this_thread::sleep_for(std::chrono::seconds(2));
  6358. while (count != 0) {
  6359. cli_.stop();
  6360. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6361. }
  6362. for (auto &t : threads) {
  6363. t.join();
  6364. }
  6365. }
  6366. TEST_F(ServerTest, GetWithRange1) {
  6367. auto res = cli_.Get("/with-range", Headers{
  6368. make_range_header({{3, 5}}),
  6369. {"Accept-Encoding", ""},
  6370. });
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6373. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6374. EXPECT_EQ(true, res->has_header("Content-Range"));
  6375. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6376. EXPECT_EQ(std::string("def"), res->body);
  6377. }
  6378. TEST_F(ServerTest, GetWithRange2) {
  6379. auto res = cli_.Get("/with-range", Headers{
  6380. make_range_header({{1, -1}}),
  6381. {"Accept-Encoding", ""},
  6382. });
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6385. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6386. EXPECT_EQ(true, res->has_header("Content-Range"));
  6387. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6388. EXPECT_EQ(std::string("bcdefg"), res->body);
  6389. }
  6390. TEST_F(ServerTest, GetWithRange3) {
  6391. auto res = cli_.Get("/with-range", Headers{
  6392. make_range_header({{0, 0}}),
  6393. {"Accept-Encoding", ""},
  6394. });
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6397. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6398. EXPECT_EQ(true, res->has_header("Content-Range"));
  6399. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6400. EXPECT_EQ(std::string("a"), res->body);
  6401. }
  6402. TEST_F(ServerTest, GetWithRange4) {
  6403. auto res = cli_.Get("/with-range", Headers{
  6404. make_range_header({{-1, 2}}),
  6405. {"Accept-Encoding", ""},
  6406. });
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6409. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6410. EXPECT_EQ(true, res->has_header("Content-Range"));
  6411. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6412. EXPECT_EQ(std::string("fg"), res->body);
  6413. }
  6414. TEST_F(ServerTest, GetWithRange5) {
  6415. auto res = cli_.Get("/with-range", Headers{
  6416. make_range_header({{0, 5}}),
  6417. {"Accept-Encoding", ""},
  6418. });
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6422. EXPECT_EQ(true, res->has_header("Content-Range"));
  6423. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6424. EXPECT_EQ(std::string("abcdef"), res->body);
  6425. }
  6426. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6427. auto res =
  6428. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6431. }
  6432. TEST_F(ServerTest, GetWithRangeMultipart) {
  6433. auto res =
  6434. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6437. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6438. EXPECT_EQ(false, res->has_header("Content-Range"));
  6439. EXPECT_EQ(267U, res->body.size());
  6440. }
  6441. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6442. auto res = cli_.Get("/with-range",
  6443. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6445. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6446. }
  6447. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6448. auto res = cli_.Get("/with-range-customized-response",
  6449. Headers{{make_range_header({{1, 2}})}});
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6452. EXPECT_EQ(true, res->has_header("Content-Length"));
  6453. EXPECT_EQ(false, res->has_header("Content-Range"));
  6454. EXPECT_EQ(JSON_DATA, res->body);
  6455. }
  6456. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6457. auto res = cli_.Get("/with-range-customized-response",
  6458. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6460. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6461. EXPECT_EQ(true, res->has_header("Content-Length"));
  6462. EXPECT_EQ(false, res->has_header("Content-Range"));
  6463. EXPECT_EQ(JSON_DATA, res->body);
  6464. }
  6465. TEST_F(ServerTest, Issue1772) {
  6466. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6469. }
  6470. TEST_F(ServerTest, Issue609) {
  6471. auto res = cli_.Delete("/issue609");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ(std::string("ok"), res->body);
  6475. }
  6476. TEST_F(ServerTest, GetStreamedChunked) {
  6477. auto res = cli_.Get("/streamed-chunked");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. EXPECT_EQ(std::string("123456789"), res->body);
  6481. }
  6482. TEST_F(ServerTest, GetStreamedChunked2) {
  6483. auto res = cli_.Get("/streamed-chunked2");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_EQ(StatusCode::OK_200, res->status);
  6486. EXPECT_EQ(std::string("123456789"), res->body);
  6487. }
  6488. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6489. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ(std::string("123456789"), res->body);
  6493. EXPECT_TRUE(res->has_header("Trailer"));
  6494. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6495. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6496. // Trailers are now stored separately from headers (security fix)
  6497. EXPECT_EQ(2U, res->trailers.size());
  6498. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6499. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6500. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6501. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6502. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6503. // Verify trailers are NOT in headers (security verification)
  6504. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6505. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6506. }
  6507. TEST_F(ServerTest, LargeChunkedPost) {
  6508. Request req;
  6509. req.method = "POST";
  6510. req.path = "/large-chunked";
  6511. std::string host_and_port;
  6512. host_and_port += HOST;
  6513. host_and_port += ":";
  6514. host_and_port += std::to_string(PORT);
  6515. req.headers.emplace("Host", host_and_port.c_str());
  6516. req.headers.emplace("Accept", "*/*");
  6517. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6518. req.headers.emplace("Content-Type", "text/plain");
  6519. req.headers.emplace("Content-Length", "0");
  6520. req.headers.emplace("Transfer-Encoding", "chunked");
  6521. std::string long_string(30 * 1024u, 'a');
  6522. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6523. // Attempt to make a large enough post to exceed OS buffers, to test that
  6524. // the server handles short reads if the full chunk data isn't available.
  6525. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6526. auto res = std::make_shared<Response>();
  6527. auto error = Error::Success;
  6528. auto ret = cli_.send(req, *res, error);
  6529. ASSERT_TRUE(ret);
  6530. EXPECT_EQ(StatusCode::OK_200, res->status);
  6531. }
  6532. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6533. auto res = cli_.Get("/remote_addr");
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::OK_200, res->status);
  6536. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6537. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6538. }
  6539. TEST_F(ServerTest, GetMethodLocalAddr) {
  6540. auto res = cli_.Get("/local_addr");
  6541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6542. EXPECT_EQ(StatusCode::OK_200, res->status);
  6543. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6544. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6545. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6546. }
  6547. TEST_F(ServerTest, HTTPResponseSplitting) {
  6548. auto res = cli_.Get("/http_response_splitting");
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. EXPECT_EQ(StatusCode::OK_200, res->status);
  6551. }
  6552. TEST_F(ServerTest, SlowRequest) {
  6553. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6554. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6555. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6556. }
  6557. #if 0
  6558. TEST_F(ServerTest, SlowPost) {
  6559. char buffer[64 * 1024];
  6560. memset(buffer, 0x42, sizeof(buffer));
  6561. auto res = cli_.Post(
  6562. "/slowpost", 64 * 1024 * 1024,
  6563. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6564. auto ret = sink.write(buffer, sizeof(buffer));
  6565. EXPECT_TRUE(ret);
  6566. return true;
  6567. },
  6568. "text/plain");
  6569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6570. EXPECT_EQ(StatusCode::OK_200, res->status);
  6571. }
  6572. TEST_F(ServerTest, SlowPostFail) {
  6573. char buffer[64 * 1024];
  6574. memset(buffer, 0x42, sizeof(buffer));
  6575. cli_.set_write_timeout(std::chrono::seconds(0));
  6576. auto res = cli_.Post(
  6577. "/slowpost", 64 * 1024 * 1024,
  6578. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6579. sink.write(buffer, sizeof(buffer));
  6580. return true;
  6581. },
  6582. "text/plain");
  6583. ASSERT_TRUE(!res);
  6584. EXPECT_EQ(Error::Write, res.error());
  6585. }
  6586. #endif
  6587. TEST_F(ServerTest, Put) {
  6588. auto res = cli_.Put("/put", "PUT", "text/plain");
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::OK_200, res->status);
  6591. EXPECT_EQ("PUT", res->body);
  6592. }
  6593. TEST_F(ServerTest, PutWithContentProvider) {
  6594. auto res = cli_.Put(
  6595. "/put", 3,
  6596. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6597. sink.os << "PUT";
  6598. return true;
  6599. },
  6600. "text/plain");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. EXPECT_EQ(StatusCode::OK_200, res->status);
  6603. EXPECT_EQ("PUT", res->body);
  6604. }
  6605. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6606. auto res = cli_.Post(
  6607. "/post", 42,
  6608. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6609. return false;
  6610. },
  6611. "text/plain");
  6612. ASSERT_TRUE(!res);
  6613. EXPECT_EQ(Error::Canceled, res.error());
  6614. }
  6615. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6616. auto res = cli_.Put(
  6617. "/put",
  6618. [](size_t /*offset*/, DataSink &sink) {
  6619. sink.os << "PUT";
  6620. sink.done();
  6621. return true;
  6622. },
  6623. "text/plain");
  6624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6625. EXPECT_EQ(StatusCode::OK_200, res->status);
  6626. EXPECT_EQ("PUT", res->body);
  6627. }
  6628. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6629. auto res = cli_.Post(
  6630. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6631. "text/plain");
  6632. ASSERT_TRUE(!res);
  6633. EXPECT_EQ(Error::Canceled, res.error());
  6634. }
  6635. TEST_F(ServerTest, PostLoopBack) {
  6636. std::string body;
  6637. auto res = cli_.Post(
  6638. "/post-loopback", 9,
  6639. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6640. EXPECT_EQ(9u, length);
  6641. sink.write("123", 3);
  6642. sink.write("456", 3);
  6643. sink.write("789", 3);
  6644. return true;
  6645. },
  6646. "text/plain",
  6647. [&body](const char *data, size_t data_length) {
  6648. body.append(data, data_length);
  6649. return true;
  6650. });
  6651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6652. EXPECT_EQ(StatusCode::OK_200, res->status);
  6653. EXPECT_EQ("123456789", body);
  6654. }
  6655. TEST_F(ServerTest, PutLoopBack) {
  6656. std::string body;
  6657. auto res = cli_.Put(
  6658. "/put-loopback", 9,
  6659. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6660. EXPECT_EQ(9u, length);
  6661. sink.write("123", 3);
  6662. sink.write("456", 3);
  6663. sink.write("789", 3);
  6664. return true;
  6665. },
  6666. "text/plain",
  6667. [&body](const char *data, size_t data_length) {
  6668. body.append(data, data_length);
  6669. return true;
  6670. });
  6671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6672. EXPECT_EQ(StatusCode::OK_200, res->status);
  6673. EXPECT_EQ("123456789", body);
  6674. }
  6675. TEST_F(ServerTest, PatchLoopBack) {
  6676. std::string body;
  6677. auto res = cli_.Patch(
  6678. "/patch-loopback", 9,
  6679. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6680. EXPECT_EQ(9u, length);
  6681. sink.write("123", 3);
  6682. sink.write("456", 3);
  6683. sink.write("789", 3);
  6684. return true;
  6685. },
  6686. "text/plain",
  6687. [&body](const char *data, size_t data_length) {
  6688. body.append(data, data_length);
  6689. return true;
  6690. });
  6691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6692. EXPECT_EQ(StatusCode::OK_200, res->status);
  6693. EXPECT_EQ("123456789", body);
  6694. }
  6695. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6696. std::string body;
  6697. auto res = cli_.Post(
  6698. "/post-loopback",
  6699. [](size_t /*offset*/, DataSink &sink) {
  6700. sink.write("123", 3);
  6701. sink.write("456", 3);
  6702. sink.write("789", 3);
  6703. sink.done();
  6704. return true;
  6705. },
  6706. "text/plain",
  6707. [&body](const char *data, size_t data_length) {
  6708. body.append(data, data_length);
  6709. return true;
  6710. });
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. EXPECT_EQ(StatusCode::OK_200, res->status);
  6713. EXPECT_EQ("123456789", body);
  6714. }
  6715. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6716. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6717. cli_.set_compress(true);
  6718. auto res = cli_.Put(
  6719. "/put", 3,
  6720. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6721. sink.os << "PUT";
  6722. return true;
  6723. },
  6724. "text/plain");
  6725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6726. EXPECT_EQ(StatusCode::OK_200, res->status);
  6727. EXPECT_EQ("PUT", res->body);
  6728. }
  6729. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6730. cli_.set_compress(true);
  6731. auto res = cli_.Post(
  6732. "/post", 42,
  6733. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6734. return false;
  6735. },
  6736. "text/plain");
  6737. ASSERT_TRUE(!res);
  6738. EXPECT_EQ(Error::Canceled, res.error());
  6739. }
  6740. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6741. cli_.set_compress(true);
  6742. auto res = cli_.Put(
  6743. "/put",
  6744. [](size_t /*offset*/, DataSink &sink) {
  6745. sink.os << "PUT";
  6746. sink.done();
  6747. return true;
  6748. },
  6749. "text/plain");
  6750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6751. EXPECT_EQ(StatusCode::OK_200, res->status);
  6752. EXPECT_EQ("PUT", res->body);
  6753. }
  6754. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6755. cli_.set_compress(true);
  6756. auto res = cli_.Post(
  6757. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6758. "text/plain");
  6759. ASSERT_TRUE(!res);
  6760. EXPECT_EQ(Error::Canceled, res.error());
  6761. }
  6762. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ(LARGE_DATA, res->body);
  6768. }
  6769. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6770. #ifdef CPPHTTPLIB_SSL_ENABLED
  6771. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6772. Client cli(s.c_str());
  6773. cli.enable_server_certificate_verification(false);
  6774. #else
  6775. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6776. Client cli(s.c_str());
  6777. #endif
  6778. cli.set_compress(true);
  6779. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::OK_200, res->status);
  6782. EXPECT_EQ(LARGE_DATA, res->body);
  6783. // The compressed size should be less than a 10th of the original. May vary
  6784. // depending on the zlib library.
  6785. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6786. static_cast<uint64_t>(10 * 1024 * 1024));
  6787. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6788. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6789. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6790. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6791. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6792. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6793. #endif
  6794. }
  6795. TEST_F(ServerTest, PutContentWithDeflate) {
  6796. cli_.set_compress(false);
  6797. Headers headers;
  6798. headers.emplace("Content-Encoding", "deflate");
  6799. // PUT in deflate format:
  6800. auto res = cli_.Put("/put", headers,
  6801. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6803. EXPECT_EQ(StatusCode::OK_200, res->status);
  6804. EXPECT_EQ("PUT", res->body);
  6805. }
  6806. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6807. Headers headers;
  6808. headers.emplace("Accept-Encoding", "gzip, deflate");
  6809. auto res = cli_.Get("/streamed-chunked", headers);
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. EXPECT_EQ(StatusCode::OK_200, res->status);
  6812. EXPECT_EQ(std::string("123456789"), res->body);
  6813. }
  6814. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6815. Headers headers;
  6816. headers.emplace("Accept-Encoding", "gzip, deflate");
  6817. auto res = cli_.Get("/streamed-chunked2", headers);
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ(std::string("123456789"), res->body);
  6821. }
  6822. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6823. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. EXPECT_EQ(StatusCode::OK_200, res->status);
  6826. }
  6827. TEST(GzipDecompressor, ChunkedDecompression) {
  6828. std::string data;
  6829. for (size_t i = 0; i < 32 * 1024; ++i) {
  6830. data.push_back(static_cast<char>('a' + i % 26));
  6831. }
  6832. std::string compressed_data;
  6833. {
  6834. httplib::detail::gzip_compressor compressor;
  6835. bool result = compressor.compress(
  6836. data.data(), data.size(),
  6837. /*last=*/true,
  6838. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6839. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6840. compressed_data_size);
  6841. return true;
  6842. });
  6843. ASSERT_TRUE(result);
  6844. }
  6845. std::string decompressed_data;
  6846. {
  6847. httplib::detail::gzip_decompressor decompressor;
  6848. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6849. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6850. size_t chunk_size = 130;
  6851. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6852. chunk_begin += chunk_size) {
  6853. size_t current_chunk_size =
  6854. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6855. bool result = decompressor.decompress(
  6856. compressed_data.data() + chunk_begin, current_chunk_size,
  6857. [&](const char *decompressed_data_chunk,
  6858. size_t decompressed_data_chunk_size) {
  6859. decompressed_data.insert(decompressed_data.size(),
  6860. decompressed_data_chunk,
  6861. decompressed_data_chunk_size);
  6862. return true;
  6863. });
  6864. ASSERT_TRUE(result);
  6865. }
  6866. }
  6867. ASSERT_EQ(data, decompressed_data);
  6868. }
  6869. TEST(GzipDecompressor, DeflateDecompression) {
  6870. std::string original_text = "Raw deflate without gzip";
  6871. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6872. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6873. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6874. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6875. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6876. std::string decompressed_data;
  6877. {
  6878. httplib::detail::gzip_decompressor decompressor;
  6879. bool result = decompressor.decompress(
  6880. compressed_data.data(), compressed_data.size(),
  6881. [&](const char *decompressed_data_chunk,
  6882. size_t decompressed_data_chunk_size) {
  6883. decompressed_data.insert(decompressed_data.size(),
  6884. decompressed_data_chunk,
  6885. decompressed_data_chunk_size);
  6886. return true;
  6887. });
  6888. ASSERT_TRUE(result);
  6889. }
  6890. ASSERT_EQ(original_text, decompressed_data);
  6891. }
  6892. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6893. std::string original_text = "Raw deflate without gzip";
  6894. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6895. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6896. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6897. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6898. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6899. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6900. std::string decompressed_data;
  6901. {
  6902. httplib::detail::gzip_decompressor decompressor;
  6903. bool result = decompressor.decompress(
  6904. compressed_data.data(), compressed_data.size(),
  6905. [&](const char *decompressed_data_chunk,
  6906. size_t decompressed_data_chunk_size) {
  6907. decompressed_data.insert(decompressed_data.size(),
  6908. decompressed_data_chunk,
  6909. decompressed_data_chunk_size);
  6910. return true;
  6911. });
  6912. ASSERT_TRUE(result);
  6913. }
  6914. ASSERT_EQ(original_text, decompressed_data);
  6915. }
  6916. #endif
  6917. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6918. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6919. Headers headers;
  6920. headers.emplace("Accept-Encoding", "br");
  6921. auto res = cli_.Get("/streamed-chunked", headers);
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ(std::string("123456789"), res->body);
  6925. }
  6926. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6927. Headers headers;
  6928. headers.emplace("Accept-Encoding", "br");
  6929. auto res = cli_.Get("/streamed-chunked2", headers);
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. EXPECT_EQ(std::string("123456789"), res->body);
  6933. }
  6934. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6935. cli_.set_compress(true);
  6936. auto res = cli_.Put(
  6937. "/put", 3,
  6938. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6939. sink.os << "PUT";
  6940. return true;
  6941. },
  6942. "text/plain");
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. EXPECT_EQ(StatusCode::OK_200, res->status);
  6945. EXPECT_EQ("PUT", res->body);
  6946. }
  6947. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6948. cli_.set_compress(true);
  6949. auto res = cli_.Put(
  6950. "/put",
  6951. [](size_t /*offset*/, DataSink &sink) {
  6952. sink.os << "PUT";
  6953. sink.done();
  6954. return true;
  6955. },
  6956. "text/plain");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. EXPECT_EQ("PUT", res->body);
  6960. }
  6961. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6962. cli_.set_compress(true);
  6963. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. EXPECT_EQ(LARGE_DATA, res->body);
  6967. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6968. }
  6969. #endif
  6970. TEST_F(ServerTest, Patch) {
  6971. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::OK_200, res->status);
  6974. EXPECT_EQ("PATCH", res->body);
  6975. }
  6976. TEST_F(ServerTest, Delete) {
  6977. auto res = cli_.Delete("/delete");
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. EXPECT_EQ(StatusCode::OK_200, res->status);
  6980. EXPECT_EQ("DELETE", res->body);
  6981. }
  6982. TEST_F(ServerTest, DeleteContentReceiver) {
  6983. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6985. EXPECT_EQ(StatusCode::OK_200, res->status);
  6986. EXPECT_EQ("content", res->body);
  6987. }
  6988. TEST_F(ServerTest, Options) {
  6989. auto res = cli_.Options("*");
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6993. EXPECT_TRUE(res->body.empty());
  6994. }
  6995. TEST_F(ServerTest, URL) {
  6996. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::OK_200, res->status);
  6999. }
  7000. TEST_F(ServerTest, ArrayParam) {
  7001. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. }
  7005. TEST_F(ServerTest, ArrayParamValues) {
  7006. auto res =
  7007. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7009. EXPECT_EQ(StatusCode::OK_200, res->status);
  7010. }
  7011. TEST_F(ServerTest, NoMultipleHeaders) {
  7012. Headers headers = {{"Content-Length", "5"}};
  7013. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7014. "text/plain");
  7015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. }
  7018. TEST_F(ServerTest, PostContentReceiver) {
  7019. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. ASSERT_EQ(StatusCode::OK_200, res->status);
  7022. ASSERT_EQ("content", res->body);
  7023. }
  7024. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7025. UploadFormDataItems items = {
  7026. {"text1", "text default", "", ""},
  7027. {"text2", "aωb", "", ""},
  7028. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7029. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7030. {"file3", "", "", "application/octet-stream"},
  7031. };
  7032. auto res = cli_.Post("/content_receiver", items);
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. }
  7036. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7037. UploadFormDataItems items = {
  7038. {"text1", "text default", "", ""},
  7039. {"text2", "aωb", "", ""},
  7040. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7041. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7042. {"file3", "", "", "application/octet-stream"},
  7043. };
  7044. auto boundary = std::string("+++++");
  7045. std::string body;
  7046. for (const auto &item : items) {
  7047. body += "--" + boundary + "\r\n";
  7048. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7049. if (!item.filename.empty()) {
  7050. body += "; filename=\"" + item.filename + "\"";
  7051. }
  7052. body += "\r\n";
  7053. if (!item.content_type.empty()) {
  7054. body += "Content-Type: " + item.content_type + "\r\n";
  7055. }
  7056. body += "\r\n";
  7057. body += item.content + "\r\n";
  7058. }
  7059. body += "--" + boundary + "--\r\n";
  7060. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7061. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. EXPECT_EQ(StatusCode::OK_200, res->status);
  7064. }
  7065. TEST(MultipartFormDataTest, FieldEscaping) {
  7066. Server svr;
  7067. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7068. const ContentReader &content_reader) {
  7069. ASSERT_TRUE(req.is_multipart_form_data());
  7070. std::vector<FormData> received;
  7071. content_reader(
  7072. [&](const FormData &file) {
  7073. received.push_back(file);
  7074. return true;
  7075. },
  7076. [&](const char *data, size_t data_length) {
  7077. received.back().content.append(data, data_length);
  7078. return true;
  7079. });
  7080. // '"', CR and LF in names and filenames are escaped following the
  7081. // WHATWG HTML standard, so each part still parses as a single part
  7082. // with no injected headers. Content types get CR/LF escaped too,
  7083. // while '"' (legal there, e.g. quoted charset) is preserved.
  7084. ASSERT_EQ(4U, received.size());
  7085. EXPECT_EQ("na%22me", received[0].name);
  7086. EXPECT_EQ("quoted name", received[0].content);
  7087. EXPECT_EQ("file", received[1].name);
  7088. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7089. received[1].filename);
  7090. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7091. EXPECT_EQ("injected", received[1].content);
  7092. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7093. EXPECT_EQ("my%22file.txt", received[2].filename);
  7094. EXPECT_EQ("cr lf name", received[2].content);
  7095. EXPECT_EQ("typed", received[3].name);
  7096. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7097. received[3].content_type);
  7098. EXPECT_EQ("typed content", received[3].content);
  7099. });
  7100. auto port = svr.bind_to_any_port("localhost");
  7101. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7102. auto se = detail::scope_exit([&] {
  7103. svr.stop();
  7104. t.join();
  7105. ASSERT_FALSE(svr.is_running());
  7106. });
  7107. svr.wait_until_ready();
  7108. Client cli("localhost", port);
  7109. UploadFormDataItems items = {
  7110. {"na\"me", "quoted name", "", ""},
  7111. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7112. "application/octet-stream"},
  7113. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7114. {"typed", "typed content", "",
  7115. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7116. };
  7117. auto res = cli.Post("/post", items);
  7118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7119. EXPECT_EQ(StatusCode::OK_200, res->status);
  7120. }
  7121. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7122. const UploadFormDataItems items = {
  7123. {"name1", "Content 1", "", ""},
  7124. {"name2", "Content 2", "file2.txt", "text/plain"},
  7125. };
  7126. Server svr;
  7127. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7128. const ContentReader &content_reader) {
  7129. ASSERT_TRUE(req.is_multipart_form_data());
  7130. std::vector<FormData> received;
  7131. content_reader(
  7132. [&](const FormData &file) {
  7133. received.push_back(file);
  7134. return true;
  7135. },
  7136. [&](const char *data, size_t data_length) {
  7137. received.back().content.append(data, data_length);
  7138. return true;
  7139. });
  7140. ASSERT_EQ(2U, received.size());
  7141. EXPECT_EQ("name1", received[0].name);
  7142. EXPECT_EQ("Content 1", received[0].content);
  7143. EXPECT_EQ("name2", received[1].name);
  7144. EXPECT_EQ("Content 2", received[1].content);
  7145. EXPECT_EQ("file2.txt", received[1].filename);
  7146. EXPECT_EQ("text/plain", received[1].content_type);
  7147. });
  7148. auto port = svr.bind_to_any_port("localhost");
  7149. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7150. auto se = detail::scope_exit([&] {
  7151. svr.stop();
  7152. t.join();
  7153. ASSERT_FALSE(svr.is_running());
  7154. });
  7155. svr.wait_until_ready();
  7156. Client cli("localhost", port);
  7157. // Whole-body serialization with a generated boundary
  7158. {
  7159. MultipartFormDataWriter writer;
  7160. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7161. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7162. writer.content_type());
  7163. auto body = writer.serialize(items);
  7164. EXPECT_EQ(body.size(), writer.content_length(items));
  7165. auto res = cli.Post("/post", body, writer.content_type());
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. EXPECT_EQ(StatusCode::OK_200, res->status);
  7168. }
  7169. // Per-part framing with a custom boundary via a content provider
  7170. {
  7171. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7172. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7173. MultipartFormDataWriter writer("custom-boundary_123");
  7174. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7175. std::string body;
  7176. for (const auto &item : items) {
  7177. body += writer.item_begin(item);
  7178. body += item.content;
  7179. body += MultipartFormDataWriter::item_end();
  7180. }
  7181. body += writer.finish();
  7182. EXPECT_EQ(body.size(), writer.content_length(items));
  7183. auto res = cli.Post(
  7184. "/post", body.size(),
  7185. [&](size_t offset, size_t length, DataSink &sink) {
  7186. sink.write(body.data() + offset, length);
  7187. return true;
  7188. },
  7189. writer.content_type());
  7190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7191. EXPECT_EQ(StatusCode::OK_200, res->status);
  7192. }
  7193. }
  7194. TEST_F(ServerTest, PostContentReceiverGzip) {
  7195. cli_.set_compress(true);
  7196. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. ASSERT_EQ(StatusCode::OK_200, res->status);
  7199. ASSERT_EQ("content", res->body);
  7200. }
  7201. TEST_F(ServerTest, PutContentReceiver) {
  7202. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. ASSERT_EQ(StatusCode::OK_200, res->status);
  7205. ASSERT_EQ("content", res->body);
  7206. }
  7207. TEST_F(ServerTest, PatchContentReceiver) {
  7208. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. ASSERT_EQ(StatusCode::OK_200, res->status);
  7211. ASSERT_EQ("content", res->body);
  7212. }
  7213. template <typename ClientType>
  7214. void TestWithHeadersAndContentReceiver(
  7215. ClientType &cli,
  7216. std::function<Result(ClientType &, const std::string &, const Headers &,
  7217. const std::string &, const std::string &,
  7218. ContentReceiver, DownloadProgress)>
  7219. request_func) {
  7220. Headers headers;
  7221. headers.emplace("X-Custom-Header", "test-value");
  7222. std::string received_body;
  7223. auto res = request_func(
  7224. cli, "/content_receiver", headers, "content", "application/json",
  7225. [&](const char *data, size_t data_length) {
  7226. received_body.append(data, data_length);
  7227. return true;
  7228. },
  7229. nullptr);
  7230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7231. EXPECT_EQ(StatusCode::OK_200, res->status);
  7232. EXPECT_EQ("content", received_body);
  7233. }
  7234. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7235. #ifdef CPPHTTPLIB_SSL_ENABLED
  7236. using ClientT = SSLClient;
  7237. #else
  7238. using ClientT = Client;
  7239. #endif
  7240. TestWithHeadersAndContentReceiver<ClientT>(
  7241. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7242. const std::string &body, const std::string &content_type,
  7243. ContentReceiver receiver, DownloadProgress progress) {
  7244. return cli.Post(path, headers, body, content_type, receiver, progress);
  7245. });
  7246. }
  7247. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7248. #ifdef CPPHTTPLIB_SSL_ENABLED
  7249. using ClientT = SSLClient;
  7250. #else
  7251. using ClientT = Client;
  7252. #endif
  7253. TestWithHeadersAndContentReceiver<ClientT>(
  7254. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7255. const std::string &body, const std::string &content_type,
  7256. ContentReceiver receiver, DownloadProgress progress) {
  7257. return cli.Put(path, headers, body, content_type, receiver, progress);
  7258. });
  7259. }
  7260. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7261. #ifdef CPPHTTPLIB_SSL_ENABLED
  7262. using ClientT = SSLClient;
  7263. #else
  7264. using ClientT = Client;
  7265. #endif
  7266. TestWithHeadersAndContentReceiver<ClientT>(
  7267. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7268. const std::string &body, const std::string &content_type,
  7269. ContentReceiver receiver, DownloadProgress progress) {
  7270. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7271. });
  7272. }
  7273. template <typename ClientType>
  7274. void TestWithHeadersAndContentReceiverWithProgress(
  7275. ClientType &cli,
  7276. std::function<Result(ClientType &, const std::string &, const Headers &,
  7277. const std::string &, const std::string &,
  7278. ContentReceiver, DownloadProgress)>
  7279. request_func) {
  7280. Headers headers;
  7281. headers.emplace("X-Test-Header", "progress-test");
  7282. std::string received_body;
  7283. auto progress_called = false;
  7284. auto res = request_func(
  7285. cli, "/content_receiver", headers, "content", "text/plain",
  7286. [&](const char *data, size_t data_length) {
  7287. received_body.append(data, data_length);
  7288. return true;
  7289. },
  7290. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7291. progress_called = true;
  7292. return true;
  7293. });
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::OK_200, res->status);
  7296. EXPECT_EQ("content", received_body);
  7297. EXPECT_TRUE(progress_called);
  7298. }
  7299. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7300. #ifdef CPPHTTPLIB_SSL_ENABLED
  7301. using ClientT = SSLClient;
  7302. #else
  7303. using ClientT = Client;
  7304. #endif
  7305. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7306. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7307. const std::string &body, const std::string &content_type,
  7308. ContentReceiver receiver, DownloadProgress progress) {
  7309. return cli.Post(path, headers, body, content_type, receiver, progress);
  7310. });
  7311. }
  7312. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7313. #ifdef CPPHTTPLIB_SSL_ENABLED
  7314. using ClientT = SSLClient;
  7315. #else
  7316. using ClientT = Client;
  7317. #endif
  7318. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7319. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7320. const std::string &body, const std::string &content_type,
  7321. ContentReceiver receiver, DownloadProgress progress) {
  7322. return cli.Put(path, headers, body, content_type, receiver, progress);
  7323. });
  7324. }
  7325. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7326. #ifdef CPPHTTPLIB_SSL_ENABLED
  7327. using ClientT = SSLClient;
  7328. #else
  7329. using ClientT = Client;
  7330. #endif
  7331. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7332. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7333. const std::string &body, const std::string &content_type,
  7334. ContentReceiver receiver, DownloadProgress progress) {
  7335. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7336. });
  7337. }
  7338. template <typename ClientType>
  7339. void TestWithHeadersAndContentReceiverError(
  7340. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7341. const Headers &, const std::string &,
  7342. const std::string &, ContentReceiver)>
  7343. request_func) {
  7344. Headers headers;
  7345. headers.emplace("X-Error-Test", "true");
  7346. std::string received_body;
  7347. auto receiver_failed = false;
  7348. auto res =
  7349. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7350. [&](const char *data, size_t data_length) {
  7351. received_body.append(data, data_length);
  7352. receiver_failed = true;
  7353. return false;
  7354. });
  7355. ASSERT_FALSE(res);
  7356. EXPECT_TRUE(receiver_failed);
  7357. }
  7358. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7359. #ifdef CPPHTTPLIB_SSL_ENABLED
  7360. using ClientT = SSLClient;
  7361. #else
  7362. using ClientT = Client;
  7363. #endif
  7364. TestWithHeadersAndContentReceiverError<ClientT>(
  7365. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7366. const std::string &body, const std::string &content_type,
  7367. ContentReceiver receiver) {
  7368. return cli.Post(path, headers, body, content_type, receiver);
  7369. });
  7370. }
  7371. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7372. #ifdef CPPHTTPLIB_SSL_ENABLED
  7373. using ClientT = SSLClient;
  7374. #else
  7375. using ClientT = Client;
  7376. #endif
  7377. TestWithHeadersAndContentReceiverError<ClientT>(
  7378. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7379. const std::string &body, const std::string &content_type,
  7380. ContentReceiver receiver) {
  7381. return cli.Put(path, headers, body, content_type, receiver);
  7382. });
  7383. }
  7384. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7385. #ifdef CPPHTTPLIB_SSL_ENABLED
  7386. using ClientT = SSLClient;
  7387. #else
  7388. using ClientT = Client;
  7389. #endif
  7390. TestWithHeadersAndContentReceiverError<ClientT>(
  7391. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7392. const std::string &body, const std::string &content_type,
  7393. ContentReceiver receiver) {
  7394. return cli.Patch(path, headers, body, content_type, receiver);
  7395. });
  7396. }
  7397. TEST_F(ServerTest, PostQueryStringAndBody) {
  7398. auto res =
  7399. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7401. ASSERT_EQ(StatusCode::OK_200, res->status);
  7402. }
  7403. TEST_F(ServerTest, HTTP2Magic) {
  7404. Request req;
  7405. req.method = "PRI";
  7406. req.path = "*";
  7407. req.body = "SM";
  7408. auto res = std::make_shared<Response>();
  7409. auto error = Error::Success;
  7410. auto ret = cli_.send(req, *res, error);
  7411. ASSERT_TRUE(ret);
  7412. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7413. }
  7414. TEST_F(ServerTest, KeepAlive) {
  7415. auto res = cli_.Get("/hi");
  7416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7417. EXPECT_EQ(StatusCode::OK_200, res->status);
  7418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7419. EXPECT_EQ("Hello World!", res->body);
  7420. res = cli_.Get("/hi");
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::OK_200, res->status);
  7423. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7424. EXPECT_EQ("Hello World!", res->body);
  7425. res = cli_.Get("/hi");
  7426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7427. EXPECT_EQ(StatusCode::OK_200, res->status);
  7428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7429. EXPECT_EQ("Hello World!", res->body);
  7430. res = cli_.Get("/not-exist");
  7431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7432. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7433. res = cli_.Post("/empty", "", "text/plain");
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. EXPECT_EQ(StatusCode::OK_200, res->status);
  7436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7437. EXPECT_EQ("empty", res->body);
  7438. EXPECT_EQ("close", res->get_header_value("Connection"));
  7439. res = cli_.Post(
  7440. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7441. "text/plain");
  7442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7443. EXPECT_EQ(StatusCode::OK_200, res->status);
  7444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7445. EXPECT_EQ("empty", res->body);
  7446. cli_.set_keep_alive(false);
  7447. res = cli_.Get("/last-request");
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. EXPECT_EQ("close", res->get_header_value("Connection"));
  7451. }
  7452. TEST_F(ServerTest, TooManyRedirect) {
  7453. cli_.set_follow_location(true);
  7454. auto res = cli_.Get("/redirect/0");
  7455. ASSERT_TRUE(!res);
  7456. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7457. }
  7458. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7459. Request req;
  7460. req.method = "FOOBAR";
  7461. req.path = "/hi";
  7462. cli_.set_keep_alive(true);
  7463. auto res = cli_.send(req);
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7466. EXPECT_EQ("close", res->get_header_value("Connection"));
  7467. EXPECT_FALSE(cli_.is_socket_open());
  7468. }
  7469. TEST_F(ServerTest, CustomRouteReadsBody) {
  7470. const std::string xml =
  7471. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7472. Request req;
  7473. req.method = "PROPFIND";
  7474. req.path = "/dav/dir";
  7475. req.set_header("Depth", "1");
  7476. req.body = xml;
  7477. auto res = cli_.send(req);
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7480. EXPECT_EQ(xml, res->body);
  7481. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7482. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7483. }
  7484. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7485. Request req;
  7486. req.method = "PROPFIND";
  7487. req.path = "/dav/42";
  7488. auto res = cli_.send(req);
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7491. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7492. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7493. }
  7494. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7495. Request req;
  7496. req.method = "PROPFIND";
  7497. req.path = "/dav-re/123";
  7498. auto res = cli_.send(req);
  7499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7500. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7501. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7502. }
  7503. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7504. Request req;
  7505. req.method = "MKCOL";
  7506. req.path = "/dav-mkcol";
  7507. auto res = cli_.send(req);
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(StatusCode::Created_201, res->status);
  7510. }
  7511. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7512. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7513. Request req;
  7514. req.method = "REPORT";
  7515. req.path = "/dav-report";
  7516. req.body = xml;
  7517. auto res = cli_.send(req);
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7520. EXPECT_EQ(xml, res->body);
  7521. }
  7522. // A content reader route must fire even when the request carries no body,
  7523. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7524. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7525. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7526. Request req;
  7527. req.method = "REPORT";
  7528. req.path = "/dav-report";
  7529. auto res = cli_.send(req);
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7532. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7533. }
  7534. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7535. Request req;
  7536. req.method = "PROPFIND";
  7537. req.path = "/not-dav";
  7538. auto res = cli_.send(req);
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7541. }
  7542. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7543. Request req;
  7544. req.method = "UNLOCK";
  7545. req.path = "/dav/dir";
  7546. cli_.set_keep_alive(true);
  7547. auto res = cli_.send(req);
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7550. EXPECT_EQ("close", res->get_header_value("Connection"));
  7551. EXPECT_FALSE(cli_.is_socket_open());
  7552. }
  7553. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7554. // The mount point serves this path, but only for GET and HEAD.
  7555. auto get_res = cli_.Get("/dir/index.html");
  7556. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7557. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7558. Request req;
  7559. req.method = "PROPFIND";
  7560. req.path = "/dir/index.html";
  7561. auto res = cli_.send(req);
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7564. }
  7565. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7566. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7567. cli_.set_keep_alive(true);
  7568. for (auto i = 0; i < 2; i++) {
  7569. Request req;
  7570. req.method = "PROPFIND";
  7571. req.path = "/dav/dir";
  7572. req.body = xml;
  7573. auto res = cli_.send(req);
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7576. EXPECT_EQ(xml, res->body);
  7577. EXPECT_TRUE(cli_.is_socket_open());
  7578. }
  7579. // A built-in method must still be served on the same connection.
  7580. cli_.set_keep_alive(false);
  7581. auto res = cli_.Get("/hi");
  7582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7583. EXPECT_EQ(StatusCode::OK_200, res->status);
  7584. EXPECT_EQ("close", res->get_header_value("Connection"));
  7585. }
  7586. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7587. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7588. Request req;
  7589. req.method = "PROPFIND";
  7590. req.path = "/dav/dir";
  7591. req.set_header("Expect", "100-continue");
  7592. req.body = xml;
  7593. auto res = cli_.send(req);
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7596. EXPECT_EQ(xml, res->body);
  7597. }
  7598. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7599. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7600. TEST_F(ServerTest, Gzip) {
  7601. Headers headers;
  7602. headers.emplace("Accept-Encoding", "gzip, deflate");
  7603. auto res = cli_.Get("/compress", headers);
  7604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7605. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7606. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7607. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7608. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7609. "7890123456789012345678901234567890",
  7610. res->body);
  7611. EXPECT_EQ(StatusCode::OK_200, res->status);
  7612. }
  7613. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7614. Headers headers;
  7615. headers.emplace("Accept-Encoding", "gzip, deflate");
  7616. auto res = cli_.Get("/compress-with-charset", headers);
  7617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7618. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7619. EXPECT_EQ("application/json; charset=utf-8",
  7620. res->get_header_value("Content-Type"));
  7621. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7622. "7890123456789012345678901234567890",
  7623. res->body);
  7624. EXPECT_EQ(StatusCode::OK_200, res->status);
  7625. }
  7626. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7627. Headers headers;
  7628. headers.emplace("Accept-Encoding", "");
  7629. auto res = cli_.Get("/compress", headers);
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7633. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7634. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7635. "7890123456789012345678901234567890",
  7636. res->body);
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. }
  7639. TEST_F(ServerTest, GzipWithContentReceiver) {
  7640. Headers headers;
  7641. headers.emplace("Accept-Encoding", "gzip, deflate");
  7642. std::string body;
  7643. auto res = cli_.Get("/compress", headers,
  7644. [&](const char *data, uint64_t data_length) {
  7645. EXPECT_EQ(100U, data_length);
  7646. body.append(data, data_length);
  7647. return true;
  7648. });
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7652. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7653. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7654. "7890123456789012345678901234567890",
  7655. body);
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. }
  7658. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7659. Headers headers;
  7660. headers.emplace("Accept-Encoding", "gzip, deflate");
  7661. cli_.set_decompress(false);
  7662. auto res = cli_.Get("/compress", headers);
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7666. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7667. EXPECT_EQ(33U, res->body.size());
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. }
  7670. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7671. Headers headers;
  7672. headers.emplace("Accept-Encoding", "");
  7673. std::string body;
  7674. auto res = cli_.Get("/compress", headers,
  7675. [&](const char *data, uint64_t data_length) {
  7676. EXPECT_EQ(100U, data_length);
  7677. body.append(data, data_length);
  7678. return true;
  7679. });
  7680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7681. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7682. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7683. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7684. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7685. "7890123456789012345678901234567890",
  7686. body);
  7687. EXPECT_EQ(StatusCode::OK_200, res->status);
  7688. }
  7689. TEST_F(ServerTest, NoGzip) {
  7690. Headers headers;
  7691. headers.emplace("Accept-Encoding", "gzip, deflate");
  7692. auto res = cli_.Get("/nocompress", headers);
  7693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7694. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7695. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7696. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7697. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7698. "7890123456789012345678901234567890",
  7699. res->body);
  7700. EXPECT_EQ(StatusCode::OK_200, res->status);
  7701. }
  7702. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7703. Headers headers;
  7704. headers.emplace("Accept-Encoding", "gzip, deflate");
  7705. std::string body;
  7706. auto res = cli_.Get("/nocompress", headers,
  7707. [&](const char *data, uint64_t data_length) {
  7708. EXPECT_EQ(100U, data_length);
  7709. body.append(data, data_length);
  7710. return true;
  7711. });
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7714. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7715. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7716. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7717. "7890123456789012345678901234567890",
  7718. body);
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. }
  7721. TEST_F(ServerTest, MultipartFormDataGzip) {
  7722. UploadFormDataItems items = {
  7723. {"key1", "test", "", ""},
  7724. {"key2", "--abcdefg123", "", ""},
  7725. };
  7726. cli_.set_compress(true);
  7727. auto res = cli_.Post("/compress-multipart", items);
  7728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7729. EXPECT_EQ(StatusCode::OK_200, res->status);
  7730. }
  7731. #endif
  7732. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7733. // Static file compression is opt-in, so these run their own server rather than
  7734. // flipping it on for the shared ServerTest fixture, which would silently
  7735. // rewrite what every other static file test is asserting.
  7736. class StaticFileCompressionTest : public ::testing::Test {
  7737. protected:
  7738. void TearDown() override {
  7739. if (t_.joinable()) {
  7740. svr_.stop();
  7741. t_.join();
  7742. }
  7743. }
  7744. int start(const std::function<void(Server &)> &configure = nullptr) {
  7745. // Serves the same tree as a directory of build-time compressed assets
  7746. // would be served: the mount point names the coding the files are already
  7747. // stored in. Registered before "/" so it is the one that matches.
  7748. svr_.set_mount_point("/pre-encoded", "./www",
  7749. {{"Content-Encoding", "gzip"}});
  7750. svr_.set_mount_point("/", "./www");
  7751. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7752. res.set_file_content("./www/dir/index.html", "text/html");
  7753. });
  7754. svr_.Get("/pre-encoded-file-content",
  7755. [](const Request & /*req*/, Response &res) {
  7756. res.set_header("Content-Encoding", "gzip");
  7757. res.set_file_content("./www/dir/index.html", "text/html");
  7758. });
  7759. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7760. res.set_content_provider(
  7761. 6, "text/plain",
  7762. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7763. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7764. return true;
  7765. });
  7766. });
  7767. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7768. res.set_content_provider(
  7769. 1000, "text/plain",
  7770. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7771. if (offset < 100) {
  7772. std::string data(100, 'A');
  7773. sink.write(data.data(), data.size());
  7774. return true;
  7775. }
  7776. std::this_thread::sleep_for(std::chrono::seconds(2));
  7777. std::string data(900, 'B');
  7778. sink.write(data.data(), data.size());
  7779. return true;
  7780. });
  7781. });
  7782. if (configure) { configure(svr_); }
  7783. auto port = svr_.bind_to_any_port(HOST);
  7784. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7785. svr_.wait_until_ready();
  7786. return port;
  7787. }
  7788. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7789. // Every file under ./www except 1MB.txt is smaller than the default
  7790. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7791. // it out of the way.
  7792. static void enable_without_floor(Server &svr) {
  7793. svr.set_static_file_compression(true);
  7794. svr.set_static_file_compression_min_length(0);
  7795. }
  7796. Server svr_;
  7797. std::thread t_;
  7798. };
  7799. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7800. auto port = start();
  7801. Client cli(HOST, port);
  7802. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7804. EXPECT_EQ(StatusCode::OK_200, res->status);
  7805. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7806. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7807. EXPECT_EQ(1048576U, res->body.size());
  7808. }
  7809. TEST_F(StaticFileCompressionTest, MountPoint) {
  7810. auto port = start(enable);
  7811. Client cli(HOST, port);
  7812. cli.set_decompress(false);
  7813. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7817. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7818. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7819. // The response stays self-delimiting: a length, not a chunked body.
  7820. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7821. EXPECT_EQ(std::to_string(res->body.size()),
  7822. res->get_header_value("Content-Length"));
  7823. EXPECT_LT(res->body.size(), 1048576U);
  7824. EXPECT_FALSE(res->body.empty());
  7825. }
  7826. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7827. auto port = start(enable);
  7828. Client cli(HOST, port);
  7829. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7831. EXPECT_EQ(StatusCode::OK_200, res->status);
  7832. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7833. EXPECT_EQ(1048576U, res->body.size());
  7834. }
  7835. TEST_F(StaticFileCompressionTest, FileContent) {
  7836. auto port = start(enable_without_floor);
  7837. Client cli(HOST, port);
  7838. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::OK_200, res->status);
  7841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7842. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7843. EXPECT_EQ(104U, res->body.size());
  7844. }
  7845. // A handler that serves an already-encoded file names the coding itself. The
  7846. // file-backed path decided its coding from Accept-Encoding and the content
  7847. // type alone, so it compressed the stored bytes a second time and appended a
  7848. // second Content-Encoding field line.
  7849. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7850. auto port = start(enable_without_floor);
  7851. Client cli(HOST, port);
  7852. cli.set_decompress(false);
  7853. auto res = cli.Get("/pre-encoded-file-content",
  7854. Headers{{"Accept-Encoding", "gzip"}});
  7855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7856. EXPECT_EQ(StatusCode::OK_200, res->status);
  7857. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7858. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7859. // Vary belongs to a coding the server chose, and it chose none here.
  7860. EXPECT_FALSE(res->has_header("Vary"));
  7861. // The file travels exactly as it is stored on disk.
  7862. EXPECT_EQ(104U, res->body.size());
  7863. }
  7864. // The 1MB file clears the default floor, so this one runs the configuration a
  7865. // deployment would actually have.
  7866. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7867. auto port = start(enable);
  7868. Client cli(HOST, port);
  7869. cli.set_decompress(false);
  7870. auto res =
  7871. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7875. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7876. EXPECT_FALSE(res->has_header("Vary"));
  7877. EXPECT_EQ(1048576U, res->body.size());
  7878. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7879. }
  7880. TEST_F(StaticFileCompressionTest, Head) {
  7881. auto port = start(enable);
  7882. Client cli(HOST, port);
  7883. cli.set_decompress(false);
  7884. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7885. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7886. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7890. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7891. // HEAD still reports the size a GET would return.
  7892. EXPECT_EQ(get->get_header_value("Content-Length"),
  7893. res->get_header_value("Content-Length"));
  7894. EXPECT_TRUE(res->body.empty());
  7895. }
  7896. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7897. auto port = start(enable);
  7898. Client cli(HOST, port);
  7899. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7900. {"Accept-Encoding", "gzip"}});
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7903. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7904. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7905. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7906. EXPECT_EQ("cd", res->body);
  7907. }
  7908. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7909. auto port = start(enable);
  7910. Client cli(HOST, port);
  7911. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7913. EXPECT_EQ(StatusCode::OK_200, res->status);
  7914. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7915. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7916. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7917. }
  7918. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7919. auto port = start(enable);
  7920. Client cli(HOST, port);
  7921. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7925. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7926. EXPECT_TRUE(res->body.empty());
  7927. }
  7928. TEST_F(StaticFileCompressionTest, MinLength) {
  7929. auto port = start(enable);
  7930. Client cli(HOST, port);
  7931. // 104 bytes, well under the default floor. Compressing it would add the
  7932. // gzip header and trailer to a body that already fits in one packet.
  7933. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7937. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7938. }
  7939. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7940. auto port = start([](Server &svr) {
  7941. svr.set_static_file_compression(true);
  7942. svr.set_static_file_compression_min_length(1);
  7943. });
  7944. Client cli(HOST, port);
  7945. cli.set_decompress(false);
  7946. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7948. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7949. // A 9-byte file comes back larger than it went in, because gzip's header and
  7950. // trailer outweigh anything deflate can save. That is the end of the range
  7951. // the floor exists to keep out.
  7952. EXPECT_GT(res->body.size(), 9U);
  7953. }
  7954. TEST_F(StaticFileCompressionTest, MaxLength) {
  7955. auto port = start([](Server &svr) {
  7956. svr.set_static_file_compression(true);
  7957. svr.set_static_file_compression_min_length(0);
  7958. svr.set_static_file_compression_max_length(1024);
  7959. });
  7960. Client cli(HOST, port);
  7961. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7962. // defines `small` as a macro on Windows.
  7963. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7964. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7965. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7966. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7967. // Under it: compressed.
  7968. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7969. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7970. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7971. }
  7972. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7973. auto port = start(enable_without_floor);
  7974. Client cli(HOST, port);
  7975. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7976. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7977. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7978. auto identity_etag = identity->get_header_value("ETag");
  7979. ASSERT_FALSE(identity_etag.empty());
  7980. auto gzipped =
  7981. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7982. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7983. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7984. auto gzip_etag = gzipped->get_header_value("ETag");
  7985. ASSERT_FALSE(gzip_etag.empty());
  7986. // Two representations, two validators.
  7987. EXPECT_NE(identity_etag, gzip_etag);
  7988. // Each one revalidates against the request that would produce it...
  7989. auto fresh =
  7990. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7991. {"If-None-Match", gzip_etag}});
  7992. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7993. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7994. auto fresh_identity =
  7995. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7996. {"If-None-Match", identity_etag}});
  7997. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7998. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7999. // ...and not against the other representation.
  8000. auto crossed =
  8001. cli.Get("/dir/index.html",
  8002. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8003. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8004. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8005. }
  8006. // The opt-in covers responses the server reads off disk itself. A caller's own
  8007. // known-length provider keeps its Content-Length and, more importantly, keeps
  8008. // delivering incrementally: routing it through a compressor would hold every
  8009. // write back until zlib's window filled.
  8010. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8011. auto port = start(enable);
  8012. Client cli(HOST, port);
  8013. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8015. EXPECT_EQ(StatusCode::OK_200, res->status);
  8016. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8017. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8018. EXPECT_EQ("aaabbb", res->body);
  8019. }
  8020. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8021. auto port = start(enable);
  8022. Client cli(HOST, port);
  8023. cli.set_read_timeout(1, 0);
  8024. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8025. Headers{{"Accept-Encoding", "gzip"}});
  8026. ASSERT_TRUE(handle.is_valid());
  8027. // The provider writes 100 bytes and then stalls for longer than the read
  8028. // timeout. Those first bytes have to arrive anyway: run the response through
  8029. // a compressor and zlib holds them until its window fills, so the read would
  8030. // come back empty instead.
  8031. char buf[256];
  8032. auto n = handle.read(buf, sizeof(buf));
  8033. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8034. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8035. }
  8036. #endif
  8037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8038. TEST_F(ServerTest, Brotli) {
  8039. Headers headers;
  8040. headers.emplace("Accept-Encoding", "br");
  8041. auto res = cli_.Get("/compress", headers);
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8044. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8045. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8047. "7890123456789012345678901234567890",
  8048. res->body);
  8049. EXPECT_EQ(StatusCode::OK_200, res->status);
  8050. }
  8051. #endif
  8052. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8053. TEST_F(ServerTest, Zstd) {
  8054. Headers headers;
  8055. headers.emplace("Accept-Encoding", "zstd");
  8056. auto res = cli_.Get("/compress", headers);
  8057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8058. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8060. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8061. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8062. "7890123456789012345678901234567890",
  8063. res->body);
  8064. EXPECT_EQ(StatusCode::OK_200, res->status);
  8065. }
  8066. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8067. Headers headers;
  8068. headers.emplace("Accept-Encoding", "");
  8069. auto res = cli_.Get("/compress", headers);
  8070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8071. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8072. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8073. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8074. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8075. "7890123456789012345678901234567890",
  8076. res->body);
  8077. EXPECT_EQ(StatusCode::OK_200, res->status);
  8078. }
  8079. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8080. Headers headers;
  8081. headers.emplace("Accept-Encoding", "zstd");
  8082. std::string body;
  8083. auto res = cli_.Get("/compress", headers,
  8084. [&](const char *data, uint64_t data_length) {
  8085. EXPECT_EQ(100U, data_length);
  8086. body.append(data, data_length);
  8087. return true;
  8088. });
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8092. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8093. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8094. "7890123456789012345678901234567890",
  8095. body);
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. }
  8098. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8099. Headers headers;
  8100. headers.emplace("Accept-Encoding", "zstd");
  8101. cli_.set_decompress(false);
  8102. auto res = cli_.Get("/compress", headers);
  8103. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8104. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8105. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8106. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8110. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8111. EXPECT_EQ(StatusCode::OK_200, res->status);
  8112. ASSERT_EQ(26U, res->body.size());
  8113. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8114. 0);
  8115. }
  8116. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8117. Headers headers;
  8118. headers.emplace("Accept-Encoding", "");
  8119. std::string body;
  8120. auto res = cli_.Get("/compress", headers,
  8121. [&](const char *data, uint64_t data_length) {
  8122. EXPECT_EQ(100U, data_length);
  8123. body.append(data, data_length);
  8124. return true;
  8125. });
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8129. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8130. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8131. "7890123456789012345678901234567890",
  8132. body);
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. }
  8135. TEST_F(ServerTest, NoZstd) {
  8136. Headers headers;
  8137. headers.emplace("Accept-Encoding", "zstd");
  8138. auto res = cli_.Get("/nocompress", headers);
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8144. "7890123456789012345678901234567890",
  8145. res->body);
  8146. EXPECT_EQ(StatusCode::OK_200, res->status);
  8147. }
  8148. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8149. Headers headers;
  8150. headers.emplace("Accept-Encoding", "zstd");
  8151. std::string body;
  8152. auto res = cli_.Get("/nocompress", headers,
  8153. [&](const char *data, uint64_t data_length) {
  8154. EXPECT_EQ(100U, data_length);
  8155. body.append(data, data_length);
  8156. return true;
  8157. });
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8160. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8161. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8162. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8163. "7890123456789012345678901234567890",
  8164. body);
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. }
  8167. // TODO: How to enable zstd ??
  8168. TEST_F(ServerTest, MultipartFormDataZstd) {
  8169. UploadFormDataItems items = {
  8170. {"key1", "test", "", ""},
  8171. {"key2", "--abcdefg123", "", ""},
  8172. };
  8173. Headers headers;
  8174. headers.emplace("Accept-Encoding", "zstd");
  8175. cli_.set_compress(true);
  8176. auto res = cli_.Post("/compress-multipart", headers, items);
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8181. Headers headers;
  8182. headers.emplace("Accept-Encoding", "zstd");
  8183. cli_.set_compress(true);
  8184. auto res = cli_.Put(
  8185. "/put", headers, 3,
  8186. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8187. sink.os << "PUT";
  8188. return true;
  8189. },
  8190. "text/plain");
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. EXPECT_EQ("PUT", res->body);
  8194. }
  8195. // Pre-compression logging tests
  8196. TEST_F(ServerTest, PreCompressionLogging) {
  8197. // Test data for compression (matches the actual /compress endpoint content)
  8198. const std::string test_content =
  8199. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8200. "3456789012345678901234567890";
  8201. // Variables to capture logging data
  8202. std::string pre_compression_body;
  8203. std::string pre_compression_content_type;
  8204. std::string pre_compression_content_encoding;
  8205. std::string post_compression_body;
  8206. std::string post_compression_content_type;
  8207. std::string post_compression_content_encoding;
  8208. // Set up pre-compression logger
  8209. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8210. const Response &res) {
  8211. pre_compression_body = res.body;
  8212. pre_compression_content_type = res.get_header_value("Content-Type");
  8213. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8214. });
  8215. // Set up post-compression logger
  8216. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8217. post_compression_body = res.body;
  8218. post_compression_content_type = res.get_header_value("Content-Type");
  8219. post_compression_content_encoding =
  8220. res.get_header_value("Content-Encoding");
  8221. });
  8222. // Test with gzip compression
  8223. Headers headers;
  8224. headers.emplace("Accept-Encoding", "gzip");
  8225. auto res = cli_.Get("/compress", headers);
  8226. // Verify response was compressed
  8227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8228. EXPECT_EQ(StatusCode::OK_200, res->status);
  8229. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8230. // Verify pre-compression logger captured uncompressed content
  8231. EXPECT_EQ(test_content, pre_compression_body);
  8232. EXPECT_EQ("text/plain", pre_compression_content_type);
  8233. EXPECT_TRUE(pre_compression_content_encoding
  8234. .empty()); // No encoding header before compression
  8235. // Verify post-compression logger captured compressed content
  8236. EXPECT_NE(test_content,
  8237. post_compression_body); // Should be different after compression
  8238. EXPECT_EQ("text/plain", post_compression_content_type);
  8239. EXPECT_EQ("gzip", post_compression_content_encoding);
  8240. // Verify compressed content is smaller
  8241. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8242. }
  8243. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8244. const std::string test_content =
  8245. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8246. "3456789012345678901234567890";
  8247. std::string pre_compression_body;
  8248. std::string post_compression_body;
  8249. svr_.set_pre_compression_logger(
  8250. [&](const Request & /*req*/, const Response &res) {
  8251. pre_compression_body = res.body;
  8252. });
  8253. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8254. post_compression_body = res.body;
  8255. });
  8256. Headers headers;
  8257. headers.emplace("Accept-Encoding", "br");
  8258. auto res = cli_.Get("/compress", headers);
  8259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8260. EXPECT_EQ(StatusCode::OK_200, res->status);
  8261. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8262. // Verify pre-compression content is uncompressed
  8263. EXPECT_EQ(test_content, pre_compression_body);
  8264. // Verify post-compression content is compressed
  8265. EXPECT_NE(test_content, post_compression_body);
  8266. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8267. }
  8268. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8269. const std::string test_content =
  8270. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8271. "3456789012345678901234567890";
  8272. std::string pre_compression_body;
  8273. std::string post_compression_body;
  8274. svr_.set_pre_compression_logger(
  8275. [&](const Request & /*req*/, const Response &res) {
  8276. pre_compression_body = res.body;
  8277. });
  8278. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8279. post_compression_body = res.body;
  8280. });
  8281. // Request without compression (use /nocompress endpoint)
  8282. Headers headers;
  8283. auto res = cli_.Get("/nocompress", headers);
  8284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8285. EXPECT_EQ(StatusCode::OK_200, res->status);
  8286. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8287. // Pre-compression logger should not be called when no compression is applied
  8288. EXPECT_TRUE(
  8289. pre_compression_body.empty()); // Pre-compression logger not called
  8290. EXPECT_EQ(
  8291. test_content,
  8292. post_compression_body); // Post-compression logger captures final content
  8293. }
  8294. TEST_F(ServerTest, LoggerSeesContentLength) {
  8295. size_t logged_content_length = 0;
  8296. std::string logged_content_length_header;
  8297. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8298. logged_content_length = res.content_length_;
  8299. logged_content_length_header = res.get_header_value("Content-Length");
  8300. });
  8301. auto res = cli_.Get("/nocompress");
  8302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8303. EXPECT_EQ(StatusCode::OK_200, res->status);
  8304. EXPECT_EQ(res->body.size(), logged_content_length);
  8305. EXPECT_EQ(std::to_string(logged_content_length),
  8306. logged_content_length_header);
  8307. }
  8308. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8309. const std::string test_content =
  8310. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8311. "3456789012345678901234567890";
  8312. std::string pre_compression_body;
  8313. bool pre_logger_called = false;
  8314. // Set only pre-compression logger
  8315. svr_.set_pre_compression_logger(
  8316. [&](const Request & /*req*/, const Response &res) {
  8317. pre_compression_body = res.body;
  8318. pre_logger_called = true;
  8319. });
  8320. Headers headers;
  8321. headers.emplace("Accept-Encoding", "gzip");
  8322. auto res = cli_.Get("/compress", headers);
  8323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8324. EXPECT_EQ(StatusCode::OK_200, res->status);
  8325. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8326. // Verify pre-compression logger was called
  8327. EXPECT_TRUE(pre_logger_called);
  8328. EXPECT_EQ(test_content, pre_compression_body);
  8329. }
  8330. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8331. {
  8332. // Test with Expect: 100-continue header - success case
  8333. // Server returns 100 Continue, client sends body, server returns 200 OK
  8334. Request req;
  8335. req.method = "POST";
  8336. req.path = "/post-large";
  8337. req.set_header("Expect", "100-continue");
  8338. req.body = LARGE_DATA;
  8339. Response res;
  8340. auto error = Error::Success;
  8341. cli_.set_keep_alive(true);
  8342. auto ret = cli_.send(req, res, error);
  8343. EXPECT_TRUE(ret);
  8344. EXPECT_EQ(StatusCode::OK_200, res.status);
  8345. EXPECT_EQ(LARGE_DATA, res.body);
  8346. }
  8347. {
  8348. // Test with Expect: 100-continue header - error case
  8349. // Client should not send the body when server returns an error
  8350. Request req;
  8351. req.method = "POST";
  8352. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8353. req.set_header("Expect", "100-continue");
  8354. req.body = LARGE_DATA;
  8355. Response res;
  8356. auto error = Error::Success;
  8357. auto start = std::chrono::high_resolution_clock::now();
  8358. cli_.set_keep_alive(true);
  8359. auto ret = cli_.send(req, res, error);
  8360. auto end = std::chrono::high_resolution_clock::now();
  8361. auto elapsed =
  8362. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8363. .count();
  8364. // With Expect: 100-continue, request completes successfully but with error
  8365. EXPECT_TRUE(ret);
  8366. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8367. EXPECT_EQ("close", res.get_header_value("Connection"));
  8368. EXPECT_FALSE(cli_.is_socket_open());
  8369. EXPECT_LE(elapsed, 2000);
  8370. }
  8371. {
  8372. // Send an extra GET request to ensure error recovery without hanging
  8373. Request req;
  8374. req.method = "GET";
  8375. req.path = "/hi";
  8376. auto start = std::chrono::high_resolution_clock::now();
  8377. auto res = cli_.send(req);
  8378. auto end = std::chrono::high_resolution_clock::now();
  8379. auto elapsed =
  8380. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8381. .count();
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ(StatusCode::OK_200, res->status);
  8384. EXPECT_EQ("Hello World!", res->body);
  8385. EXPECT_LE(elapsed, 500);
  8386. }
  8387. }
  8388. TEST(ZstdDecompressor, ChunkedDecompression) {
  8389. std::string data;
  8390. for (size_t i = 0; i < 32 * 1024; ++i) {
  8391. data.push_back(static_cast<char>('a' + i % 26));
  8392. }
  8393. std::string compressed_data;
  8394. {
  8395. httplib::detail::zstd_compressor compressor;
  8396. bool result = compressor.compress(
  8397. data.data(), data.size(),
  8398. /*last=*/true,
  8399. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8400. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8401. compressed_data_size);
  8402. return true;
  8403. });
  8404. ASSERT_TRUE(result);
  8405. }
  8406. std::string decompressed_data;
  8407. {
  8408. httplib::detail::zstd_decompressor decompressor;
  8409. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8410. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8411. size_t chunk_size = 130;
  8412. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8413. chunk_begin += chunk_size) {
  8414. size_t current_chunk_size =
  8415. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8416. bool result = decompressor.decompress(
  8417. compressed_data.data() + chunk_begin, current_chunk_size,
  8418. [&](const char *decompressed_data_chunk,
  8419. size_t decompressed_data_chunk_size) {
  8420. decompressed_data.insert(decompressed_data.size(),
  8421. decompressed_data_chunk,
  8422. decompressed_data_chunk_size);
  8423. return true;
  8424. });
  8425. ASSERT_TRUE(result);
  8426. }
  8427. }
  8428. ASSERT_EQ(data, decompressed_data);
  8429. }
  8430. TEST(ZstdDecompressor, Decompress) {
  8431. std::string original_text = "Compressed with ZSTD";
  8432. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8433. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8434. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8435. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8436. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8437. std::string decompressed_data;
  8438. {
  8439. httplib::detail::zstd_decompressor decompressor;
  8440. bool result = decompressor.decompress(
  8441. compressed_data.data(), compressed_data.size(),
  8442. [&](const char *decompressed_data_chunk,
  8443. size_t decompressed_data_chunk_size) {
  8444. decompressed_data.insert(decompressed_data.size(),
  8445. decompressed_data_chunk,
  8446. decompressed_data_chunk_size);
  8447. return true;
  8448. });
  8449. ASSERT_TRUE(result);
  8450. }
  8451. ASSERT_EQ(original_text, decompressed_data);
  8452. }
  8453. #endif
  8454. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8455. // separate chunks so that the server sees each part in its own read(). Used to
  8456. // place a read boundary at a specific offset of a request body.
  8457. static bool send_request_in_parts(time_t read_timeout_sec,
  8458. const std::vector<std::string> &parts,
  8459. std::string *resp = nullptr,
  8460. int port = PORT) {
  8461. auto error = Error::Success;
  8462. auto client_sock = detail::create_client_socket(
  8463. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8464. /*connection_timeout_sec=*/5, 0,
  8465. /*read_timeout_sec=*/5, 0,
  8466. /*write_timeout_sec=*/5, 0, std::string(), error);
  8467. if (client_sock == INVALID_SOCKET) { return false; }
  8468. auto ret = detail::process_client_socket(
  8469. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8470. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8471. for (size_t i = 0; i < parts.size(); i++) {
  8472. const auto &part = parts[i];
  8473. if (part.size() !=
  8474. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8475. return false;
  8476. }
  8477. if (i + 1 < parts.size()) {
  8478. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8479. }
  8480. }
  8481. char buf[512];
  8482. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8483. while (line_reader.getline()) {
  8484. if (resp) { *resp += line_reader.ptr(); }
  8485. }
  8486. return true;
  8487. });
  8488. detail::close_socket(client_sock);
  8489. return ret;
  8490. }
  8491. // Sends a raw request to a server listening at HOST:PORT.
  8492. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8493. std::string *resp = nullptr, int port = PORT) {
  8494. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8495. }
  8496. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8497. Server svr;
  8498. std::string header_value;
  8499. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8500. header_value = req.get_header_value("foo");
  8501. res.set_content("ok", "text/plain");
  8502. });
  8503. thread t = thread([&] { svr.listen(HOST, PORT); });
  8504. auto se = detail::scope_exit([&] {
  8505. svr.stop();
  8506. t.join();
  8507. ASSERT_FALSE(svr.is_running());
  8508. });
  8509. svr.wait_until_ready();
  8510. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8511. // like characters are not treated the same - use vertical tab and escape.
  8512. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8513. "foo: \t \v bar \x1B\t \r\n"
  8514. "Connection: close\r\n"
  8515. "\r\n";
  8516. std::string res;
  8517. ASSERT_TRUE(send_request(5, req, &res));
  8518. EXPECT_EQ(header_value, "");
  8519. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8520. }
  8521. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8522. Server svr;
  8523. std::string received;
  8524. svr.Get("/order", [&](const Request &req, Response &res) {
  8525. received = entries_to_string(req.headers);
  8526. res.set_content("ok", "text/plain");
  8527. });
  8528. auto port = svr.bind_to_any_port(HOST);
  8529. thread t = thread([&] { svr.listen_after_bind(); });
  8530. auto se = detail::scope_exit([&] {
  8531. svr.stop();
  8532. t.join();
  8533. ASSERT_FALSE(svr.is_running());
  8534. });
  8535. svr.wait_until_ready();
  8536. const std::string req = "GET /order HTTP/1.1\r\n"
  8537. "X-First: 1\r\n"
  8538. "X-Dup: a\r\n"
  8539. "X-Second: 2\r\n"
  8540. "X-Dup: b\r\n"
  8541. "Connection: close\r\n"
  8542. "\r\n";
  8543. std::string res;
  8544. ASSERT_TRUE(send_request(5, req, &res, port));
  8545. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8546. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8547. }
  8548. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8549. Server svr;
  8550. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8551. res.set_header("Set-Cookie", "first=1");
  8552. res.set_header("X-Between", "y");
  8553. res.set_header("Set-Cookie", "second=2");
  8554. res.set_content("ok", "text/plain");
  8555. });
  8556. auto port = svr.bind_to_any_port(HOST);
  8557. thread t = thread([&] { svr.listen_after_bind(); });
  8558. auto se = detail::scope_exit([&] {
  8559. svr.stop();
  8560. t.join();
  8561. ASSERT_FALSE(svr.is_running());
  8562. });
  8563. svr.wait_until_ready();
  8564. Client cli(HOST, port);
  8565. auto res = cli.Get("/cookies");
  8566. ASSERT_TRUE(res);
  8567. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8568. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8569. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8570. }
  8571. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8572. Server svr;
  8573. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8574. auto i = new int(0);
  8575. res.set_header("Trailer", "X-Safe, X-Reflected");
  8576. res.set_chunked_content_provider(
  8577. "text/plain",
  8578. [i](size_t /*offset*/, DataSink &sink) {
  8579. if (*i == 0) {
  8580. sink.os << "body";
  8581. } else {
  8582. Headers trailer;
  8583. // A valid trailer that must survive.
  8584. trailer.emplace("X-Safe", "safe");
  8585. // Attacker-controlled value carrying CR/LF (response splitting).
  8586. trailer.emplace("X-Reflected",
  8587. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8588. // Attacker-controlled name carrying CR/LF.
  8589. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8590. sink.done_with_trailer(trailer);
  8591. }
  8592. (*i)++;
  8593. return true;
  8594. },
  8595. [i](bool /*success*/) { delete i; });
  8596. });
  8597. thread t = thread([&] { svr.listen(HOST, PORT); });
  8598. auto se = detail::scope_exit([&] {
  8599. svr.stop();
  8600. t.join();
  8601. ASSERT_FALSE(svr.is_running());
  8602. });
  8603. svr.wait_until_ready();
  8604. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8605. "Host: " + HOST +
  8606. "\r\n"
  8607. "Connection: close\r\n"
  8608. "\r\n";
  8609. std::string res;
  8610. ASSERT_TRUE(send_request(5, req, &res));
  8611. // The injected fields must not appear anywhere in the raw response.
  8612. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8613. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8614. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8615. // Invalid trailers are dropped entirely, matching set_header().
  8616. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8617. // The valid trailer still passes through.
  8618. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8619. }
  8620. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8621. Server svr;
  8622. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8623. // res.headers is a public field an application can populate directly,
  8624. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8625. // A valid header that must survive.
  8626. res.headers.emplace("X-Safe", "safe");
  8627. // Attacker-controlled value carrying CR/LF (response splitting).
  8628. res.headers.emplace("X-Reflected",
  8629. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8630. // Attacker-controlled name carrying CR/LF.
  8631. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8632. res.set_content("body", "text/plain");
  8633. });
  8634. thread t = thread([&] { svr.listen(HOST, PORT); });
  8635. auto se = detail::scope_exit([&] {
  8636. svr.stop();
  8637. t.join();
  8638. ASSERT_FALSE(svr.is_running());
  8639. });
  8640. svr.wait_until_ready();
  8641. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8642. "Host: " + HOST +
  8643. "\r\n"
  8644. "Connection: close\r\n"
  8645. "\r\n";
  8646. std::string res;
  8647. ASSERT_TRUE(send_request(5, req, &res));
  8648. // The injected fields must not appear anywhere in the raw response.
  8649. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8650. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8651. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8652. // Invalid headers are dropped entirely, matching set_header().
  8653. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8654. // The valid header still passes through.
  8655. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8656. }
  8657. // Forward declaration: in split builds split.py strips `inline` and moves the
  8658. // definition into httplib.cc, so detail::write_request_line is not visible from
  8659. // the public httplib.h. Re-declaring it here lets the tests link against the
  8660. // symbol in both header-only and split builds.
  8661. namespace httplib {
  8662. namespace detail {
  8663. ssize_t write_request_line(Stream &strm, const std::string &method,
  8664. const std::string &path);
  8665. } // namespace detail
  8666. } // namespace httplib
  8667. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8668. // A well-formed target is written verbatim.
  8669. {
  8670. detail::BufferStream strm;
  8671. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8672. EXPECT_GT(n, 0);
  8673. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8674. }
  8675. // A target carrying CR/LF, SP or other control octets must be rejected
  8676. // before anything reaches the wire, otherwise it splits the request line and
  8677. // injects a header or a whole request.
  8678. const std::string evil_targets[] = {
  8679. "/a\r\nInjected: pwned",
  8680. "/a\rInjected",
  8681. "/a\nInjected",
  8682. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8683. "/a b",
  8684. "/a\tb",
  8685. "/a\x7f",
  8686. };
  8687. for (const auto &evil : evil_targets) {
  8688. detail::BufferStream strm;
  8689. auto n = detail::write_request_line(strm, "GET", evil);
  8690. EXPECT_LT(n, 0);
  8691. EXPECT_TRUE(strm.get_buffer().empty());
  8692. }
  8693. }
  8694. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8695. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8696. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8697. // target reaches write_request. The client must fail cleanly with
  8698. // Error::Write instead of putting a request-line-less, header-injecting
  8699. // request on the wire.
  8700. Server svr;
  8701. svr.Get("/a", [](const Request &, Response &res) {
  8702. res.set_content("ok", "text/plain");
  8703. });
  8704. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8705. auto se = detail::scope_exit([&] {
  8706. svr.stop();
  8707. thread.join();
  8708. ASSERT_FALSE(svr.is_running());
  8709. });
  8710. svr.wait_until_ready();
  8711. {
  8712. Client cli(HOST, PORT);
  8713. cli.set_path_encode(false);
  8714. // The request is rejected before anything is written, so the connection
  8715. // stays silent and the subsequent response read would otherwise block for
  8716. // the full default read timeout. Shorten it -- the assertion is on the
  8717. // error, not the timeout.
  8718. cli.set_read_timeout(1, 0);
  8719. auto res = cli.Get("/a\r\nInjected: pwned");
  8720. EXPECT_FALSE(res);
  8721. EXPECT_EQ(Error::Write, res.error());
  8722. }
  8723. }
  8724. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8725. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8726. // including extension methods.
  8727. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8728. for (const auto &method : good_methods) {
  8729. detail::BufferStream strm;
  8730. auto n = detail::write_request_line(strm, method, "/");
  8731. EXPECT_GT(n, 0);
  8732. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8733. }
  8734. // A method carrying CR/LF would split the request line and smuggle a whole
  8735. // request ahead of the real one. A space or an empty method corrupts the
  8736. // request line. All must be rejected before anything reaches the wire.
  8737. const std::string evil_methods[] = {
  8738. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8739. "GET\r\nInjected: pwned",
  8740. "GET\r",
  8741. "GET\n",
  8742. "GE T",
  8743. "",
  8744. };
  8745. for (const auto &evil : evil_methods) {
  8746. detail::BufferStream strm;
  8747. auto n = detail::write_request_line(strm, evil, "/");
  8748. EXPECT_LT(n, 0);
  8749. EXPECT_TRUE(strm.get_buffer().empty());
  8750. }
  8751. }
  8752. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8753. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8754. // through Client::send must fail with Error::Write and no request, neither
  8755. // the smuggled one nor the real one, may reach the server.
  8756. Server svr;
  8757. std::atomic<int> request_count(0);
  8758. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8759. request_count++;
  8760. res.status = StatusCode::OK_200;
  8761. return Server::HandlerResponse::Handled;
  8762. });
  8763. auto port = svr.bind_to_any_port(HOST);
  8764. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8765. auto se = detail::scope_exit([&] {
  8766. svr.stop();
  8767. thread.join();
  8768. ASSERT_FALSE(svr.is_running());
  8769. });
  8770. svr.wait_until_ready();
  8771. {
  8772. Client cli(HOST, port);
  8773. const std::string evil_methods[] = {
  8774. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8775. "GE T",
  8776. "",
  8777. };
  8778. for (const auto &evil : evil_methods) {
  8779. Request req;
  8780. req.method = evil;
  8781. req.path = "/";
  8782. auto res = cli.send(req);
  8783. EXPECT_FALSE(res);
  8784. EXPECT_EQ(Error::Write, res.error());
  8785. }
  8786. auto handle =
  8787. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8788. EXPECT_FALSE(handle.is_valid());
  8789. EXPECT_EQ(Error::Write, handle.error);
  8790. // A valid request on the same client still goes through.
  8791. auto res = cli.Get("/");
  8792. ASSERT_TRUE(res);
  8793. EXPECT_EQ(StatusCode::OK_200, res->status);
  8794. }
  8795. EXPECT_EQ(1, request_count.load());
  8796. }
  8797. // Sends a raw request and verifies that there isn't a crash or exception.
  8798. static void test_raw_request(const std::string &req,
  8799. std::string *out = nullptr) {
  8800. Server svr;
  8801. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8802. res.set_content("ok", "text/plain");
  8803. });
  8804. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8805. res.set_content("ok", "text/plain");
  8806. });
  8807. svr.Get("/header_field_value_check",
  8808. [&](const Request & /*req*/, Response &res) {
  8809. res.set_content("ok", "text/plain");
  8810. });
  8811. svr.CustomRoute("PROPFIND", "/dav",
  8812. [&](const Request & /*req*/, Response &res) {
  8813. res.status = StatusCode::MultiStatus_207;
  8814. });
  8815. // Server read timeout must be longer than the client read timeout for the
  8816. // bug to reproduce, probably to force the server to process a request
  8817. // without a trailing blank line.
  8818. const time_t client_read_timeout_sec = 1;
  8819. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8820. bool listen_thread_ok = false;
  8821. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8822. auto se = detail::scope_exit([&] {
  8823. svr.stop();
  8824. t.join();
  8825. ASSERT_FALSE(svr.is_running());
  8826. EXPECT_TRUE(listen_thread_ok);
  8827. });
  8828. svr.wait_until_ready();
  8829. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8830. }
  8831. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8832. // A certain header line causes an exception if the header property is parsed
  8833. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8834. test_raw_request(
  8835. "GET /hi HTTP/1.1\r\n"
  8836. " : "
  8837. " "
  8838. " ");
  8839. }
  8840. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8841. // A certain header line causes an exception if the header property *name* is
  8842. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8843. // greedy matcher and requires backtracking when there are a lot of ":"
  8844. // characters.
  8845. // This occurs with libc++ but not libstdc++.
  8846. test_raw_request(
  8847. "GET /hi HTTP/1.1\r\n"
  8848. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8849. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8850. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8851. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8852. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8853. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8854. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8855. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8856. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8857. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8858. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8859. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8860. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8861. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8862. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8863. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8864. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8865. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8866. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8867. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8868. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8869. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8870. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8871. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8872. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8873. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8874. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8875. "&&&%%%");
  8876. }
  8877. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8878. // Make sure this doesn't crash the server.
  8879. // In a previous version of the header line regex, the "\r" rendered the line
  8880. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8881. // a new position where the leading white space ended and the field value
  8882. // began.
  8883. // The crash occurs with libc++ but not libstdc++.
  8884. test_raw_request("GET /hi HTTP/1.1\r\n"
  8885. "a:" +
  8886. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8887. "\r\n"
  8888. "\r\n");
  8889. }
  8890. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8891. std::string out;
  8892. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8893. "Content-Type: text/plain\r\n"
  8894. "Transfer-Encoding: chunked\r\n"
  8895. "\r\n"
  8896. "nothex\r\n",
  8897. &out);
  8898. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8899. }
  8900. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8901. std::string out;
  8902. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8903. "Content-Type: text/plain\r\n"
  8904. "Transfer-Encoding: chunked\r\n"
  8905. "\r\n"
  8906. "3\r\n"
  8907. "xyz\r\n"
  8908. "NaN\r\n",
  8909. &out);
  8910. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8911. }
  8912. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8913. std::string out;
  8914. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8915. "Content-Type: text/plain\r\n"
  8916. "Transfer-Encoding: chunked\r\n"
  8917. "\r\n"
  8918. // Length is too large for 64 bits.
  8919. "1ffffffffffffffff\r\n"
  8920. "xyz\r\n",
  8921. &out);
  8922. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8923. }
  8924. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8925. test_raw_request("GET /hi HTTP/1.1\r\n"
  8926. "Content-Type: text/plain\r\n\r");
  8927. }
  8928. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8929. std::string out;
  8930. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8931. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8932. }
  8933. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8934. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8935. std::string out;
  8936. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8937. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8938. }
  8939. }
  8940. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8941. std::string out;
  8942. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8943. "Connection: close\r\n\r\n",
  8944. &out);
  8945. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8946. }
  8947. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8948. Server svr;
  8949. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8950. EXPECT_TRUE(!req.remote_addr.empty());
  8951. });
  8952. thread t = thread([&] { svr.listen(HOST, PORT); });
  8953. auto se = detail::scope_exit([&] {
  8954. svr.stop();
  8955. t.join();
  8956. ASSERT_FALSE(svr.is_running());
  8957. });
  8958. svr.wait_until_ready();
  8959. // Send an invalid request line to trigger Bad Request
  8960. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8961. std::string out;
  8962. ASSERT_TRUE(send_request(5, bad_req, &out));
  8963. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8964. }
  8965. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8966. // answered right away rather than blocking on a read that waits for EOF.
  8967. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8968. std::string out;
  8969. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8970. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8971. }
  8972. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8973. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8974. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8975. for (const auto *method : methods) {
  8976. Server svr;
  8977. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8978. EXPECT_FALSE(svr.is_valid()) << method;
  8979. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8980. }
  8981. }
  8982. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8983. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8984. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8985. for (const auto *method : methods) {
  8986. Server svr;
  8987. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8988. EXPECT_FALSE(svr.is_valid()) << method;
  8989. }
  8990. }
  8991. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8992. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8993. "COPY", "MOVE", "LOCK",
  8994. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8995. Server svr;
  8996. for (const auto *method : methods) {
  8997. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8998. }
  8999. EXPECT_TRUE(svr.is_valid());
  9000. }
  9001. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9002. Server svr;
  9003. svr.CustomRoute("POST", "/x",
  9004. [](const Request &, Response &, const ContentReader &) {});
  9005. EXPECT_FALSE(svr.is_valid());
  9006. }
  9007. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9008. Server svr;
  9009. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9010. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9011. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9012. EXPECT_FALSE(svr.is_valid());
  9013. }
  9014. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9015. Server svr;
  9016. auto captured = Error::Success;
  9017. svr.set_error_logger(
  9018. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9019. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9020. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9021. }
  9022. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9023. std::string out;
  9024. std::string request(
  9025. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9026. test_raw_request(request, &out);
  9027. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9028. }
  9029. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9030. std::string out;
  9031. std::string request(
  9032. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9033. test_raw_request(request, &out);
  9034. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9035. }
  9036. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9037. std::string out;
  9038. std::string request(
  9039. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9040. test_raw_request(request, &out);
  9041. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9042. }
  9043. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9044. std::string out;
  9045. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9046. "Test: \r\n\r\n",
  9047. &out);
  9048. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9049. }
  9050. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9051. Server svr;
  9052. std::string x_custom;
  9053. std::string cookie;
  9054. std::string xff;
  9055. std::string x_unicode;
  9056. std::string x_iis;
  9057. svr.Get("/check", [&](const Request &req, Response &res) {
  9058. x_custom = req.get_header_value("X-Custom");
  9059. cookie = req.get_header_value("Cookie");
  9060. xff = req.get_header_value("X-Forwarded-For");
  9061. x_unicode = req.get_header_value("X-Unicode");
  9062. x_iis = req.get_header_value("X-IIS");
  9063. res.set_content("ok", "text/plain");
  9064. });
  9065. thread t = thread([&] { svr.listen(HOST, PORT); });
  9066. auto se = detail::scope_exit([&] {
  9067. svr.stop();
  9068. t.join();
  9069. ASSERT_FALSE(svr.is_running());
  9070. });
  9071. svr.wait_until_ready();
  9072. const std::string req = "GET /check HTTP/1.1\r\n"
  9073. "Host: localhost\r\n"
  9074. "X-Custom: a%0D%0AInjected: b\r\n"
  9075. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9076. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9077. "X-Unicode: %E3%81%82\r\n"
  9078. "X-IIS: %u00E9\r\n"
  9079. "Connection: close\r\n"
  9080. "\r\n";
  9081. std::string res;
  9082. ASSERT_TRUE(send_request(5, req, &res));
  9083. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9084. // Every value must be returned verbatim (wire form), with no decoding.
  9085. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9086. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9087. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9088. EXPECT_EQ("%E3%81%82", x_unicode);
  9089. EXPECT_EQ("%u00E9", x_iis);
  9090. }
  9091. // Applications that previously relied on automatic percent-decoding can
  9092. // reproduce the old behavior by explicitly calling decode_path_component()
  9093. // or, for RFC 3986 conformance, decode_uri_component().
  9094. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9095. Server svr;
  9096. std::string decoded;
  9097. svr.Get("/check", [&](const Request &req, Response &res) {
  9098. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9099. res.set_content("ok", "text/plain");
  9100. });
  9101. thread t = thread([&] { svr.listen(HOST, PORT); });
  9102. auto se = detail::scope_exit([&] {
  9103. svr.stop();
  9104. t.join();
  9105. ASSERT_FALSE(svr.is_running());
  9106. });
  9107. svr.wait_until_ready();
  9108. const std::string req = "GET /check HTTP/1.1\r\n"
  9109. "Host: localhost\r\n"
  9110. "X-Custom: hello%20world\r\n"
  9111. "Connection: close\r\n"
  9112. "\r\n";
  9113. std::string res;
  9114. ASSERT_TRUE(send_request(5, req, &res));
  9115. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9116. EXPECT_EQ("hello world", decoded);
  9117. }
  9118. // Regression test for #2033. Browsers send Referer values that include
  9119. // percent-encoded characters such as %0A inside the URL. Decoding the
  9120. // header value would either trip the post-decode CR/LF/NUL guard (the
  9121. // original bug, returning 400) or, after that guard was relaxed, silently
  9122. // store a literal LF — both unacceptable. The wire form must round-trip.
  9123. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9124. Server svr;
  9125. std::string referer;
  9126. svr.Get("/check", [&](const Request &req, Response &res) {
  9127. referer = req.get_header_value("Referer");
  9128. res.set_content("ok", "text/plain");
  9129. });
  9130. thread t = thread([&] { svr.listen(HOST, PORT); });
  9131. auto se = detail::scope_exit([&] {
  9132. svr.stop();
  9133. t.join();
  9134. ASSERT_FALSE(svr.is_running());
  9135. });
  9136. svr.wait_until_ready();
  9137. const std::string req = "GET /check HTTP/1.1\r\n"
  9138. "Host: localhost\r\n"
  9139. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9140. "Connection: close\r\n"
  9141. "\r\n";
  9142. std::string res;
  9143. ASSERT_TRUE(send_request(5, req, &res));
  9144. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9145. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9146. }
  9147. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9148. Server svr;
  9149. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9150. res.set_header("Cache-Control", "no-cache");
  9151. res.set_chunked_content_provider(
  9152. "text/event-stream", [](size_t offset, DataSink &sink) {
  9153. std::string s = "data:";
  9154. s += std::to_string(offset);
  9155. s += "\n\n";
  9156. auto ret = sink.write(s.data(), s.size());
  9157. EXPECT_TRUE(ret);
  9158. std::this_thread::sleep_for(std::chrono::seconds(1));
  9159. return true;
  9160. });
  9161. });
  9162. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9163. svr.wait_until_ready();
  9164. Client client(HOST, PORT);
  9165. const Headers headers = {{"Accept", "text/event-stream"}};
  9166. auto get_thread = std::thread([&client, &headers]() {
  9167. auto res = client.Get(
  9168. "/events", headers,
  9169. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9170. });
  9171. auto se = detail::scope_exit([&] {
  9172. svr.stop();
  9173. get_thread.join();
  9174. listen_thread.join();
  9175. ASSERT_FALSE(svr.is_running());
  9176. });
  9177. // Give GET time to get a few messages.
  9178. std::this_thread::sleep_for(std::chrono::seconds(2));
  9179. }
  9180. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9181. httplib::Server svr;
  9182. svr.Post("/hi",
  9183. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9184. res.status = StatusCode::OK_200;
  9185. });
  9186. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9187. svr.wait_until_ready();
  9188. Client cli(HOST, PORT);
  9189. auto res = cli.Post("/hi", "data", "text/plain");
  9190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9191. EXPECT_EQ(StatusCode::OK_200, res->status);
  9192. svr.stop();
  9193. thread.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. res = cli.Post("/hi", "data", "text/plain");
  9196. ASSERT_FALSE(res);
  9197. }
  9198. TEST(ServerStopTest, ListenFailure) {
  9199. Server svr;
  9200. auto t = thread([&]() {
  9201. auto ret = svr.listen("????", PORT);
  9202. EXPECT_FALSE(ret);
  9203. });
  9204. svr.wait_until_ready();
  9205. svr.stop();
  9206. t.join();
  9207. }
  9208. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9209. TEST(ServerStopTest, Decommision) {
  9210. Server svr;
  9211. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9212. for (int i = 0; i < 4; i++) {
  9213. auto is_even = !(i % 2);
  9214. std::thread t{[&] {
  9215. try {
  9216. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9217. if (is_even) {
  9218. throw std::runtime_error("Some thing that happens to go wrong.");
  9219. }
  9220. svr.listen(HOST, PORT);
  9221. } catch (...) { svr.decommission(); }
  9222. }};
  9223. svr.wait_until_ready();
  9224. // Server is up
  9225. {
  9226. Client cli(HOST, PORT);
  9227. auto res = cli.Get("/hi");
  9228. if (is_even) {
  9229. EXPECT_FALSE(res);
  9230. } else {
  9231. EXPECT_TRUE(res);
  9232. EXPECT_EQ("hi...", res->body);
  9233. }
  9234. }
  9235. svr.stop();
  9236. t.join();
  9237. // Server is down...
  9238. {
  9239. Client cli(HOST, PORT);
  9240. auto res = cli.Get("/hi");
  9241. EXPECT_FALSE(res);
  9242. }
  9243. }
  9244. }
  9245. #endif
  9246. // Helper function for string body upload progress tests
  9247. template <typename SetupHandler, typename ClientCall>
  9248. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9249. ClientCall &&client_call,
  9250. const string &body) {
  9251. Server svr;
  9252. setup_handler(svr);
  9253. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9254. auto se = detail::scope_exit([&] {
  9255. svr.stop();
  9256. t.join();
  9257. });
  9258. svr.wait_until_ready();
  9259. Client cli(HOST, PORT);
  9260. vector<uint64_t> progress_values;
  9261. bool progress_called = false;
  9262. auto res =
  9263. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9264. progress_values.push_back(current);
  9265. progress_called = true;
  9266. return true;
  9267. });
  9268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9269. EXPECT_EQ(200, res->status);
  9270. EXPECT_TRUE(progress_called);
  9271. }
  9272. TEST(UploadProgressTest, PostStringBodyBasic) {
  9273. TestStringBodyUploadProgress(
  9274. [](Server &svr) {
  9275. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9276. res.set_content("received", "text/plain");
  9277. });
  9278. },
  9279. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9280. return cli.Post("/test", body, "text/plain", progress_callback);
  9281. },
  9282. "test data for upload progress");
  9283. }
  9284. TEST(UploadProgressTest, PutStringBodyBasic) {
  9285. TestStringBodyUploadProgress(
  9286. [](Server &svr) {
  9287. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9288. res.set_content("put received", "text/plain");
  9289. });
  9290. },
  9291. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9292. return cli.Put("/test", body, "text/plain", progress_callback);
  9293. },
  9294. "put test data for upload progress");
  9295. }
  9296. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9297. TestStringBodyUploadProgress(
  9298. [](Server &svr) {
  9299. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9300. res.set_content("patch received", "text/plain");
  9301. });
  9302. },
  9303. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9304. return cli.Patch("/test", body, "text/plain", progress_callback);
  9305. },
  9306. "patch test data for upload progress");
  9307. }
  9308. // Helper function for content provider upload progress tests
  9309. template <typename SetupHandler, typename ClientCall>
  9310. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9311. ClientCall &&client_call) {
  9312. Server svr;
  9313. setup_handler(svr);
  9314. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9315. auto se = detail::scope_exit([&] {
  9316. svr.stop();
  9317. t.join();
  9318. });
  9319. svr.wait_until_ready();
  9320. Client cli(HOST, PORT);
  9321. vector<uint64_t> progress_values;
  9322. auto res =
  9323. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9324. progress_values.push_back(current);
  9325. return true;
  9326. });
  9327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9328. EXPECT_EQ(200, res->status);
  9329. EXPECT_FALSE(progress_values.empty());
  9330. }
  9331. TEST(UploadProgressTest, PostContentProviderProgress) {
  9332. TestContentProviderUploadProgress(
  9333. [](Server &svr) {
  9334. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9335. res.set_content("provider received", "text/plain");
  9336. });
  9337. },
  9338. [](Client &cli, UploadProgress progress_callback) {
  9339. return cli.Post(
  9340. "/test", 10,
  9341. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9342. sink.os << "test data";
  9343. return true;
  9344. },
  9345. "text/plain", progress_callback);
  9346. });
  9347. }
  9348. // Helper function for multipart upload progress tests
  9349. template <typename SetupHandler, typename ClientCall>
  9350. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9351. ClientCall &&client_call,
  9352. const string &endpoint) {
  9353. Server svr;
  9354. setup_handler(svr);
  9355. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. });
  9360. svr.wait_until_ready();
  9361. Client cli(HOST, PORT);
  9362. vector<uint64_t> progress_values;
  9363. UploadFormDataItems items = {
  9364. {"field1", "value1", "", ""},
  9365. {"field2", "longer value for progress tracking test", "", ""},
  9366. {"file1", "file content data for upload progress", "test.txt",
  9367. "text/plain"}};
  9368. auto res = client_call(cli, endpoint, items,
  9369. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9370. progress_values.push_back(current);
  9371. return true;
  9372. });
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. EXPECT_EQ(200, res->status);
  9375. EXPECT_FALSE(progress_values.empty());
  9376. }
  9377. TEST(UploadProgressTest, PostMultipartProgress) {
  9378. TestMultipartUploadProgress(
  9379. [](Server &svr) {
  9380. svr.Post("/multipart", [](const Request &req, Response &res) {
  9381. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9382. res.set_content("multipart received", "text/plain");
  9383. });
  9384. },
  9385. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9386. UploadProgress progress_callback) {
  9387. return cli.Post(endpoint, items, progress_callback);
  9388. },
  9389. "/multipart");
  9390. }
  9391. // Helper function for basic download progress tests
  9392. template <typename SetupHandler, typename ClientCall>
  9393. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9394. ClientCall &&client_call, const string &endpoint,
  9395. size_t expected_content_size) {
  9396. Server svr;
  9397. setup_handler(svr);
  9398. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9399. auto se = detail::scope_exit([&] {
  9400. svr.stop();
  9401. t.join();
  9402. });
  9403. svr.wait_until_ready();
  9404. Client cli(HOST, PORT);
  9405. vector<uint64_t> progress_values;
  9406. auto res = client_call(cli, endpoint,
  9407. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9408. progress_values.push_back(current);
  9409. return true;
  9410. });
  9411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9412. EXPECT_EQ(200, res->status);
  9413. EXPECT_FALSE(progress_values.empty());
  9414. EXPECT_EQ(expected_content_size, res->body.size());
  9415. }
  9416. TEST(DownloadProgressTest, GetBasic) {
  9417. TestBasicDownloadProgress(
  9418. [](Server &svr) {
  9419. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9420. string content(1000, 'D');
  9421. res.set_content(content, "text/plain");
  9422. });
  9423. },
  9424. [](Client &cli, const string &endpoint,
  9425. DownloadProgress progress_callback) {
  9426. return cli.Get(endpoint, progress_callback);
  9427. },
  9428. "/download", 1000u);
  9429. }
  9430. // Helper function for content receiver download progress tests
  9431. template <typename SetupHandler, typename ClientCall>
  9432. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9433. ClientCall &&client_call,
  9434. const string &endpoint,
  9435. size_t expected_content_size) {
  9436. Server svr;
  9437. setup_handler(svr);
  9438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9439. auto se = detail::scope_exit([&] {
  9440. svr.stop();
  9441. t.join();
  9442. });
  9443. svr.wait_until_ready();
  9444. Client cli(HOST, PORT);
  9445. vector<uint64_t> progress_values;
  9446. string received_body;
  9447. auto res = client_call(
  9448. cli, endpoint,
  9449. [&](const char *data, size_t data_length) -> bool {
  9450. received_body.append(data, data_length);
  9451. return true;
  9452. },
  9453. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9454. progress_values.push_back(current);
  9455. return true;
  9456. });
  9457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9458. EXPECT_EQ(200, res->status);
  9459. EXPECT_FALSE(progress_values.empty());
  9460. EXPECT_EQ(expected_content_size, received_body.size());
  9461. EXPECT_TRUE(res->body.empty());
  9462. }
  9463. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9464. TestContentReceiverDownloadProgress(
  9465. [](Server &svr) {
  9466. svr.Get("/download-receiver",
  9467. [](const Request & /*req*/, Response &res) {
  9468. string content(2000, 'R');
  9469. res.set_content(content, "text/plain");
  9470. });
  9471. },
  9472. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9473. DownloadProgress progress_callback) {
  9474. return cli.Get(endpoint, content_receiver, progress_callback);
  9475. },
  9476. "/download-receiver", 2000u);
  9477. }
  9478. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9479. // A provider reaching a pass with nothing to hand over - an empty buffer
  9480. // popped off a queue, say - must not be taken to mean the body is finished.
  9481. // It used to end the loop with the terminating chunk unwritten while the
  9482. // server still considered the response complete, so the peer waited for an
  9483. // end that never arrived.
  9484. Server svr;
  9485. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9486. auto step = std::make_shared<int>(0);
  9487. res.set_chunked_content_provider("text/plain",
  9488. [step](size_t /*offset*/, DataSink &sink) {
  9489. switch ((*step)++) {
  9490. case 0: sink.write("", 0); break;
  9491. case 1: sink.write("hello", 5); break;
  9492. default: sink.done(); break;
  9493. }
  9494. return true;
  9495. });
  9496. });
  9497. auto port = svr.bind_to_any_port(HOST);
  9498. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9499. auto listen_se = detail::scope_exit([&] {
  9500. svr.stop();
  9501. listen_thread.join();
  9502. ASSERT_FALSE(svr.is_running());
  9503. });
  9504. svr.wait_until_ready();
  9505. Client cli(HOST, port);
  9506. // Without the fix the body is never terminated, so bound the wait rather
  9507. // than letting the test hang on the default read timeout.
  9508. cli.set_read_timeout(5, 0);
  9509. auto res = cli.Get("/stream");
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ(StatusCode::OK_200, res->status);
  9512. EXPECT_EQ("hello", res->body);
  9513. }
  9514. TEST(StreamingTest, NoContentLengthStreaming) {
  9515. Server svr;
  9516. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9517. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9518. if (offset < 6) {
  9519. sink.os << (offset < 3 ? "a" : "b");
  9520. } else {
  9521. sink.done();
  9522. }
  9523. return true;
  9524. });
  9525. });
  9526. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9527. auto listen_se = detail::scope_exit([&] {
  9528. svr.stop();
  9529. listen_thread.join();
  9530. ASSERT_FALSE(svr.is_running());
  9531. });
  9532. svr.wait_until_ready();
  9533. Client client(HOST, PORT);
  9534. auto get_thread = std::thread([&client]() {
  9535. std::string s;
  9536. auto res =
  9537. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9538. s += std::string(data, len);
  9539. return true;
  9540. });
  9541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9542. EXPECT_EQ(StatusCode::OK_200, res->status);
  9543. EXPECT_EQ("aaabbb", s);
  9544. });
  9545. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9546. // Give GET time to get a few messages.
  9547. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9548. }
  9549. TEST(MountTest, Unmount) {
  9550. Server svr;
  9551. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9552. auto se = detail::scope_exit([&] {
  9553. svr.stop();
  9554. listen_thread.join();
  9555. ASSERT_FALSE(svr.is_running());
  9556. });
  9557. svr.wait_until_ready();
  9558. Client cli("localhost", PORT);
  9559. svr.set_mount_point("/mount2", "./www2");
  9560. auto res = cli.Get("/");
  9561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9562. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9563. res = cli.Get("/mount2/dir/test.html");
  9564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9565. EXPECT_EQ(StatusCode::OK_200, res->status);
  9566. svr.set_mount_point("/", "./www");
  9567. res = cli.Get("/dir/");
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. EXPECT_EQ(StatusCode::OK_200, res->status);
  9570. svr.remove_mount_point("/");
  9571. res = cli.Get("/dir/");
  9572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9574. svr.remove_mount_point("/mount2");
  9575. res = cli.Get("/mount2/dir/test.html");
  9576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9577. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9578. }
  9579. TEST(MountTest, PathSegmentBoundary) {
  9580. Server svr;
  9581. svr.set_mount_point("/mount2", "./www2");
  9582. svr.set_mount_point("/", "./www");
  9583. auto port = svr.bind_to_any_port(HOST);
  9584. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. listen_thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. Client cli(HOST, port);
  9592. auto res = cli.Get("/mount2/dir/test.html");
  9593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9594. EXPECT_EQ(StatusCode::OK_200, res->status);
  9595. // "/mount2" must not match part-way through a path segment.
  9596. res = cli.Get("/mount2dir/test.html");
  9597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9598. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9599. // A mount point ending in '/' keeps matching every path below it.
  9600. res = cli.Get("/dir/test.html");
  9601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9602. EXPECT_EQ(StatusCode::OK_200, res->status);
  9603. }
  9604. TEST(MountTest, Redicect) {
  9605. Server svr;
  9606. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9607. auto se = detail::scope_exit([&] {
  9608. svr.stop();
  9609. listen_thread.join();
  9610. ASSERT_FALSE(svr.is_running());
  9611. });
  9612. svr.set_mount_point("/", "./www");
  9613. svr.wait_until_ready();
  9614. Client cli("localhost", PORT);
  9615. auto res = cli.Get("/dir/");
  9616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9617. EXPECT_EQ(StatusCode::OK_200, res->status);
  9618. res = cli.Get("/dir");
  9619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9620. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9621. res = cli.Get("/file");
  9622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9623. EXPECT_EQ(StatusCode::OK_200, res->status);
  9624. res = cli.Get("/file/");
  9625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9627. cli.set_follow_location(true);
  9628. res = cli.Get("/dir");
  9629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9630. EXPECT_EQ(StatusCode::OK_200, res->status);
  9631. }
  9632. TEST(MountTest, MultibytesPathName) {
  9633. Server svr;
  9634. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9635. auto se = detail::scope_exit([&] {
  9636. svr.stop();
  9637. listen_thread.join();
  9638. ASSERT_FALSE(svr.is_running());
  9639. });
  9640. svr.set_mount_point("/", "./www");
  9641. svr.wait_until_ready();
  9642. Client cli("localhost", PORT);
  9643. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9645. EXPECT_EQ(StatusCode::OK_200, res->status);
  9646. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9647. }
  9648. #ifdef _WIN32
  9649. // Issue #2435: mmap::open() must succeed even when another handle holds
  9650. // the file open for writing (e.g. an active log file).
  9651. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9652. const char *path = "mmap_concurrent_writer_test.txt";
  9653. const char *content = "hello";
  9654. {
  9655. std::ofstream f(path, std::ios::binary);
  9656. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9657. }
  9658. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9659. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9660. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9661. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9662. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9663. detail::mmap m(path);
  9664. ASSERT_TRUE(m.is_open());
  9665. EXPECT_EQ(strlen(content), m.size());
  9666. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9667. }
  9668. #endif
  9669. #ifndef _WIN32
  9670. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9671. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9672. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9673. TEST(MmapTest, FailedMappingIsNotOpen) {
  9674. const char *path = "./mmap_failed_mapping_test_dir";
  9675. ASSERT_EQ(0, ::mkdir(path, 0755));
  9676. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9677. detail::mmap m(path);
  9678. EXPECT_FALSE(m.is_open());
  9679. EXPECT_EQ(0U, m.size());
  9680. EXPECT_NE(static_cast<const void *>(m.data()),
  9681. static_cast<const void *>(MAP_FAILED));
  9682. }
  9683. #endif
  9684. TEST(KeepAliveTest, ReadTimeout) {
  9685. Server svr;
  9686. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9687. std::this_thread::sleep_for(std::chrono::seconds(2));
  9688. res.set_content("a", "text/plain");
  9689. });
  9690. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9691. res.set_content("b", "text/plain");
  9692. });
  9693. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9694. auto se = detail::scope_exit([&] {
  9695. svr.stop();
  9696. listen_thread.join();
  9697. ASSERT_FALSE(svr.is_running());
  9698. });
  9699. svr.wait_until_ready();
  9700. Client cli("localhost", PORT);
  9701. cli.set_keep_alive(true);
  9702. cli.set_read_timeout(std::chrono::seconds(1));
  9703. auto resa = cli.Get("/a");
  9704. ASSERT_FALSE(resa);
  9705. EXPECT_EQ(Error::Read, resa.error());
  9706. auto resb = cli.Get("/b");
  9707. ASSERT_TRUE(resb);
  9708. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9709. EXPECT_EQ("b", resb->body);
  9710. }
  9711. TEST(KeepAliveTest, MaxCount) {
  9712. size_t keep_alive_max_count = 3;
  9713. Server svr;
  9714. svr.set_keep_alive_max_count(keep_alive_max_count);
  9715. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9716. res.set_content("Hello World!", "text/plain");
  9717. });
  9718. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9719. auto se = detail::scope_exit([&] {
  9720. svr.stop();
  9721. listen_thread.join();
  9722. ASSERT_FALSE(svr.is_running());
  9723. });
  9724. svr.wait_until_ready();
  9725. Client cli(HOST, PORT);
  9726. cli.set_keep_alive(true);
  9727. for (size_t i = 0; i < 5; i++) {
  9728. auto result = cli.Get("/hi");
  9729. ASSERT_TRUE(result);
  9730. EXPECT_EQ(StatusCode::OK_200, result->status);
  9731. if (i == keep_alive_max_count - 1) {
  9732. EXPECT_EQ("close", result->get_header_value("Connection"));
  9733. } else {
  9734. EXPECT_FALSE(result->has_header("Connection"));
  9735. }
  9736. }
  9737. }
  9738. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9739. // can pull the next one into the server's buffer. The server must serve it
  9740. // without waiting for the socket to become readable again. The keep-alive
  9741. // timeout outlasts the client's read timeout, so a request left waiting for it
  9742. // shows up as a missing response.
  9743. static void serve_pipelining_routes(Server &svr,
  9744. const std::function<void(int)> &client) {
  9745. svr.set_keep_alive_timeout(5);
  9746. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9747. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9748. });
  9749. svr.Post("/echo", [](const Request &req, Response &res) {
  9750. res.set_content("echo " + req.body, "text/plain");
  9751. });
  9752. auto port = svr.bind_to_any_port(HOST);
  9753. thread t = thread([&] { svr.listen_after_bind(); });
  9754. auto se = detail::scope_exit([&] {
  9755. svr.stop();
  9756. t.join();
  9757. });
  9758. svr.wait_until_ready();
  9759. client(port);
  9760. }
  9761. static std::string
  9762. send_pipelined_requests(const std::vector<std::string> &parts) {
  9763. Server svr;
  9764. std::string res;
  9765. serve_pipelining_routes(svr, [&](int port) {
  9766. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9767. });
  9768. return res;
  9769. }
  9770. static void expect_in_order(const std::string &res,
  9771. const std::vector<std::string> &bodies) {
  9772. size_t pos = 0;
  9773. for (const auto &body : bodies) {
  9774. pos = res.find(body, pos);
  9775. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9776. pos += body.size();
  9777. }
  9778. }
  9779. TEST(KeepAliveTest, PipelinedRequests) {
  9780. auto res = send_pipelined_requests(
  9781. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9782. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9783. "Content-Length: 4\r\n\r\nbody"
  9784. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9785. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9786. }
  9787. // The second request starts in the server's buffer and ends on the socket.
  9788. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9789. auto res =
  9790. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9791. "GET /hi/2 HTTP/1.1\r\nHo",
  9792. "st: localhost\r\nConnection: close\r\n\r\n"});
  9793. expect_in_order(res, {"hi 1", "hi 2"});
  9794. }
  9795. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9796. // CRLF after a body does not turn into a 400 for the next request.
  9797. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9798. auto res = send_pipelined_requests(
  9799. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9800. "Content-Length: 4\r\n\r\nbody\r\n"
  9801. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9802. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9803. expect_in_order(res, {"echo body", "hi 2"});
  9804. }
  9805. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9806. // must not be served as the next request.
  9807. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9808. auto res = send_pipelined_requests(
  9809. {"INVALID REQUEST LINE\r\n\r\n"
  9810. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9811. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9812. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9813. }
  9814. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9815. // Over TLS, the next request is held by the TLS library as already decrypted
  9816. // data rather than on the socket.
  9817. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9819. std::string res;
  9820. serve_pipelining_routes(svr, [&](int port) {
  9821. auto error = Error::Success;
  9822. auto sock = detail::create_client_socket(
  9823. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9824. /*connection_timeout_sec=*/5, 0,
  9825. /*read_timeout_sec=*/2, 0,
  9826. /*write_timeout_sec=*/5, 0, std::string(), error);
  9827. ASSERT_NE(INVALID_SOCKET, sock);
  9828. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9829. auto ctx = SSL_CTX_new(TLS_client_method());
  9830. auto ssl = SSL_new(ctx);
  9831. auto ssl_se = detail::scope_exit([&] {
  9832. SSL_free(ssl);
  9833. SSL_CTX_free(ctx);
  9834. });
  9835. SSL_set_fd(ssl, static_cast<int>(sock));
  9836. ASSERT_EQ(1, SSL_connect(ssl));
  9837. // One write, so all three requests arrive in one TLS record
  9838. const std::string req =
  9839. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9840. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9841. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9842. ASSERT_EQ(static_cast<int>(req.size()),
  9843. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9844. char buf[512];
  9845. int n;
  9846. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9847. res.append(buf, static_cast<size_t>(n));
  9848. }
  9849. });
  9850. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9851. }
  9852. #endif
  9853. TEST(KeepAliveTest, Issue1041) {
  9854. Server svr;
  9855. svr.set_keep_alive_timeout(3);
  9856. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9857. res.set_content("Hello World!", "text/plain");
  9858. });
  9859. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9860. auto se = detail::scope_exit([&] {
  9861. svr.stop();
  9862. listen_thread.join();
  9863. ASSERT_FALSE(svr.is_running());
  9864. });
  9865. svr.wait_until_ready();
  9866. Client cli(HOST, PORT);
  9867. cli.set_keep_alive(true);
  9868. auto result = cli.Get("/hi");
  9869. ASSERT_TRUE(result);
  9870. EXPECT_EQ(StatusCode::OK_200, result->status);
  9871. std::this_thread::sleep_for(std::chrono::seconds(5));
  9872. result = cli.Get("/hi");
  9873. ASSERT_TRUE(result);
  9874. EXPECT_EQ(StatusCode::OK_200, result->status);
  9875. }
  9876. TEST(KeepAliveTest, Issue1959) {
  9877. Server svr;
  9878. svr.set_keep_alive_timeout(5);
  9879. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9880. res.set_content("a", "text/plain");
  9881. });
  9882. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9883. auto se = detail::scope_exit([&] {
  9884. if (!svr.is_running()) return;
  9885. svr.stop();
  9886. listen_thread.join();
  9887. ASSERT_FALSE(svr.is_running());
  9888. });
  9889. svr.wait_until_ready();
  9890. Client cli("localhost", PORT);
  9891. cli.set_keep_alive(true);
  9892. using namespace std::chrono;
  9893. auto start = steady_clock::now();
  9894. cli.Get("/a");
  9895. svr.stop();
  9896. listen_thread.join();
  9897. auto end = steady_clock::now();
  9898. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9899. EXPECT_LT(elapsed, 5000);
  9900. }
  9901. #ifdef CPPHTTPLIB_SSL_ENABLED
  9902. TEST(KeepAliveTest, SSLClientReconnection) {
  9903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9904. ASSERT_TRUE(svr.is_valid());
  9905. svr.set_keep_alive_timeout(1);
  9906. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9907. res.set_content("Hello World!", "text/plain");
  9908. });
  9909. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9910. auto se = detail::scope_exit([&] {
  9911. svr.stop();
  9912. listen_thread.join();
  9913. ASSERT_FALSE(svr.is_running());
  9914. });
  9915. svr.wait_until_ready();
  9916. SSLClient cli(HOST, PORT);
  9917. cli.enable_server_certificate_verification(false);
  9918. cli.set_keep_alive(true);
  9919. auto result = cli.Get("/hi");
  9920. ASSERT_TRUE(result);
  9921. EXPECT_EQ(StatusCode::OK_200, result->status);
  9922. result = cli.Get("/hi");
  9923. ASSERT_TRUE(result);
  9924. EXPECT_EQ(StatusCode::OK_200, result->status);
  9925. std::this_thread::sleep_for(std::chrono::seconds(2));
  9926. // Recoonect
  9927. result = cli.Get("/hi");
  9928. ASSERT_TRUE(result);
  9929. EXPECT_EQ(StatusCode::OK_200, result->status);
  9930. result = cli.Get("/hi");
  9931. ASSERT_TRUE(result);
  9932. EXPECT_EQ(StatusCode::OK_200, result->status);
  9933. }
  9934. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9936. ASSERT_TRUE(svr.is_valid());
  9937. svr.set_keep_alive_timeout(1);
  9938. std::string content = "reconnect";
  9939. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9940. res.set_content("Hello World!", "text/plain");
  9941. });
  9942. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. listen_thread.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. SSLClient cli(HOST, PORT);
  9950. cli.enable_server_certificate_verification(false);
  9951. cli.set_keep_alive(true);
  9952. auto result = cli.Post(
  9953. "/hi", content.size(),
  9954. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9955. sink.write(content.c_str(), content.size());
  9956. return true;
  9957. },
  9958. "text/plain");
  9959. ASSERT_TRUE(result);
  9960. EXPECT_EQ(200, result->status);
  9961. std::this_thread::sleep_for(std::chrono::seconds(2));
  9962. // Recoonect
  9963. result = cli.Post(
  9964. "/hi", content.size(),
  9965. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9966. sink.write(content.c_str(), content.size());
  9967. return true;
  9968. },
  9969. "text/plain");
  9970. ASSERT_TRUE(result);
  9971. EXPECT_EQ(200, result->status);
  9972. result = cli.Post(
  9973. "/hi", content.size(),
  9974. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9975. sink.write(content.c_str(), content.size());
  9976. return true;
  9977. },
  9978. "text/plain");
  9979. ASSERT_TRUE(result);
  9980. EXPECT_EQ(200, result->status);
  9981. }
  9982. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9983. using namespace httplib::tls;
  9984. {
  9985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9986. ASSERT_TRUE(svr.is_valid());
  9987. svr.Get("/sni", [&](const Request &req, Response &res) {
  9988. std::string expected = req.sni();
  9989. EXPECT_EQ(expected, req.get_param_value("expected"));
  9990. res.set_content("ok", "text/plain");
  9991. });
  9992. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9993. auto se = detail::scope_exit([&] {
  9994. svr.stop();
  9995. listen_thread.join();
  9996. ASSERT_FALSE(svr.is_running());
  9997. });
  9998. svr.wait_until_ready();
  9999. {
  10000. SSLClient cli("localhost", PORT);
  10001. cli.enable_server_certificate_verification(false);
  10002. auto res = cli.Get("/sni?expected=localhost");
  10003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10004. }
  10005. {
  10006. SSLClient cli("::1", PORT);
  10007. cli.enable_server_certificate_verification(false);
  10008. auto res = cli.Get("/sni?expected=");
  10009. // NOTE: This may fail if the server is listening on IPv4 only
  10010. // (e.g., when localhost resolves to 127.0.0.1 only)
  10011. if (res) {
  10012. EXPECT_EQ(StatusCode::OK_200, res->status);
  10013. } else {
  10014. EXPECT_EQ(Error::Connection, res.error());
  10015. }
  10016. }
  10017. }
  10018. }
  10019. #endif
  10020. TEST(ClientProblemDetectionTest, ContentProvider) {
  10021. Server svr;
  10022. size_t content_length = 1024 * 1024;
  10023. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10024. res.set_content_provider(
  10025. content_length, "text/plain",
  10026. [&](size_t offset, size_t length, DataSink &sink) {
  10027. auto out_len = std::min(length, static_cast<size_t>(1024));
  10028. std::string out(out_len, '@');
  10029. sink.write(out.data(), out_len);
  10030. return offset < 4096;
  10031. },
  10032. [](bool success) { ASSERT_FALSE(success); });
  10033. });
  10034. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10035. res.set_content_provider(
  10036. 0, "text/plain",
  10037. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10038. EXPECT_TRUE(false);
  10039. return true;
  10040. },
  10041. [](bool success) { ASSERT_FALSE(success); });
  10042. });
  10043. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10044. auto se = detail::scope_exit([&] {
  10045. svr.stop();
  10046. listen_thread.join();
  10047. ASSERT_FALSE(svr.is_running());
  10048. });
  10049. svr.wait_until_ready();
  10050. Client cli("localhost", PORT);
  10051. {
  10052. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10053. size_t /*data_length*/) { return false; });
  10054. ASSERT_FALSE(res);
  10055. }
  10056. {
  10057. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10058. size_t /*data_length*/) { return false; });
  10059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10060. }
  10061. }
  10062. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10063. // A provider that reports success without writing anything and without
  10064. // calling done() used to be handed the same offset and length again on every
  10065. // pass, so it spun for as long as the peer stayed connected.
  10066. Server svr;
  10067. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10068. res.set_content("ok", "text/plain");
  10069. });
  10070. auto port = svr.bind_to_any_port(HOST);
  10071. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10072. auto se = detail::scope_exit([&] {
  10073. svr.stop();
  10074. listen_thread.join();
  10075. ASSERT_FALSE(svr.is_running());
  10076. });
  10077. svr.wait_until_ready();
  10078. std::atomic<int> call_count{0};
  10079. Client cli(HOST, port);
  10080. auto res = cli.Post(
  10081. "/", 1024,
  10082. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10083. // Give up after enough passes to show the spin, so that losing the
  10084. // check below fails this test instead of hanging it.
  10085. return ++call_count < 100;
  10086. },
  10087. "text/plain");
  10088. ASSERT_FALSE(res);
  10089. EXPECT_EQ(Error::Write, res.error());
  10090. EXPECT_EQ(1, call_count.load());
  10091. }
  10092. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10093. // A writer only has to assign `write`. The other three used to be left as
  10094. // empty std::functions, so a provider calling one threw
  10095. // std::bad_function_call out of the thread running it and took the whole
  10096. // process down.
  10097. DataSink sink;
  10098. std::string written;
  10099. sink.write = [&](const char *data, size_t data_len) {
  10100. written.append(data, data_len);
  10101. return true;
  10102. };
  10103. EXPECT_TRUE(sink.is_writable());
  10104. sink.done();
  10105. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10106. EXPECT_TRUE(written.empty());
  10107. }
  10108. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10109. // A sink that cannot carry trailers still has to finish.
  10110. DataSink sink;
  10111. auto done_count = 0;
  10112. sink.done = [&]() { done_count++; };
  10113. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10114. EXPECT_EQ(1, done_count);
  10115. }
  10116. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10117. Server svr;
  10118. const std::string body(4096, 'x');
  10119. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10120. res.set_content_provider(body.size(), "text/plain",
  10121. [&](size_t offset, size_t length, DataSink &sink) {
  10122. sink.write(body.data() + offset, length);
  10123. sink.done();
  10124. return true;
  10125. });
  10126. });
  10127. auto port = svr.bind_to_any_port(HOST);
  10128. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10129. auto se = detail::scope_exit([&] {
  10130. svr.stop();
  10131. listen_thread.join();
  10132. ASSERT_FALSE(svr.is_running());
  10133. });
  10134. svr.wait_until_ready();
  10135. Client cli(HOST, port);
  10136. auto res = cli.Get("/");
  10137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10138. EXPECT_EQ(StatusCode::OK_200, res->status);
  10139. EXPECT_EQ(body, res->body);
  10140. }
  10141. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10142. Server svr;
  10143. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10144. res.set_content_provider(
  10145. 1024, "text/plain",
  10146. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10147. sink.write("hello", 5);
  10148. sink.done(); // short of the 1024 bytes the response promised
  10149. return true;
  10150. });
  10151. });
  10152. auto port = svr.bind_to_any_port(HOST);
  10153. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10154. auto se = detail::scope_exit([&] {
  10155. svr.stop();
  10156. listen_thread.join();
  10157. ASSERT_FALSE(svr.is_running());
  10158. });
  10159. svr.wait_until_ready();
  10160. Client cli(HOST, port);
  10161. cli.set_read_timeout(5, 0);
  10162. // The response is short of its Content-Length, so the client cannot read a
  10163. // complete body. What matters is that this returns at all: a no-op done()
  10164. // would leave the writer looping over a provider that never makes progress.
  10165. auto res = cli.Get("/");
  10166. EXPECT_FALSE(res);
  10167. }
  10168. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10169. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10170. // The compressed path builds the whole body before connecting, so this
  10171. // fails client-side and never reaches a server.
  10172. Client cli(HOST, PORT);
  10173. cli.set_compress(true);
  10174. auto res = cli.Post(
  10175. "/", 1024,
  10176. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10177. sink.write("hello", 5);
  10178. sink.done(); // short of the 1024 bytes the request announced
  10179. return true;
  10180. },
  10181. "text/plain");
  10182. ASSERT_FALSE(res);
  10183. EXPECT_EQ(Error::Write, res.error());
  10184. }
  10185. #endif
  10186. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10187. Server svr;
  10188. svr.set_error_handler([](Request const &, Response &res) -> void {
  10189. res.set_chunked_content_provider(
  10190. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10191. sink.os << "hello";
  10192. sink.os << "world";
  10193. sink.done();
  10194. return true;
  10195. });
  10196. });
  10197. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10198. auto se = detail::scope_exit([&] {
  10199. svr.stop();
  10200. listen_thread.join();
  10201. ASSERT_FALSE(svr.is_running());
  10202. });
  10203. svr.wait_until_ready();
  10204. Client cli("localhost", PORT);
  10205. auto res = cli.Get("/");
  10206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10207. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10208. EXPECT_EQ("helloworld", res->body);
  10209. }
  10210. TEST(LongPollingTest, ClientCloseDetection) {
  10211. Server svr;
  10212. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10213. res.set_chunked_content_provider(
  10214. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10215. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10216. sink.os << "hello";
  10217. auto count = 10;
  10218. while (count > 0 && sink.is_writable()) {
  10219. this_thread::sleep_for(chrono::milliseconds(10));
  10220. count--;
  10221. }
  10222. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10223. return true;
  10224. });
  10225. });
  10226. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10227. auto se = detail::scope_exit([&] {
  10228. svr.stop();
  10229. listen_thread.join();
  10230. ASSERT_FALSE(svr.is_running());
  10231. });
  10232. svr.wait_until_ready();
  10233. Client cli("localhost", PORT);
  10234. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10235. EXPECT_EQ("hello", string(data, data_length));
  10236. return false; // close the socket immediately.
  10237. });
  10238. ASSERT_FALSE(res);
  10239. }
  10240. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10241. Server svr;
  10242. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10243. res.set_chunked_content_provider(
  10244. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10245. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10246. sink.os << "hello";
  10247. EXPECT_TRUE(sink.os.good());
  10248. // Wait for the client to close the connection
  10249. auto count = 10;
  10250. while (count > 0 && sink.is_writable()) {
  10251. this_thread::sleep_for(chrono::milliseconds(10));
  10252. count--;
  10253. }
  10254. // After client disconnect, write repeatedly until the socket
  10255. // write actually fails (small writes may be absorbed by the
  10256. // kernel buffer)
  10257. std::string chunk(1024, 'x');
  10258. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10259. sink.os << chunk;
  10260. }
  10261. EXPECT_TRUE(sink.os.fail());
  10262. return true;
  10263. });
  10264. });
  10265. auto port = svr.bind_to_any_port("localhost");
  10266. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10267. auto se = detail::scope_exit([&] {
  10268. svr.stop();
  10269. listen_thread.join();
  10270. ASSERT_FALSE(svr.is_running());
  10271. });
  10272. svr.wait_until_ready();
  10273. Client cli("localhost", port);
  10274. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10275. EXPECT_EQ("hello", string(data, data_length));
  10276. return false; // close the socket immediately.
  10277. });
  10278. ASSERT_FALSE(res);
  10279. }
  10280. TEST(GetWithParametersTest, GetWithParameters) {
  10281. Server svr;
  10282. svr.Get("/", [&](const Request &req, Response &) {
  10283. EXPECT_EQ("world", req.get_param_value("hello"));
  10284. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10285. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10286. });
  10287. svr.Get("/params", [&](const Request &req, Response &) {
  10288. EXPECT_EQ("world", req.get_param_value("hello"));
  10289. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10290. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10291. });
  10292. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10293. EXPECT_EQ("resource-id", req.matches[1]);
  10294. EXPECT_EQ("foo", req.get_param_value("param1"));
  10295. EXPECT_EQ("bar", req.get_param_value("param2"));
  10296. });
  10297. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10298. EXPECT_EQ("user-id", req.path_params.at("id"));
  10299. EXPECT_EQ("foo", req.get_param_value("param1"));
  10300. EXPECT_EQ("bar", req.get_param_value("param2"));
  10301. });
  10302. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10303. auto se = detail::scope_exit([&] {
  10304. svr.stop();
  10305. listen_thread.join();
  10306. ASSERT_FALSE(svr.is_running());
  10307. });
  10308. svr.wait_until_ready();
  10309. {
  10310. Client cli(HOST, PORT);
  10311. Params params;
  10312. params.emplace("hello", "world");
  10313. params.emplace("hello2", "world2");
  10314. params.emplace("hello3", "world3");
  10315. auto res = cli.Get("/", params, Headers{});
  10316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10317. EXPECT_EQ(StatusCode::OK_200, res->status);
  10318. }
  10319. {
  10320. Client cli(HOST, PORT);
  10321. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10323. EXPECT_EQ(StatusCode::OK_200, res->status);
  10324. }
  10325. {
  10326. Client cli(HOST, PORT);
  10327. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10329. EXPECT_EQ(StatusCode::OK_200, res->status);
  10330. }
  10331. {
  10332. Client cli(HOST, PORT);
  10333. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10335. EXPECT_EQ(StatusCode::OK_200, res->status);
  10336. }
  10337. }
  10338. TEST(GetWithParametersTest, GetWithParameters2) {
  10339. Server svr;
  10340. svr.Get("/", [&](const Request &req, Response &res) {
  10341. auto text = req.get_param_value("hello");
  10342. res.set_content(text, "text/plain");
  10343. });
  10344. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10345. auto se = detail::scope_exit([&] {
  10346. svr.stop();
  10347. listen_thread.join();
  10348. ASSERT_FALSE(svr.is_running());
  10349. });
  10350. svr.wait_until_ready();
  10351. Client cli("localhost", PORT);
  10352. Params params;
  10353. params.emplace("hello", "world");
  10354. std::string body;
  10355. auto res = cli.Get("/", params, Headers{},
  10356. [&](const char *data, size_t data_length) {
  10357. body.append(data, data_length);
  10358. return true;
  10359. });
  10360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10361. EXPECT_EQ(StatusCode::OK_200, res->status);
  10362. EXPECT_EQ("world", body);
  10363. }
  10364. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10365. Server svr;
  10366. svr.Get("/search", [&](const Request &req, Response &res) {
  10367. auto q = req.get_param_value("q");
  10368. res.set_content(q, "text/plain");
  10369. });
  10370. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10371. auto se = detail::scope_exit([&] {
  10372. svr.stop();
  10373. listen_thread.join();
  10374. ASSERT_FALSE(svr.is_running());
  10375. });
  10376. svr.wait_until_ready();
  10377. Client cli("localhost", PORT);
  10378. // Verify that Get(path, params) works without requiring Headers argument
  10379. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10381. EXPECT_EQ(StatusCode::OK_200, res->status);
  10382. EXPECT_EQ("cpp-httplib", res->body);
  10383. }
  10384. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10385. auto host = "httpbingo.org";
  10386. auto path = std::string{"/range/32"};
  10387. #ifdef CPPHTTPLIB_SSL_ENABLED
  10388. SSLClient cli(host);
  10389. #else
  10390. Client cli(host);
  10391. #endif
  10392. cli.set_default_headers({make_range_header({{1, 10}})});
  10393. cli.set_connection_timeout(5);
  10394. {
  10395. auto res = cli.Get(path);
  10396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10397. EXPECT_EQ("bcdefghijk", res->body);
  10398. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10399. }
  10400. {
  10401. auto res = cli.Get(path);
  10402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10403. EXPECT_EQ("bcdefghijk", res->body);
  10404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10405. }
  10406. }
  10407. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10408. Server svr;
  10409. svr.set_default_headers({{"Hello", "World"}});
  10410. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10411. res.set_content("ok", "text/plain");
  10412. });
  10413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10414. auto se = detail::scope_exit([&] {
  10415. svr.stop();
  10416. listen_thread.join();
  10417. ASSERT_FALSE(svr.is_running());
  10418. });
  10419. svr.wait_until_ready();
  10420. Client cli("localhost", PORT);
  10421. auto res = cli.Get("/");
  10422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10423. EXPECT_EQ(StatusCode::OK_200, res->status);
  10424. EXPECT_EQ("ok", res->body);
  10425. EXPECT_EQ("World", res->get_header_value("Hello"));
  10426. }
  10427. #ifdef CPPHTTPLIB_SSL_ENABLED
  10428. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10430. ASSERT_TRUE(svr.is_valid());
  10431. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10432. std::this_thread::sleep_for(std::chrono::seconds(2));
  10433. res.set_content("a", "text/plain");
  10434. });
  10435. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10436. res.set_content("b", "text/plain");
  10437. });
  10438. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10439. auto se = detail::scope_exit([&] {
  10440. svr.stop();
  10441. listen_thread.join();
  10442. ASSERT_FALSE(svr.is_running());
  10443. });
  10444. svr.wait_until_ready();
  10445. SSLClient cli("localhost", PORT);
  10446. cli.enable_server_certificate_verification(false);
  10447. cli.set_keep_alive(true);
  10448. cli.set_read_timeout(std::chrono::seconds(1));
  10449. auto resa = cli.Get("/a");
  10450. ASSERT_TRUE(!resa);
  10451. EXPECT_EQ(Error::Read, resa.error());
  10452. auto resb = cli.Get("/b");
  10453. ASSERT_TRUE(resb);
  10454. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10455. EXPECT_EQ("b", resb->body);
  10456. }
  10457. // Closing an idle keep-alive connection sends close_notify and returns. The
  10458. // server must not wait for the client's close_notify: an idle client never
  10459. // sends one, so the worker would be held until the read timeout expires, and
  10460. // stop() would wait for it.
  10461. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10463. ASSERT_TRUE(svr.is_valid());
  10464. svr.set_keep_alive_timeout(1);
  10465. svr.set_read_timeout(10, 0);
  10466. svr.Get("/", [](const Request &, Response &res) {
  10467. res.set_content("ok", "text/plain");
  10468. });
  10469. auto port = svr.bind_to_any_port(HOST);
  10470. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10471. auto se = detail::scope_exit([&] {
  10472. if (listen_thread.joinable()) {
  10473. svr.stop();
  10474. listen_thread.join();
  10475. }
  10476. });
  10477. svr.wait_until_ready();
  10478. SSLClient cli(HOST, port);
  10479. cli.enable_server_certificate_verification(false);
  10480. cli.set_keep_alive(true);
  10481. auto res = cli.Get("/");
  10482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10483. EXPECT_EQ(StatusCode::OK_200, res->status);
  10484. // Stay idle past the keep-alive timeout so the server closes the connection.
  10485. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10486. auto start = std::chrono::steady_clock::now();
  10487. svr.stop();
  10488. listen_thread.join();
  10489. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10490. std::chrono::steady_clock::now() - start)
  10491. .count();
  10492. EXPECT_LT(elapsed, 3000);
  10493. }
  10494. #endif
  10495. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10496. protected:
  10497. ServerTestWithAI_PASSIVE()
  10498. : cli_(HOST, PORT)
  10499. #ifdef CPPHTTPLIB_SSL_ENABLED
  10500. ,
  10501. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10502. #endif
  10503. {
  10504. #ifdef CPPHTTPLIB_SSL_ENABLED
  10505. cli_.enable_server_certificate_verification(false);
  10506. #endif
  10507. }
  10508. virtual void SetUp() {
  10509. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10510. res.set_content("Hello World!", "text/plain");
  10511. });
  10512. t_ = thread(
  10513. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10514. svr_.wait_until_ready();
  10515. }
  10516. virtual void TearDown() {
  10517. svr_.stop();
  10518. t_.join();
  10519. }
  10520. #ifdef CPPHTTPLIB_SSL_ENABLED
  10521. SSLClient cli_;
  10522. SSLServer svr_;
  10523. #else
  10524. Client cli_;
  10525. Server svr_;
  10526. #endif
  10527. thread t_;
  10528. };
  10529. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10530. auto res = cli_.Get("/hi");
  10531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10532. EXPECT_EQ(StatusCode::OK_200, res->status);
  10533. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10534. EXPECT_EQ("Hello World!", res->body);
  10535. }
  10536. class ServerUpDownTest : public ::testing::Test {
  10537. protected:
  10538. ServerUpDownTest() : cli_(HOST, PORT) {}
  10539. virtual void SetUp() {
  10540. t_ = thread([&]() {
  10541. svr_.bind_to_any_port(HOST);
  10542. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10543. ASSERT_TRUE(svr_.listen_after_bind());
  10544. });
  10545. svr_.wait_until_ready();
  10546. }
  10547. virtual void TearDown() {
  10548. svr_.stop();
  10549. t_.join();
  10550. }
  10551. Client cli_;
  10552. Server svr_;
  10553. thread t_;
  10554. };
  10555. TEST_F(ServerUpDownTest, QuickStartStop) {
  10556. // Should not crash, especially when run with
  10557. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10558. }
  10559. class PayloadMaxLengthTest : public ::testing::Test {
  10560. protected:
  10561. PayloadMaxLengthTest()
  10562. : cli_(HOST, PORT)
  10563. #ifdef CPPHTTPLIB_SSL_ENABLED
  10564. ,
  10565. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10566. #endif
  10567. {
  10568. #ifdef CPPHTTPLIB_SSL_ENABLED
  10569. cli_.enable_server_certificate_verification(false);
  10570. #endif
  10571. }
  10572. virtual void SetUp() {
  10573. svr_.set_payload_max_length(8);
  10574. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10575. res.set_content("test", "text/plain");
  10576. });
  10577. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10578. svr_.wait_until_ready();
  10579. }
  10580. virtual void TearDown() {
  10581. svr_.stop();
  10582. t_.join();
  10583. }
  10584. #ifdef CPPHTTPLIB_SSL_ENABLED
  10585. SSLClient cli_;
  10586. SSLServer svr_;
  10587. #else
  10588. Client cli_;
  10589. Server svr_;
  10590. #endif
  10591. thread t_;
  10592. };
  10593. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10594. auto res = cli_.Post("/test", "123456789", "text/plain");
  10595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10596. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10597. res = cli_.Post("/test", "12345678", "text/plain");
  10598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10599. EXPECT_EQ(StatusCode::OK_200, res->status);
  10600. }
  10601. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10602. // Test chunked encoding with payload exceeding the 8-byte limit
  10603. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10604. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10606. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10607. }
  10608. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10609. // Test chunked encoding with payload within the 8-byte limit
  10610. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10611. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10613. EXPECT_EQ(StatusCode::OK_200, res->status);
  10614. }
  10615. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10616. // Test using send_request to send chunked data exceeding payload limit
  10617. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10618. "Host: " +
  10619. std::string(HOST) + ":" + std::to_string(PORT) +
  10620. "\r\n"
  10621. "Transfer-Encoding: chunked\r\n"
  10622. "Connection: close\r\n"
  10623. "\r\n"
  10624. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10625. "0123456789\r\n"
  10626. "0\r\n" // End chunk
  10627. "\r\n";
  10628. std::string response;
  10629. bool result = send_request(1, chunked_request, &response);
  10630. if (!result) {
  10631. // If send_request fails, it might be because the server closed the
  10632. // connection due to payload limit enforcement, which is acceptable
  10633. SUCCEED()
  10634. << "Server rejected oversized chunked request (connection closed)";
  10635. } else {
  10636. // If we got a response, check if it's an error response or connection was
  10637. // closed early Short response length indicates connection was closed due to
  10638. // payload limit
  10639. if (response.length() <= 10) {
  10640. SUCCEED() << "Server closed connection for oversized chunked request";
  10641. } else {
  10642. // Check for error status codes
  10643. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10644. response.find("Payload Too Large") != std::string::npos ||
  10645. response.find("400") != std::string::npos);
  10646. }
  10647. }
  10648. }
  10649. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10650. // Test request without Content-Length header exceeding payload limit
  10651. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10652. "Host: " +
  10653. std::string(HOST) + ":" +
  10654. std::to_string(PORT) +
  10655. "\r\n"
  10656. "Connection: close\r\n"
  10657. "\r\n";
  10658. // Add payload exceeding the 8-byte limit
  10659. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10660. request_without_content_length += large_payload;
  10661. std::string response;
  10662. bool result = send_request(1, request_without_content_length, &response);
  10663. if (!result) {
  10664. // If send_request fails, server likely closed connection due to payload
  10665. // limit
  10666. SUCCEED() << "Server rejected oversized request without Content-Length "
  10667. "(connection closed)";
  10668. } else {
  10669. // Check if server responded with error or closed connection early
  10670. if (response.length() <= 10) {
  10671. SUCCEED() << "Server closed connection for oversized request without "
  10672. "Content-Length";
  10673. } else {
  10674. // Check for error status codes
  10675. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10676. response.find("Payload Too Large") != std::string::npos ||
  10677. response.find("400") != std::string::npos);
  10678. }
  10679. }
  10680. }
  10681. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10682. // Test request without Content-Length header within payload limit
  10683. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10684. "Host: " +
  10685. std::string(HOST) + ":" +
  10686. std::to_string(PORT) +
  10687. "\r\n"
  10688. "Connection: close\r\n"
  10689. "\r\n";
  10690. // Add payload within the 8-byte limit
  10691. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10692. request_without_content_length += small_payload;
  10693. std::string response;
  10694. bool result = send_request(1, request_without_content_length, &response);
  10695. // For requests without Content-Length, the server may have different behavior
  10696. // The key is that it should not reject due to payload limit for small
  10697. // payloads
  10698. if (result) {
  10699. // Check for any HTTP response (success or error, but not connection closed)
  10700. if (response.length() > 10) {
  10701. SUCCEED()
  10702. << "Server processed request without Content-Length within limit";
  10703. } else {
  10704. // Short response might indicate connection closed, which is acceptable
  10705. SUCCEED() << "Server closed connection for request without "
  10706. "Content-Length (acceptable behavior)";
  10707. }
  10708. } else {
  10709. // Connection failure might be due to protocol requirements
  10710. SUCCEED() << "Connection issue with request without Content-Length "
  10711. "(environment-specific)";
  10712. }
  10713. }
  10714. class LargePayloadMaxLengthTest : public ::testing::Test {
  10715. protected:
  10716. LargePayloadMaxLengthTest()
  10717. : cli_(HOST, PORT)
  10718. #ifdef CPPHTTPLIB_SSL_ENABLED
  10719. ,
  10720. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10721. #endif
  10722. {
  10723. #ifdef CPPHTTPLIB_SSL_ENABLED
  10724. cli_.enable_server_certificate_verification(false);
  10725. #endif
  10726. }
  10727. virtual void SetUp() {
  10728. // Set 10MB payload limit
  10729. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10730. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10731. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10732. res.set_content("Large payload test", "text/plain");
  10733. });
  10734. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10735. svr_.wait_until_ready();
  10736. }
  10737. virtual void TearDown() {
  10738. svr_.stop();
  10739. t_.join();
  10740. }
  10741. #ifdef CPPHTTPLIB_SSL_ENABLED
  10742. SSLClient cli_;
  10743. SSLServer svr_;
  10744. #else
  10745. Client cli_;
  10746. Server svr_;
  10747. #endif
  10748. thread t_;
  10749. };
  10750. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10751. // Test chunked encoding with payload within 10MB limit
  10752. std::string medium_payload(5 * 1024 * 1024,
  10753. 'A'); // 5MB payload, within 10MB limit
  10754. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10756. EXPECT_EQ(StatusCode::OK_200, res->status);
  10757. }
  10758. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10759. // Test chunked encoding with payload exceeding 10MB limit
  10760. std::string large_payload(12 * 1024 * 1024,
  10761. 'B'); // 12MB payload, exceeds 10MB limit
  10762. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10763. // Server may either return 413 or close the connection
  10764. if (res) {
  10765. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10766. } else {
  10767. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10768. }
  10769. }
  10770. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10771. // Test request without Content-Length header within 10MB limit
  10772. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10773. "Host: " +
  10774. std::string(HOST) + ":" +
  10775. std::to_string(PORT) +
  10776. "\r\n"
  10777. "Connection: close\r\n"
  10778. "\r\n";
  10779. // Add 1MB payload (within 10MB limit)
  10780. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10781. request_without_content_length += medium_payload;
  10782. std::string response;
  10783. bool result = send_request(5, request_without_content_length, &response);
  10784. if (result) {
  10785. // Should get a proper HTTP response for payloads within limit
  10786. if (response.length() > 10) {
  10787. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10788. "10MB limit";
  10789. } else {
  10790. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10791. "Content-Length)";
  10792. }
  10793. } else {
  10794. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10795. }
  10796. }
  10797. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10798. // Test request without Content-Length header exceeding 10MB limit
  10799. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10800. "Host: " +
  10801. std::string(HOST) + ":" +
  10802. std::to_string(PORT) +
  10803. "\r\n"
  10804. "Connection: close\r\n"
  10805. "\r\n";
  10806. // Add 12MB payload (exceeds 10MB limit)
  10807. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10808. request_without_content_length += large_payload;
  10809. std::string response;
  10810. bool result = send_request(10, request_without_content_length, &response);
  10811. if (!result) {
  10812. // Server should close connection due to payload limit
  10813. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10814. "(connection closed)";
  10815. } else {
  10816. // Check for error response
  10817. if (response.length() <= 10) {
  10818. SUCCEED()
  10819. << "Server closed connection for 12MB request exceeding 10MB limit";
  10820. } else {
  10821. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10822. response.find("Payload Too Large") != std::string::npos ||
  10823. response.find("400") != std::string::npos);
  10824. }
  10825. }
  10826. }
  10827. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10828. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10829. // path.
  10830. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10831. Server svr;
  10832. const size_t LIMIT = 64 * 1024; // 64KB
  10833. svr.set_payload_max_length(LIMIT);
  10834. size_t total = 0;
  10835. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10836. const ContentReader &content_reader) {
  10837. content_reader([&](const char * /*data*/, size_t len) {
  10838. total += len;
  10839. return true;
  10840. });
  10841. res.status = 200;
  10842. res.set_content("stream_ok", "text/plain");
  10843. });
  10844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10845. auto se = detail::scope_exit([&] {
  10846. svr.stop();
  10847. thread.join();
  10848. ASSERT_FALSE(svr.is_running());
  10849. });
  10850. svr.wait_until_ready();
  10851. // Prepare 256KB raw data and gzip-compress it
  10852. std::string raw(256 * 1024, 'A');
  10853. std::string gz;
  10854. {
  10855. z_stream zs{};
  10856. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10857. Z_DEFAULT_STRATEGY);
  10858. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10859. zs.avail_in = static_cast<uInt>(raw.size());
  10860. char outbuf[4096];
  10861. int ret;
  10862. do {
  10863. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10864. zs.avail_out = sizeof(outbuf);
  10865. ret = deflate(&zs, Z_FINISH);
  10866. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10867. } while (ret != Z_STREAM_END);
  10868. deflateEnd(&zs);
  10869. }
  10870. Client cli(HOST, PORT);
  10871. cli.set_connection_timeout(std::chrono::seconds(5));
  10872. Headers headers = {{"Content-Encoding", "gzip"}};
  10873. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10874. "application/octet-stream");
  10875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10876. // Server must reject oversized decompressed payloads with 413.
  10877. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10878. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10879. EXPECT_LE(total, LIMIT);
  10880. }
  10881. #ifndef CPPHTTPLIB_SSL_ENABLED
  10882. // For a request with neither Content-Length nor Transfer-Encoding, the
  10883. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10884. // compressed wire bytes straight to the ContentReader without ever routing
  10885. // them through the decompressor, so payload_max_length_ only bounded the
  10886. // compressed size on the wire, not the decompressed size.
  10887. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10888. Server svr;
  10889. const size_t LIMIT = 64 * 1024; // 64KB
  10890. svr.set_payload_max_length(LIMIT);
  10891. size_t total = 0;
  10892. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10893. const ContentReader &content_reader) {
  10894. content_reader([&](const char * /*data*/, size_t len) {
  10895. total += len;
  10896. return true;
  10897. });
  10898. res.status = 200;
  10899. res.set_content("stream_ok", "text/plain");
  10900. });
  10901. auto port = svr.bind_to_any_port(HOST);
  10902. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10903. auto se = detail::scope_exit([&] {
  10904. svr.stop();
  10905. thread.join();
  10906. ASSERT_FALSE(svr.is_running());
  10907. });
  10908. svr.wait_until_ready();
  10909. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10910. // StreamingGzipDecompression test above.
  10911. std::string raw(256 * 1024, 'A');
  10912. std::string gz;
  10913. {
  10914. httplib::detail::gzip_compressor compressor;
  10915. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10916. [&](const char *chunk, size_t len) {
  10917. gz.append(chunk, len);
  10918. return true;
  10919. });
  10920. ASSERT_TRUE(result);
  10921. }
  10922. // Send the gzip body over raw TCP with neither Content-Length nor
  10923. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10924. // kicks in.
  10925. std::string req = "POST /stream HTTP/1.1\r\n"
  10926. "Host: " +
  10927. std::string(HOST) + ":" + std::to_string(port) +
  10928. "\r\n"
  10929. "Content-Encoding: gzip\r\n"
  10930. "Connection: close\r\n"
  10931. "\r\n" +
  10932. gz;
  10933. std::string response;
  10934. ASSERT_TRUE(send_request(5, req, &response, port));
  10935. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10936. EXPECT_LE(total, LIMIT);
  10937. }
  10938. #endif
  10939. #endif
  10940. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10941. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10942. // the payload must be passed through untouched instead of being rejected.
  10943. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10944. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10945. Server svr;
  10946. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10947. res.set_content(body, "image/jpeg");
  10948. res.set_header("Content-Encoding", "UTF-8");
  10949. });
  10950. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10951. res.set_content(body, "image/jpeg");
  10952. res.set_header("Content-Encoding", "identity");
  10953. });
  10954. svr.Post("/echo", [](const Request &req, Response &res) {
  10955. res.set_content(req.body, "image/jpeg");
  10956. });
  10957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10958. auto se = detail::scope_exit([&] {
  10959. svr.stop();
  10960. t.join();
  10961. ASSERT_FALSE(svr.is_running());
  10962. });
  10963. svr.wait_until_ready();
  10964. Client cli(HOST, PORT);
  10965. {
  10966. auto res = cli.Get("/image");
  10967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10968. EXPECT_EQ(StatusCode::OK_200, res->status);
  10969. EXPECT_EQ(body, res->body);
  10970. }
  10971. {
  10972. auto res = cli.Get("/identity");
  10973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10974. EXPECT_EQ(StatusCode::OK_200, res->status);
  10975. EXPECT_EQ(body, res->body);
  10976. }
  10977. {
  10978. // The same applies to a request body reaching the server.
  10979. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10980. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10982. EXPECT_EQ(StatusCode::OK_200, res->status);
  10983. EXPECT_EQ(body, res->body);
  10984. }
  10985. }
  10986. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10987. // gzip-encoded response even when the build has no zlib support.
  10988. static const char GZIPPED_HELLO_WORLD[] = {
  10989. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10990. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10991. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10992. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10993. // A content coding is a whole token, not something the field value merely
  10994. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10995. // as "fibre" look like Brotli, and turned a multi-coding value like
  10996. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10997. // it was never meant to see.
  10998. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10999. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11000. Server svr;
  11001. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11002. res.set_content(body, "image/jpeg");
  11003. res.set_header("Content-Encoding", "fibre");
  11004. });
  11005. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11006. res.set_content(body, "image/jpeg");
  11007. res.set_header("Content-Encoding", "gzip, br");
  11008. });
  11009. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11010. res.set_content(body, "image/jpeg");
  11011. res.set_header("Content-Encoding", "x-zstd-ish");
  11012. });
  11013. auto port = svr.bind_to_any_port(HOST);
  11014. thread t = thread([&]() { svr.listen_after_bind(); });
  11015. auto se = detail::scope_exit([&] {
  11016. svr.stop();
  11017. t.join();
  11018. ASSERT_FALSE(svr.is_running());
  11019. });
  11020. svr.wait_until_ready();
  11021. Client cli(HOST, port);
  11022. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11023. auto res = cli.Get(path);
  11024. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11025. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11026. // Not a coding we recognize, so the payload comes back untouched
  11027. EXPECT_EQ(body, res->body) << path;
  11028. }
  11029. }
  11030. // A content coding cpp-httplib recognizes but was not built with must be
  11031. // reported as such. Handing the still-compressed payload back to the caller
  11032. // would silently corrupt it.
  11033. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11034. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11035. Server svr;
  11036. // "image/jpeg" keeps the server from applying a content coding of its own,
  11037. // so the hand-crafted Content-Encoding below survives.
  11038. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11039. res.set_content(gzipped, "image/jpeg");
  11040. res.set_header("Content-Encoding", "gzip");
  11041. });
  11042. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11043. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11044. res.set_content(gzipped, "image/jpeg");
  11045. res.set_header("Content-Encoding", "GZIP");
  11046. });
  11047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. t.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. Client cli(HOST, PORT);
  11055. {
  11056. auto res = cli.Get("/gzipped");
  11057. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ("Hello World!", res->body);
  11060. #else
  11061. ASSERT_FALSE(res);
  11062. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11063. #endif
  11064. }
  11065. {
  11066. // open_stream() must behave the same way.
  11067. auto handle = cli.open_stream("GET", "/gzipped");
  11068. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11069. ASSERT_TRUE(handle.is_valid());
  11070. std::string received;
  11071. char buf[256];
  11072. ssize_t n;
  11073. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11074. received.append(buf, static_cast<size_t>(n));
  11075. }
  11076. EXPECT_EQ("Hello World!", received);
  11077. #else
  11078. EXPECT_FALSE(handle.is_valid());
  11079. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11080. #endif
  11081. }
  11082. {
  11083. // A differently-cased coding must not be mistaken for an unknown one, or
  11084. // the body would be handed back still compressed.
  11085. auto res = cli.Get("/gzipped-uppercase");
  11086. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11088. EXPECT_EQ("Hello World!", res->body);
  11089. #else
  11090. ASSERT_FALSE(res);
  11091. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11092. #endif
  11093. }
  11094. }
  11095. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11096. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11097. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11098. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11099. // body a second time and appending a second Content-Encoding field line, so
  11100. // clients that decode one coding per listed value handed back raw gzip bytes.
  11101. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11102. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11103. Server svr;
  11104. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11105. // keeps the server from applying a coding of its own.
  11106. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11107. res.set_content(gzipped, "text/plain");
  11108. res.set_header("Content-Encoding", "gzip");
  11109. });
  11110. auto port = svr.bind_to_any_port(HOST);
  11111. thread t = thread([&]() { svr.listen_after_bind(); });
  11112. auto se = detail::scope_exit([&] {
  11113. svr.stop();
  11114. t.join();
  11115. ASSERT_FALSE(svr.is_running());
  11116. });
  11117. svr.wait_until_ready();
  11118. Client cli(HOST, port);
  11119. Headers headers = {{"Accept-Encoding", "gzip"}};
  11120. auto res = cli.Get("/pre-gzipped", headers);
  11121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11122. EXPECT_EQ(StatusCode::OK_200, res->status);
  11123. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11124. EXPECT_EQ("Hello World!", res->body);
  11125. }
  11126. // A chunked provider settles its coding where the headers are written and
  11127. // reuses it at write time. Both ends of that have to hold: a handler's own
  11128. // Content-Encoding suppresses the coding, and a response without one is still
  11129. // compressed as it always was.
  11130. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11131. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11132. const std::string plain = "Hello World! Hello World! Hello World!";
  11133. Server svr;
  11134. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11135. res.set_header("Content-Encoding", "gzip");
  11136. res.set_chunked_content_provider(
  11137. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11138. sink.write(gzipped.data(), gzipped.size());
  11139. sink.done();
  11140. return true;
  11141. });
  11142. });
  11143. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11144. res.set_chunked_content_provider(
  11145. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11146. sink.write(plain.data(), plain.size());
  11147. sink.done();
  11148. return true;
  11149. });
  11150. });
  11151. auto port = svr.bind_to_any_port(HOST);
  11152. thread t = thread([&]() { svr.listen_after_bind(); });
  11153. auto se = detail::scope_exit([&] {
  11154. svr.stop();
  11155. t.join();
  11156. ASSERT_FALSE(svr.is_running());
  11157. });
  11158. svr.wait_until_ready();
  11159. Client cli(HOST, port);
  11160. Headers headers = {{"Accept-Encoding", "gzip"}};
  11161. {
  11162. auto res = cli.Get("/pre-gzipped", headers);
  11163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11164. EXPECT_EQ(StatusCode::OK_200, res->status);
  11165. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11166. EXPECT_EQ("Hello World!", res->body);
  11167. }
  11168. {
  11169. auto res = cli.Get("/negotiated", headers);
  11170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11171. EXPECT_EQ(StatusCode::OK_200, res->status);
  11172. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11173. EXPECT_EQ(plain, res->body);
  11174. }
  11175. }
  11176. #endif
  11177. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11178. // the same message as the comma-joined one, so both have to be read the same
  11179. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11180. // single gzip coding, and a body the sender says was encoded twice was handed
  11181. // back after one pass, still compressed but presented as decoded.
  11182. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11183. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11184. Server svr;
  11185. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11186. res.set_content(body, "image/jpeg");
  11187. res.headers.emplace("Content-Encoding", "gzip");
  11188. res.headers.emplace("Content-Encoding", "gzip");
  11189. });
  11190. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11191. res.set_content(body, "image/jpeg");
  11192. res.set_header("Content-Encoding", "gzip, gzip");
  11193. });
  11194. auto port = svr.bind_to_any_port(HOST);
  11195. thread t = thread([&]() { svr.listen_after_bind(); });
  11196. auto se = detail::scope_exit([&] {
  11197. svr.stop();
  11198. t.join();
  11199. ASSERT_FALSE(svr.is_running());
  11200. });
  11201. svr.wait_until_ready();
  11202. Client cli(HOST, port);
  11203. // Two codings is not something cpp-httplib decodes, so both representations
  11204. // take the pass-through path rather than one of them being gunzipped once.
  11205. for (const char *path : {"/split", "/joined"}) {
  11206. auto res = cli.Get(path);
  11207. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11208. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11209. EXPECT_EQ(body, res->body) << path;
  11210. }
  11211. }
  11212. // Regression test for DoS vulnerability: a malicious server sending a response
  11213. // without Content-Length header must not cause unbounded memory consumption on
  11214. // the client side. The client should stop reading after a reasonable limit,
  11215. // similar to the server-side set_payload_max_length protection.
  11216. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11217. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11218. #ifndef _WIN32
  11219. signal(SIGPIPE, SIG_IGN);
  11220. #endif
  11221. auto server_thread = std::thread([] {
  11222. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11223. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11224. default_socket_options(srv);
  11225. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11226. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11227. sockaddr_in addr{};
  11228. addr.sin_family = AF_INET;
  11229. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11230. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11231. int opt = 1;
  11232. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11233. #ifdef _WIN32
  11234. reinterpret_cast<const char *>(&opt),
  11235. #else
  11236. &opt,
  11237. #endif
  11238. sizeof(opt));
  11239. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11240. ::listen(srv, 1);
  11241. sockaddr_in cli_addr{};
  11242. socklen_t cli_len = sizeof(cli_addr);
  11243. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11244. if (cli != INVALID_SOCKET) {
  11245. char buf[4096];
  11246. ::recv(cli, buf, sizeof(buf), 0);
  11247. // Malicious response: no Content-Length, no chunked encoding
  11248. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11249. "Connection: close\r\n"
  11250. "\r\n";
  11251. ::send(cli,
  11252. #ifdef _WIN32
  11253. static_cast<const char *>(response_header.c_str()),
  11254. static_cast<int>(response_header.size()),
  11255. #else
  11256. response_header.c_str(), response_header.size(),
  11257. #endif
  11258. 0);
  11259. // Send 10MB of data
  11260. std::string chunk(64 * 1024, 'A');
  11261. size_t total_sent = 0;
  11262. while (total_sent < MALICIOUS_DATA_SIZE) {
  11263. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11264. auto sent = ::send(cli,
  11265. #ifdef _WIN32
  11266. static_cast<const char *>(chunk.c_str()),
  11267. static_cast<int>(to_send),
  11268. #else
  11269. chunk.c_str(), to_send,
  11270. #endif
  11271. 0);
  11272. if (sent <= 0) break;
  11273. total_sent += static_cast<size_t>(sent);
  11274. }
  11275. detail::close_socket(cli);
  11276. }
  11277. detail::close_socket(srv);
  11278. });
  11279. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11280. size_t total_read = 0;
  11281. {
  11282. Client cli("127.0.0.1", PORT + 2);
  11283. cli.set_read_timeout(5, 0);
  11284. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11285. auto stream = cli.open_stream("GET", "/malicious");
  11286. ASSERT_TRUE(stream.is_valid());
  11287. char buffer[64 * 1024];
  11288. ssize_t n;
  11289. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11290. total_read += static_cast<size_t>(n);
  11291. }
  11292. } // StreamHandle and Client destroyed here, closing the socket
  11293. server_thread.join();
  11294. // With set_payload_max_length, the client must stop reading before consuming
  11295. // all 10MB. The read loop should be cut off at or near the configured limit.
  11296. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11297. << "Client read " << total_read << " bytes, exceeding the configured "
  11298. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11299. }
  11300. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11301. // the entire response body without truncation.
  11302. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11303. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11304. #ifndef _WIN32
  11305. signal(SIGPIPE, SIG_IGN);
  11306. #endif
  11307. auto server_thread = std::thread([] {
  11308. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11309. default_socket_options(srv);
  11310. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11311. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11312. sockaddr_in addr{};
  11313. addr.sin_family = AF_INET;
  11314. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11315. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11316. int opt = 1;
  11317. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11318. #ifdef _WIN32
  11319. reinterpret_cast<const char *>(&opt),
  11320. #else
  11321. &opt,
  11322. #endif
  11323. sizeof(opt));
  11324. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11325. ::listen(srv, 1);
  11326. sockaddr_in cli_addr{};
  11327. socklen_t cli_len = sizeof(cli_addr);
  11328. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11329. if (cli != INVALID_SOCKET) {
  11330. char buf[4096];
  11331. ::recv(cli, buf, sizeof(buf), 0);
  11332. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11333. "Connection: close\r\n"
  11334. "\r\n";
  11335. ::send(cli,
  11336. #ifdef _WIN32
  11337. static_cast<const char *>(response_header.c_str()),
  11338. static_cast<int>(response_header.size()),
  11339. #else
  11340. response_header.c_str(), response_header.size(),
  11341. #endif
  11342. 0);
  11343. std::string chunk(64 * 1024, 'A');
  11344. size_t total_sent = 0;
  11345. while (total_sent < DATA_SIZE) {
  11346. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11347. auto sent = ::send(cli,
  11348. #ifdef _WIN32
  11349. static_cast<const char *>(chunk.c_str()),
  11350. static_cast<int>(to_send),
  11351. #else
  11352. chunk.c_str(), to_send,
  11353. #endif
  11354. 0);
  11355. if (sent <= 0) break;
  11356. total_sent += static_cast<size_t>(sent);
  11357. }
  11358. #ifdef _WIN32
  11359. ::shutdown(cli, SD_SEND);
  11360. #else
  11361. ::shutdown(cli, SHUT_WR);
  11362. #endif
  11363. // Drain until the client closes its end, ensuring all data is delivered
  11364. char drain[1024];
  11365. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11366. detail::close_socket(cli);
  11367. }
  11368. detail::close_socket(srv);
  11369. });
  11370. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11371. size_t total_read = 0;
  11372. {
  11373. Client cli("127.0.0.1", PORT + 2);
  11374. cli.set_read_timeout(5, 0);
  11375. cli.set_payload_max_length(0); // 0 means no limit
  11376. auto stream = cli.open_stream("GET", "/data");
  11377. ASSERT_TRUE(stream.is_valid());
  11378. char buffer[64 * 1024];
  11379. ssize_t n;
  11380. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11381. total_read += static_cast<size_t>(n);
  11382. }
  11383. }
  11384. server_thread.join();
  11385. EXPECT_EQ(total_read, DATA_SIZE)
  11386. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11387. << " bytes without truncation, but only read " << total_read << " bytes.";
  11388. }
  11389. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11390. // enormous Content-Length must not cause the client to pre-allocate a huge
  11391. // response body buffer. The reservation is capped at payload_max_length_, and
  11392. // the read itself fails when the body exceeds the limit.
  11393. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11394. #ifndef _WIN32
  11395. signal(SIGPIPE, SIG_IGN);
  11396. #endif
  11397. auto server_thread = std::thread([] {
  11398. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11399. default_socket_options(srv);
  11400. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11401. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11402. sockaddr_in addr{};
  11403. addr.sin_family = AF_INET;
  11404. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11405. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11406. int opt = 1;
  11407. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11408. #ifdef _WIN32
  11409. reinterpret_cast<const char *>(&opt),
  11410. #else
  11411. &opt,
  11412. #endif
  11413. sizeof(opt));
  11414. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11415. ::listen(srv, 1);
  11416. sockaddr_in cli_addr{};
  11417. socklen_t cli_len = sizeof(cli_addr);
  11418. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11419. if (cli != INVALID_SOCKET) {
  11420. char buf[4096];
  11421. ::recv(cli, buf, sizeof(buf), 0);
  11422. // Malicious response: claim a 20GB body but send only a tiny payload.
  11423. std::string response = "HTTP/1.1 200 OK\r\n"
  11424. "Content-Length: 20000000000\r\n"
  11425. "\r\n"
  11426. "abc";
  11427. ::send(cli,
  11428. #ifdef _WIN32
  11429. static_cast<const char *>(response.c_str()),
  11430. static_cast<int>(response.size()),
  11431. #else
  11432. response.c_str(), response.size(),
  11433. #endif
  11434. 0);
  11435. detail::close_socket(cli);
  11436. }
  11437. detail::close_socket(srv);
  11438. });
  11439. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11440. {
  11441. Client cli("127.0.0.1", PORT + 2);
  11442. cli.set_read_timeout(5, 0);
  11443. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11444. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11445. // (server claims more bytes than payload_max_length permits), but it must
  11446. // not exhaust memory before getting there.
  11447. auto res = cli.Get("/malicious");
  11448. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11449. }
  11450. server_thread.join();
  11451. }
  11452. // Verify that content_receiver bypasses the default payload_max_length,
  11453. // allowing streaming downloads larger than 100MB without requiring an explicit
  11454. // set_payload_max_length call.
  11455. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11456. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11457. #ifndef _WIN32
  11458. signal(SIGPIPE, SIG_IGN);
  11459. #endif
  11460. auto server_thread = std::thread([] {
  11461. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11462. default_socket_options(srv);
  11463. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11464. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11465. sockaddr_in addr{};
  11466. addr.sin_family = AF_INET;
  11467. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11468. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11469. int opt = 1;
  11470. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11471. #ifdef _WIN32
  11472. reinterpret_cast<const char *>(&opt),
  11473. #else
  11474. &opt,
  11475. #endif
  11476. sizeof(opt));
  11477. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11478. ::listen(srv, 1);
  11479. sockaddr_in cli_addr{};
  11480. socklen_t cli_len = sizeof(cli_addr);
  11481. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11482. if (cli != INVALID_SOCKET) {
  11483. char buf[4096];
  11484. ::recv(cli, buf, sizeof(buf), 0);
  11485. // Response with Content-Length larger than default 100MB limit
  11486. auto content_length = std::to_string(DATA_SIZE);
  11487. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11488. "Content-Length: " +
  11489. content_length +
  11490. "\r\n"
  11491. "Connection: close\r\n"
  11492. "\r\n";
  11493. ::send(cli,
  11494. #ifdef _WIN32
  11495. static_cast<const char *>(response_header.c_str()),
  11496. static_cast<int>(response_header.size()),
  11497. #else
  11498. response_header.c_str(), response_header.size(),
  11499. #endif
  11500. 0);
  11501. std::string chunk(64 * 1024, 'A');
  11502. size_t total_sent = 0;
  11503. while (total_sent < DATA_SIZE) {
  11504. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11505. auto sent = ::send(cli,
  11506. #ifdef _WIN32
  11507. static_cast<const char *>(chunk.c_str()),
  11508. static_cast<int>(to_send),
  11509. #else
  11510. chunk.c_str(), to_send,
  11511. #endif
  11512. 0);
  11513. if (sent <= 0) break;
  11514. total_sent += static_cast<size_t>(sent);
  11515. }
  11516. detail::close_socket(cli);
  11517. }
  11518. detail::close_socket(srv);
  11519. });
  11520. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11521. size_t total_received = 0;
  11522. {
  11523. Client cli("127.0.0.1", PORT + 2);
  11524. cli.set_read_timeout(10, 0);
  11525. // Do NOT call set_payload_max_length — use the default 100MB limit
  11526. auto res =
  11527. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11528. total_received += data_length;
  11529. return true;
  11530. });
  11531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11532. EXPECT_EQ(StatusCode::OK_200, res->status);
  11533. }
  11534. server_thread.join();
  11535. EXPECT_EQ(total_received, DATA_SIZE)
  11536. << "With content_receiver, the client should read all " << DATA_SIZE
  11537. << " bytes despite the default 100MB payload_max_length, but only read "
  11538. << total_received << " bytes.";
  11539. }
  11540. // Verify that an explicit set_payload_max_length smaller than the response is
  11541. // enforced even when a content_receiver is used.
  11542. TEST(ClientVulnerabilityTest,
  11543. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11544. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11545. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11546. #ifndef _WIN32
  11547. signal(SIGPIPE, SIG_IGN);
  11548. #endif
  11549. auto server_thread = std::thread([] {
  11550. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11551. default_socket_options(srv);
  11552. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11553. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11554. sockaddr_in addr{};
  11555. addr.sin_family = AF_INET;
  11556. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11557. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11558. int opt = 1;
  11559. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11560. #ifdef _WIN32
  11561. reinterpret_cast<const char *>(&opt),
  11562. #else
  11563. &opt,
  11564. #endif
  11565. sizeof(opt));
  11566. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11567. ::listen(srv, 1);
  11568. sockaddr_in cli_addr{};
  11569. socklen_t cli_len = sizeof(cli_addr);
  11570. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11571. if (cli != INVALID_SOCKET) {
  11572. char buf[4096];
  11573. ::recv(cli, buf, sizeof(buf), 0);
  11574. auto content_length = std::to_string(DATA_SIZE);
  11575. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11576. "Content-Length: " +
  11577. content_length +
  11578. "\r\n"
  11579. "Connection: close\r\n"
  11580. "\r\n";
  11581. ::send(cli,
  11582. #ifdef _WIN32
  11583. static_cast<const char *>(response_header.c_str()),
  11584. static_cast<int>(response_header.size()),
  11585. #else
  11586. response_header.c_str(), response_header.size(),
  11587. #endif
  11588. 0);
  11589. std::string chunk(64 * 1024, 'A');
  11590. size_t total_sent = 0;
  11591. while (total_sent < DATA_SIZE) {
  11592. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11593. auto sent = ::send(cli,
  11594. #ifdef _WIN32
  11595. static_cast<const char *>(chunk.c_str()),
  11596. static_cast<int>(to_send),
  11597. #else
  11598. chunk.c_str(), to_send,
  11599. #endif
  11600. 0);
  11601. if (sent <= 0) break;
  11602. total_sent += static_cast<size_t>(sent);
  11603. }
  11604. detail::close_socket(cli);
  11605. }
  11606. detail::close_socket(srv);
  11607. });
  11608. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11609. size_t total_received = 0;
  11610. {
  11611. Client cli("127.0.0.1", PORT + 2);
  11612. cli.set_read_timeout(10, 0);
  11613. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11614. auto res =
  11615. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11616. total_received += data_length;
  11617. return true;
  11618. });
  11619. // Should fail because 200MB exceeds the explicit 150MB limit
  11620. EXPECT_FALSE(res);
  11621. }
  11622. server_thread.join();
  11623. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11624. << "Client with content_receiver should respect the explicit "
  11625. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11626. << total_received << " bytes.";
  11627. }
  11628. // Verify that an explicit set_payload_max_length larger than the response
  11629. // allows the content_receiver to read all data successfully.
  11630. TEST(ClientVulnerabilityTest,
  11631. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11632. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11633. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11634. #ifndef _WIN32
  11635. signal(SIGPIPE, SIG_IGN);
  11636. #endif
  11637. auto server_thread = std::thread([] {
  11638. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11639. default_socket_options(srv);
  11640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11642. sockaddr_in addr{};
  11643. addr.sin_family = AF_INET;
  11644. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11645. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11646. int opt = 1;
  11647. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11648. #ifdef _WIN32
  11649. reinterpret_cast<const char *>(&opt),
  11650. #else
  11651. &opt,
  11652. #endif
  11653. sizeof(opt));
  11654. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11655. ::listen(srv, 1);
  11656. sockaddr_in cli_addr{};
  11657. socklen_t cli_len = sizeof(cli_addr);
  11658. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11659. if (cli != INVALID_SOCKET) {
  11660. char buf[4096];
  11661. ::recv(cli, buf, sizeof(buf), 0);
  11662. auto content_length = std::to_string(DATA_SIZE);
  11663. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11664. "Content-Length: " +
  11665. content_length +
  11666. "\r\n"
  11667. "Connection: close\r\n"
  11668. "\r\n";
  11669. ::send(cli,
  11670. #ifdef _WIN32
  11671. static_cast<const char *>(response_header.c_str()),
  11672. static_cast<int>(response_header.size()),
  11673. #else
  11674. response_header.c_str(), response_header.size(),
  11675. #endif
  11676. 0);
  11677. std::string chunk(64 * 1024, 'A');
  11678. size_t total_sent = 0;
  11679. while (total_sent < DATA_SIZE) {
  11680. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11681. auto sent = ::send(cli,
  11682. #ifdef _WIN32
  11683. static_cast<const char *>(chunk.c_str()),
  11684. static_cast<int>(to_send),
  11685. #else
  11686. chunk.c_str(), to_send,
  11687. #endif
  11688. 0);
  11689. if (sent <= 0) break;
  11690. total_sent += static_cast<size_t>(sent);
  11691. }
  11692. #ifdef _WIN32
  11693. ::shutdown(cli, SD_SEND);
  11694. #else
  11695. ::shutdown(cli, SHUT_WR);
  11696. #endif
  11697. char drain[1024];
  11698. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11699. detail::close_socket(cli);
  11700. }
  11701. detail::close_socket(srv);
  11702. });
  11703. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11704. size_t total_received = 0;
  11705. {
  11706. Client cli("127.0.0.1", PORT + 2);
  11707. cli.set_read_timeout(10, 0);
  11708. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11709. auto res =
  11710. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11711. total_received += data_length;
  11712. return true;
  11713. });
  11714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11715. EXPECT_EQ(StatusCode::OK_200, res->status);
  11716. }
  11717. server_thread.join();
  11718. EXPECT_EQ(total_received, DATA_SIZE)
  11719. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11720. << " bytes (larger than " << DATA_SIZE
  11721. << " bytes response), content_receiver should read all data, but only "
  11722. "read "
  11723. << total_received << " bytes.";
  11724. }
  11725. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11726. // Regression test for "zip bomb" attack on the client side: a malicious server
  11727. // sends a small gzip-compressed response that decompresses to a huge payload.
  11728. // The client must enforce payload_max_length on the decompressed size.
  11729. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11730. constexpr size_t DECOMPRESSED_SIZE =
  11731. 10 * 1024 * 1024; // 10MB after decompression
  11732. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11733. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11734. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11735. std::string compressed;
  11736. {
  11737. httplib::detail::gzip_compressor compressor;
  11738. bool ok =
  11739. compressor.compress(uncompressed.data(), uncompressed.size(),
  11740. /*last=*/true, [&](const char *buf, size_t len) {
  11741. compressed.append(buf, len);
  11742. return true;
  11743. });
  11744. ASSERT_TRUE(ok);
  11745. }
  11746. // Sanity: compressed data should be much smaller than the decompressed size
  11747. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11748. #ifndef _WIN32
  11749. signal(SIGPIPE, SIG_IGN);
  11750. #endif
  11751. // Set up the listening socket in the main thread so the server is guaranteed
  11752. // to be ready before the client connects (eliminates race condition).
  11753. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11754. default_socket_options(srv);
  11755. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11756. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11757. sockaddr_in addr{};
  11758. addr.sin_family = AF_INET;
  11759. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11760. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11761. int opt = 1;
  11762. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11763. #ifdef _WIN32
  11764. reinterpret_cast<const char *>(&opt),
  11765. #else
  11766. &opt,
  11767. #endif
  11768. sizeof(opt));
  11769. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11770. ASSERT_EQ(0, ::listen(srv, 1));
  11771. auto server_thread = std::thread([&compressed, srv] {
  11772. sockaddr_in cli_addr{};
  11773. socklen_t cli_len = sizeof(cli_addr);
  11774. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11775. if (cli != INVALID_SOCKET) {
  11776. // Read the full HTTP request (until \r\n\r\n)
  11777. char buf[4096];
  11778. size_t total = 0;
  11779. while (total < sizeof(buf)) {
  11780. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11781. if (n <= 0) break;
  11782. total += static_cast<size_t>(n);
  11783. // Check for end of headers
  11784. if (total >= 4) {
  11785. std::string req(buf, total);
  11786. if (req.find("\r\n\r\n") != std::string::npos) break;
  11787. }
  11788. }
  11789. // Malicious response: gzip-compressed body, no Content-Length
  11790. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11791. "Content-Encoding: gzip\r\n"
  11792. "Connection: close\r\n"
  11793. "\r\n";
  11794. ::send(cli,
  11795. #ifdef _WIN32
  11796. static_cast<const char *>(response_header.c_str()),
  11797. static_cast<int>(response_header.size()),
  11798. #else
  11799. response_header.c_str(), response_header.size(),
  11800. #endif
  11801. 0);
  11802. // Send the compressed payload (small on the wire, huge when decompressed)
  11803. size_t total_sent = 0;
  11804. while (total_sent < compressed.size()) {
  11805. auto to_send = std::min(compressed.size() - total_sent,
  11806. static_cast<size_t>(64 * 1024));
  11807. auto sent =
  11808. ::send(cli,
  11809. #ifdef _WIN32
  11810. static_cast<const char *>(compressed.c_str() + total_sent),
  11811. static_cast<int>(to_send),
  11812. #else
  11813. compressed.c_str() + total_sent, to_send,
  11814. #endif
  11815. 0);
  11816. if (sent <= 0) break;
  11817. total_sent += static_cast<size_t>(sent);
  11818. }
  11819. detail::close_socket(cli);
  11820. }
  11821. });
  11822. auto se = detail::scope_exit([&] {
  11823. detail::close_socket(srv);
  11824. server_thread.join();
  11825. });
  11826. size_t total_decompressed = 0;
  11827. {
  11828. Client cli("127.0.0.1", PORT + 3);
  11829. cli.set_read_timeout(5, 0);
  11830. cli.set_decompress(true);
  11831. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11832. auto stream = cli.open_stream("GET", "/zipbomb");
  11833. ASSERT_TRUE(stream.is_valid());
  11834. char buffer[64 * 1024];
  11835. ssize_t n;
  11836. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11837. total_decompressed += static_cast<size_t>(n);
  11838. }
  11839. }
  11840. // The decompressed size must be capped by payload_max_length. Without
  11841. // protection, the client would decompress the full 10MB from a tiny
  11842. // compressed payload, enabling a zip bomb DoS attack.
  11843. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11844. << "Client decompressed " << total_decompressed
  11845. << " bytes from a gzip response. The decompressed size should be "
  11846. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11847. }
  11848. #endif
  11849. TEST(HostAndPortPropertiesTest, NoSSL) {
  11850. httplib::Client cli("www.google.com", 1234);
  11851. ASSERT_EQ("www.google.com", cli.host());
  11852. ASSERT_EQ(1234, cli.port());
  11853. }
  11854. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11855. httplib::Client cli("www.google.com:1234");
  11856. ASSERT_EQ("www.google.com", cli.host());
  11857. ASSERT_EQ(1234, cli.port());
  11858. }
  11859. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11860. // Port number that overflows int — should not crash, client becomes invalid
  11861. httplib::Client cli("http://www.google.com:99999999999999999999");
  11862. ASSERT_FALSE(cli.is_valid());
  11863. }
  11864. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11865. // Port 99999 exceeds valid range (1-65535) — should not crash
  11866. httplib::Client cli("http://www.google.com:99999");
  11867. ASSERT_FALSE(cli.is_valid());
  11868. }
  11869. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11870. httplib::Client cli("http://www.google.com:80abc");
  11871. ASSERT_FALSE(cli.is_valid());
  11872. }
  11873. #ifdef CPPHTTPLIB_SSL_ENABLED
  11874. TEST(HostAndPortPropertiesTest, SSL) {
  11875. httplib::SSLClient cli("www.google.com");
  11876. ASSERT_EQ("www.google.com", cli.host());
  11877. ASSERT_EQ(443, cli.port());
  11878. }
  11879. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11880. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11881. std::string cert;
  11882. read_file(CA_CERT_FILE, cert);
  11883. httplib::SSLClient httplib_client("www.google.com");
  11884. // Load CA store first time
  11885. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11886. // Load CA store second time (update)
  11887. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11888. // Verify client is still valid and can make connections
  11889. httplib_client.enable_server_certificate_verification(true);
  11890. auto res = httplib_client.Get("/");
  11891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11892. // Google may return 200 or 301 depending on various factors
  11893. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11894. res->status == StatusCode::MovedPermanently_301);
  11895. }
  11896. TEST(SSLClientTest, ServerNameIndication_Online) {
  11897. auto host = "httpbingo.org";
  11898. auto path = std::string{"/get"};
  11899. SSLClient cli(host, 443);
  11900. auto res = cli.Get(path);
  11901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11902. ASSERT_EQ(StatusCode::OK_200, res->status);
  11903. }
  11904. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11905. // Use a site that will cause SSL verification failure due to self-signed cert
  11906. SSLClient cli("self-signed.badssl.com", 443);
  11907. cli.enable_server_certificate_verification(true);
  11908. auto res = cli.Get("/");
  11909. ASSERT_TRUE(!res);
  11910. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11911. // Verify backend error is captured for SSLServerVerification
  11912. // This occurs when certificate verification fails
  11913. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11914. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11915. EXPECT_NE(0UL, res.ssl_backend_error());
  11916. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11917. // For OpenSSL, ssl_error is 0 for verification errors
  11918. EXPECT_EQ(0, res.ssl_error());
  11919. #if !defined(_WIN32) || \
  11920. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11921. // On non-Windows or when Windows Schannel is disabled, the error comes
  11922. // from OpenSSL's verification
  11923. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11924. res.ssl_backend_error());
  11925. #endif
  11926. #endif
  11927. }
  11928. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11929. // Use a site where hostname doesn't match the certificate
  11930. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11931. SSLClient cli("wrong.host.badssl.com", 443);
  11932. cli.enable_server_certificate_verification(true);
  11933. cli.enable_server_hostname_verification(true);
  11934. auto res = cli.Get("/");
  11935. ASSERT_TRUE(!res);
  11936. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11937. // Verify backend error is captured for hostname verification failure
  11938. EXPECT_NE(0UL, res.ssl_backend_error());
  11939. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11940. // For OpenSSL, ssl_error is 0 for verification errors
  11941. EXPECT_EQ(0, res.ssl_error());
  11942. #if !defined(_WIN32) || \
  11943. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11944. // On non-Windows or when Windows Schannel is disabled, the error comes
  11945. // from OpenSSL's hostname verification
  11946. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11947. res.ssl_backend_error());
  11948. #endif
  11949. #endif
  11950. }
  11951. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11952. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11953. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11954. SSLClient cli("www.google.com", 443);
  11955. cli.enable_server_certificate_verification(true);
  11956. auto res = cli.Get("/");
  11957. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11958. }
  11959. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11960. SSLClient cli("www.google.com", 443);
  11961. cli.enable_server_certificate_verification(true);
  11962. cli.enable_windows_certificate_verification(false);
  11963. auto res = cli.Get("/");
  11964. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11965. }
  11966. // The server sends an intermediate cross-signed by a root Windows trusts,
  11967. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11968. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11969. SSLClient cli("accounts.spotify.com", 443);
  11970. auto res = cli.Get("/");
  11971. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11972. << " ssl_backend_error=" << res.ssl_backend_error();
  11973. }
  11974. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  11975. // policy status, which no backend reports for a self-signed certificate.
  11976. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11977. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11978. ASSERT_TRUE(svr.is_valid());
  11979. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11980. auto se = detail::scope_exit([&] {
  11981. svr.stop();
  11982. t.join();
  11983. ASSERT_FALSE(svr.is_running());
  11984. });
  11985. svr.wait_until_ready();
  11986. SSLClient cli("127.0.0.1", PORT);
  11987. cli.set_connection_timeout(30);
  11988. auto res = cli.Get("/");
  11989. ASSERT_FALSE(res);
  11990. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11991. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  11992. }
  11993. #endif
  11994. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11995. Client cli("https://google.com");
  11996. auto res = cli.Get("/");
  11997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11998. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11999. }
  12000. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12001. SSLClient cli("google.com");
  12002. cli.set_ca_cert_path(CA_CERT_FILE);
  12003. auto res = cli.Get("/");
  12004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12005. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12006. }
  12007. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12008. SSLClient cli("google.com");
  12009. cli.enable_server_certificate_verification(true);
  12010. cli.set_ca_cert_path("hello");
  12011. auto res = cli.Get("/");
  12012. ASSERT_TRUE(!res);
  12013. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12014. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12015. // should be set
  12016. EXPECT_EQ(0, res.ssl_error());
  12017. // Verify backend error is captured for SSLLoadingCerts
  12018. // This error occurs when loading CA certificates fails
  12019. EXPECT_NE(0UL, res.ssl_backend_error());
  12020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12021. // OpenSSL specific error codes:
  12022. // > openssl errstr 0x80000002
  12023. // error:80000002:system library::No such file or directory
  12024. // > openssl errstr 0xA000126
  12025. // error:0A000126:SSL routines::unexpected eof while reading
  12026. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12027. res.ssl_backend_error() == 0xA000126);
  12028. #endif
  12029. }
  12030. TEST(SSLClientTest, ServerCertificateVerification4) {
  12031. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12032. ASSERT_TRUE(svr.is_valid());
  12033. svr.Get("/test", [&](const Request &, Response &res) {
  12034. res.set_content("test", "text/plain");
  12035. svr.stop();
  12036. ASSERT_TRUE(true);
  12037. });
  12038. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12039. auto se = detail::scope_exit([&] {
  12040. t.join();
  12041. ASSERT_FALSE(svr.is_running());
  12042. });
  12043. svr.wait_until_ready();
  12044. SSLClient cli("127.0.0.1", PORT);
  12045. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12046. cli.enable_server_certificate_verification(true);
  12047. cli.set_connection_timeout(30);
  12048. auto res = cli.Get("/test");
  12049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12050. ASSERT_EQ(StatusCode::OK_200, res->status);
  12051. }
  12052. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12053. std::string cert;
  12054. read_file(CA_CERT_FILE, cert);
  12055. SSLClient cli("google.com");
  12056. cli.load_ca_cert_store(cert.data(), cert.size());
  12057. const auto res = cli.Get("/");
  12058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12059. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12060. }
  12061. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12062. // clang-format off
  12063. static constexpr char cert[] =
  12064. "GlobalSign Root CA\n"
  12065. "==================\n"
  12066. "-----BEGIN CERTIFICATE-----\n"
  12067. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12068. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12069. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12070. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12071. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12072. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12073. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12074. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12075. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12076. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12077. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12078. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12079. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12080. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12081. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12082. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12083. "-----END CERTIFICATE-----\n";
  12084. // clang-format on
  12085. SSLClient cli("google.com");
  12086. cli.load_ca_cert_store(cert, sizeof(cert));
  12087. const auto res = cli.Get("/");
  12088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12089. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12090. }
  12091. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12092. SSLClient cli("www.youtube.com");
  12093. cli.set_ca_cert_path(CA_CERT_FILE);
  12094. cli.enable_server_certificate_verification(true);
  12095. cli.set_follow_location(true);
  12096. auto res = cli.Get("/");
  12097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12098. ASSERT_EQ(StatusCode::OK_200, res->status);
  12099. }
  12100. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12101. SSLClient cli("wWw.YouTube.Com");
  12102. cli.set_ca_cert_path(CA_CERT_FILE);
  12103. cli.enable_server_certificate_verification(true);
  12104. cli.enable_server_hostname_verification(true);
  12105. cli.set_follow_location(true);
  12106. auto res = cli.Get("/");
  12107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12108. ASSERT_EQ(StatusCode::OK_200, res->status);
  12109. }
  12110. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12111. SSLClient cli("gOoGlE.COm");
  12112. cli.enable_server_certificate_verification(true);
  12113. cli.enable_server_hostname_verification(true);
  12114. cli.set_follow_location(true);
  12115. auto res = cli.Get("/");
  12116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12117. ASSERT_EQ(StatusCode::OK_200, res->status);
  12118. }
  12119. TEST(SSLClientTest, Issue2004_Online) {
  12120. Client client("https://google.com");
  12121. client.set_follow_location(true);
  12122. auto res = client.Get("/");
  12123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12124. ASSERT_EQ(StatusCode::OK_200, res->status);
  12125. auto body = res->body;
  12126. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12127. }
  12128. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12129. // Create SSLClient with invalid cert/key to make is_valid() return false
  12130. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12131. "nonexistent_key.pem");
  12132. // is_valid() should be false due to cert loading failure
  12133. ASSERT_FALSE(cli.is_valid());
  12134. auto res = cli.Get("/");
  12135. ASSERT_FALSE(res);
  12136. EXPECT_EQ(Error::SSLConnection, res.error());
  12137. }
  12138. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12139. // Test for Issue #2251: SSL error not properly reported when client cert
  12140. // and key paths are swapped or mismatched
  12141. // This simulates the scenario where user accidentally swaps the cert and key
  12142. // files
  12143. // Using client cert file as private key and vice versa (completely wrong)
  12144. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12145. // Should fail validation due to cert/key mismatch
  12146. ASSERT_FALSE(cli.is_valid());
  12147. // Attempt to make a request should fail with proper error
  12148. auto res = cli.Get("/");
  12149. ASSERT_FALSE(res);
  12150. EXPECT_EQ(Error::SSLConnection, res.error());
  12151. // SSL error should be recorded in the Result object (this is the key fix for
  12152. // Issue #2251)
  12153. auto backend_error = res.ssl_backend_error();
  12154. EXPECT_NE(0u, backend_error);
  12155. }
  12156. // Tests cert/key mismatch detection at the TLS context level
  12157. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12158. // Test that using mismatched cert/key causes connection failure.
  12159. // We verify this at the SSLClient level rather than through internal
  12160. // TLS API functions.
  12161. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12162. cli.enable_server_certificate_verification(false);
  12163. cli.set_connection_timeout(2);
  12164. // The mismatch should cause a connection or handshake error
  12165. auto res = cli.Get("/test");
  12166. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12167. // Either way, the request should fail
  12168. EXPECT_FALSE(res);
  12169. }
  12170. #endif
  12171. #if 0
  12172. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12173. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12174. ASSERT_TRUE(cli != nullptr);
  12175. cli->set_address_family(AF_INET6);
  12176. cli->set_interface("en0");
  12177. auto res = cli->Get("/get");
  12178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12179. ASSERT_EQ(StatusCode::OK_200, res->status);
  12180. }
  12181. #endif
  12182. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12183. #ifdef CPPHTTPLIB_SSL_ENABLED
  12184. void ClientCertPresent(
  12185. const std::string &client_cert_file,
  12186. const std::string &client_private_key_file,
  12187. const std::string &client_encrypted_private_key_pass = std::string()) {
  12188. using namespace httplib::tls;
  12189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12190. CLIENT_CA_CERT_DIR);
  12191. ASSERT_TRUE(svr.is_valid());
  12192. svr.Get("/test", [&](const Request &req, Response &res) {
  12193. res.set_content("test", "text/plain");
  12194. auto cert = req.peer_cert();
  12195. ASSERT_TRUE(static_cast<bool>(cert));
  12196. std::string common_name = cert.subject_cn();
  12197. EXPECT_EQ("Common Name", common_name);
  12198. });
  12199. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12200. auto se = detail::scope_exit([&] {
  12201. svr.stop();
  12202. t.join();
  12203. ASSERT_FALSE(svr.is_running());
  12204. });
  12205. svr.wait_until_ready();
  12206. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12207. client_encrypted_private_key_pass);
  12208. cli.enable_server_certificate_verification(false);
  12209. cli.set_connection_timeout(30);
  12210. auto res = cli.Get("/test");
  12211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12212. ASSERT_EQ(StatusCode::OK_200, res->status);
  12213. }
  12214. TEST(SSLClientServerTest, ClientCertPresent) {
  12215. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12216. }
  12217. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12218. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12219. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12220. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12221. }
  12222. // PEM memory-based constructor tests (works with all TLS backends)
  12223. void PemMemoryClientCertPresent(
  12224. const std::string &client_cert_file,
  12225. const std::string &client_private_key_file,
  12226. const std::string &client_encrypted_private_key_pass = std::string()) {
  12227. // Read PEM files into memory
  12228. std::string server_cert_pem, server_key_pem;
  12229. std::string client_ca_pem;
  12230. std::string client_cert_pem, client_key_pem;
  12231. read_file(SERVER_CERT_FILE, server_cert_pem);
  12232. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12233. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12234. read_file(client_cert_file, client_cert_pem);
  12235. read_file(client_private_key_file, client_key_pem);
  12236. // Create server with PEM memory
  12237. SSLServer::PemMemory server_pem = {
  12238. server_cert_pem.c_str(),
  12239. server_cert_pem.size(),
  12240. server_key_pem.c_str(),
  12241. server_key_pem.size(),
  12242. client_ca_pem.c_str(),
  12243. client_ca_pem.size(),
  12244. nullptr // no password for server key
  12245. };
  12246. SSLServer svr(server_pem);
  12247. ASSERT_TRUE(svr.is_valid());
  12248. svr.Get("/test", [&](const Request &, Response &res) {
  12249. res.set_content("test", "text/plain");
  12250. });
  12251. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12252. auto se = detail::scope_exit([&] {
  12253. svr.stop();
  12254. t.join();
  12255. ASSERT_FALSE(svr.is_running());
  12256. });
  12257. svr.wait_until_ready();
  12258. // Create client with PEM memory
  12259. const char *password = client_encrypted_private_key_pass.empty()
  12260. ? nullptr
  12261. : client_encrypted_private_key_pass.c_str();
  12262. SSLClient::PemMemory client_pem = {
  12263. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12264. client_key_pem.size(), password};
  12265. SSLClient cli(HOST, PORT, client_pem);
  12266. cli.enable_server_certificate_verification(false);
  12267. cli.set_connection_timeout(30);
  12268. auto res = cli.Get("/test");
  12269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12270. ASSERT_EQ(StatusCode::OK_200, res->status);
  12271. }
  12272. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12273. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12274. }
  12275. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12276. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12277. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12278. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12279. }
  12280. TEST(SSLClientServerTest, ClientCertMissing) {
  12281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12282. CLIENT_CA_CERT_DIR);
  12283. ASSERT_TRUE(svr.is_valid());
  12284. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12285. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12286. auto se = detail::scope_exit([&] {
  12287. svr.stop();
  12288. t.join();
  12289. ASSERT_FALSE(svr.is_running());
  12290. });
  12291. svr.wait_until_ready();
  12292. SSLClient cli(HOST, PORT);
  12293. cli.set_connection_timeout(30);
  12294. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12295. // the chain check on Windows, so the result does not depend on the order.
  12296. cli.enable_server_hostname_verification(false);
  12297. auto res = cli.Get("/test");
  12298. ASSERT_TRUE(!res);
  12299. // When client cert is missing and server requires it, connection fails
  12300. // Error type depends on backend implementation
  12301. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12302. res.error() == Error::SSLConnection);
  12303. // Verify backend error is captured
  12304. // Note: This test may have different error codes depending on the exact
  12305. // verification failure
  12306. EXPECT_NE(0UL, res.ssl_backend_error());
  12307. }
  12308. TEST(SSLClientServerTest, TrustDirOptional) {
  12309. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12310. ASSERT_TRUE(svr.is_valid());
  12311. svr.Get("/test", [&](const Request &, Response &res) {
  12312. res.set_content("test", "text/plain");
  12313. });
  12314. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12315. auto se = detail::scope_exit([&] {
  12316. svr.stop();
  12317. t.join();
  12318. ASSERT_FALSE(svr.is_running());
  12319. });
  12320. svr.wait_until_ready();
  12321. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12322. cli.enable_server_certificate_verification(false);
  12323. cli.set_connection_timeout(30);
  12324. auto res = cli.Get("/test");
  12325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12326. ASSERT_EQ(StatusCode::OK_200, res->status);
  12327. }
  12328. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12329. class NoListenSSLServer : public SSLServer {
  12330. public:
  12331. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12332. const char *client_ca_cert_file_path,
  12333. const char *client_ca_cert_dir_path = nullptr)
  12334. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12335. client_ca_cert_dir_path),
  12336. stop_(false) {}
  12337. std::atomic_bool stop_;
  12338. private:
  12339. bool process_and_close_socket(socket_t /*sock*/) override {
  12340. // Don't create SSL context
  12341. while (!stop_.load()) {
  12342. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12343. }
  12344. return true;
  12345. }
  12346. };
  12347. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12348. CLIENT_CA_CERT_FILE);
  12349. ASSERT_TRUE(svr.is_valid());
  12350. svr.Get("/test", [&](const Request &, Response &res) {
  12351. res.set_content("test", "text/plain");
  12352. });
  12353. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12354. auto se = detail::scope_exit([&] {
  12355. svr.stop_ = true;
  12356. svr.stop();
  12357. t.join();
  12358. ASSERT_FALSE(svr.is_running());
  12359. });
  12360. svr.wait_until_ready();
  12361. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12362. cli.enable_server_certificate_verification(false);
  12363. cli.set_connection_timeout(1);
  12364. auto res = cli.Get("/test");
  12365. ASSERT_TRUE(!res);
  12366. EXPECT_EQ(Error::SSLConnection, res.error());
  12367. // Timeout results in WantRead error code (maps to backend-specific value)
  12368. EXPECT_NE(0, res.ssl_error());
  12369. }
  12370. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12371. // Test SSLServer with client certificate verification using the standard
  12372. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12374. CLIENT_CA_CERT_DIR);
  12375. ASSERT_TRUE(svr.is_valid());
  12376. svr.Get("/test", [&](const Request &req, Response &res) {
  12377. res.set_content("test", "text/plain");
  12378. auto cert = req.peer_cert();
  12379. ASSERT_TRUE(static_cast<bool>(cert));
  12380. auto common_name = cert.subject_cn();
  12381. EXPECT_EQ("Common Name", common_name);
  12382. });
  12383. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12384. auto se = detail::scope_exit([&] {
  12385. svr.stop();
  12386. t.join();
  12387. ASSERT_FALSE(svr.is_running());
  12388. });
  12389. svr.wait_until_ready();
  12390. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12391. cli.enable_server_certificate_verification(false);
  12392. cli.set_connection_timeout(30);
  12393. auto res = cli.Get("/test");
  12394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12395. ASSERT_EQ(StatusCode::OK_200, res->status);
  12396. }
  12397. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12398. // Verifies that wildcard matching and exact matching work consistently
  12399. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12400. using namespace httplib::tls;
  12401. // We need a running server to test against
  12402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12403. ASSERT_TRUE(svr.is_valid());
  12404. svr.Get("/test", [](const Request &, Response &res) {
  12405. res.set_content("ok", "text/plain");
  12406. });
  12407. thread t([&]() { svr.listen(HOST, PORT); });
  12408. auto se = detail::scope_exit([&] {
  12409. svr.stop();
  12410. t.join();
  12411. });
  12412. svr.wait_until_ready();
  12413. bool verify_callback_called = false;
  12414. bool verify_result_wrong = false;
  12415. SSLClient cli(HOST, PORT);
  12416. cli.enable_server_certificate_verification(true);
  12417. cli.set_ca_cert_path(CA_CERT_FILE);
  12418. cli.set_connection_timeout(5);
  12419. // Note: Test certificate has CN="Common Name", not "localhost"
  12420. bool verify_result_cn = false;
  12421. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12422. verify_callback_called = true;
  12423. if (!ctx.cert) return false;
  12424. // Test 1: "Common Name" should match (our test server cert CN)
  12425. verify_result_cn = ctx.check_hostname("Common Name");
  12426. // Test 2: wrong hostname should not match
  12427. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12428. return true; // Accept for the purpose of this test
  12429. });
  12430. auto res = cli.Get("/test");
  12431. // The request may succeed or fail depending on cert configuration
  12432. // but the callback should have been called
  12433. ASSERT_TRUE(verify_callback_called)
  12434. << "Verify callback should have been called";
  12435. // CN="Common Name" should match our test certificate
  12436. //
  12437. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12438. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12439. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12440. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12441. // <openssl/base.h>, which is included transitively when
  12442. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12443. #if defined(OPENSSL_IS_BORINGSSL)
  12444. EXPECT_FALSE(verify_result_cn)
  12445. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12446. #else
  12447. EXPECT_TRUE(verify_result_cn)
  12448. << "verify_hostname should match 'Common Name' (certificate CN)";
  12449. #endif
  12450. // Wrong hostname should not match
  12451. EXPECT_FALSE(verify_result_wrong)
  12452. << "verify_hostname should not match 'wronghost.example.com'";
  12453. }
  12454. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12455. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12456. // X509_check_ip behavior and must hold for every backend.
  12457. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12458. using namespace httplib::tls;
  12459. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12460. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12461. ASSERT_TRUE(svr.is_valid());
  12462. svr.Get("/test", [](const Request &, Response &res) {
  12463. res.set_content("ok", "text/plain");
  12464. });
  12465. thread t([&]() { svr.listen(HOST, PORT); });
  12466. auto se = detail::scope_exit([&] {
  12467. svr.stop();
  12468. t.join();
  12469. });
  12470. svr.wait_until_ready();
  12471. bool verify_callback_called = false;
  12472. bool ip_matched_via_cn = true;
  12473. SSLClient cli(HOST, PORT);
  12474. cli.enable_server_certificate_verification(true);
  12475. cli.set_ca_cert_path(CA_CERT_FILE);
  12476. cli.set_connection_timeout(5);
  12477. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12478. verify_callback_called = true;
  12479. if (!ctx.cert) return false;
  12480. // The IP appears only in the CN, so it must NOT be accepted.
  12481. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12482. return true; // Accept for the purpose of this test
  12483. });
  12484. cli.Get("/test");
  12485. ASSERT_TRUE(verify_callback_called)
  12486. << "Verify callback should have been called";
  12487. EXPECT_FALSE(ip_matched_via_cn)
  12488. << "An IP host must not be authenticated via the certificate CN";
  12489. }
  12490. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12491. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12492. using namespace httplib::tls;
  12493. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12494. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12495. ASSERT_TRUE(svr.is_valid());
  12496. svr.Get("/test", [](const Request &, Response &res) {
  12497. res.set_content("ok", "text/plain");
  12498. });
  12499. thread t([&]() { svr.listen(HOST, PORT); });
  12500. auto se = detail::scope_exit([&] {
  12501. svr.stop();
  12502. t.join();
  12503. });
  12504. svr.wait_until_ready();
  12505. bool verify_callback_called = false;
  12506. bool san_matched = false;
  12507. bool wrong_ipv6_matched = true;
  12508. bool cn_ipv6_matched = true;
  12509. SSLClient cli(HOST, PORT);
  12510. cli.enable_server_certificate_verification(true);
  12511. cli.set_ca_cert_path(CA_CERT_FILE);
  12512. cli.set_connection_timeout(5);
  12513. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12514. verify_callback_called = true;
  12515. if (!ctx.cert) return false;
  12516. // Matches the IPv6 iPAddress SAN.
  12517. san_matched = ctx.check_hostname("2001:db8::1");
  12518. // A different IPv6 address must not match.
  12519. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12520. // "::1" lives only in the CN, so it must not be accepted.
  12521. cn_ipv6_matched = ctx.check_hostname("::1");
  12522. return true; // Accept for the purpose of this test
  12523. });
  12524. cli.Get("/test");
  12525. ASSERT_TRUE(verify_callback_called)
  12526. << "Verify callback should have been called";
  12527. EXPECT_TRUE(san_matched)
  12528. << "verify_hostname should match an IPv6 iPAddress SAN";
  12529. EXPECT_FALSE(wrong_ipv6_matched)
  12530. << "verify_hostname should not match a non-matching IPv6 address";
  12531. EXPECT_FALSE(cn_ipv6_matched)
  12532. << "An IPv6 host must not be authenticated via the certificate CN";
  12533. }
  12534. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12535. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12536. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12537. using namespace httplib::tls;
  12538. // SANs: DNS:a.zz, IP:42.46.122.122
  12539. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12540. ASSERT_TRUE(svr.is_valid());
  12541. svr.Get("/test", [](const Request &, Response &res) {
  12542. res.set_content("ok", "text/plain");
  12543. });
  12544. auto port = svr.bind_to_any_port(HOST);
  12545. thread t([&]() { svr.listen_after_bind(); });
  12546. auto se = detail::scope_exit([&] {
  12547. svr.stop();
  12548. t.join();
  12549. });
  12550. svr.wait_until_ready();
  12551. bool verify_callback_called = false;
  12552. bool dns_san_matched = false;
  12553. bool ip_san_matched = false;
  12554. bool ip_matched_via_dns_san = true;
  12555. bool dns_matched_via_ip_san = true;
  12556. SSLClient cli(HOST, port);
  12557. cli.enable_server_certificate_verification(true);
  12558. cli.set_ca_cert_path(CA_CERT_FILE);
  12559. cli.set_connection_timeout(5);
  12560. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12561. verify_callback_called = true;
  12562. if (!ctx.cert) return false;
  12563. dns_san_matched = ctx.check_hostname("a.zz");
  12564. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12565. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12566. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12567. return true; // Accept for the purpose of this test
  12568. });
  12569. cli.Get("/test");
  12570. ASSERT_TRUE(verify_callback_called)
  12571. << "Verify callback should have been called";
  12572. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12573. EXPECT_TRUE(ip_san_matched)
  12574. << "verify_hostname should match an iPAddress SAN";
  12575. EXPECT_FALSE(ip_matched_via_dns_san)
  12576. << "An IP host must not be authenticated via a dNSName SAN";
  12577. EXPECT_FALSE(dns_matched_via_ip_san)
  12578. << "A DNS host must not be authenticated via an iPAddress SAN";
  12579. }
  12580. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12581. // "www.*.example.test" names one host and not every host under example.test.
  12582. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12583. using namespace httplib::tls;
  12584. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12585. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12586. ASSERT_TRUE(svr.is_valid());
  12587. svr.Get("/test", [](const Request &, Response &res) {
  12588. res.set_content("ok", "text/plain");
  12589. });
  12590. auto port = svr.bind_to_any_port(HOST);
  12591. thread t([&]() { svr.listen_after_bind(); });
  12592. auto se = detail::scope_exit([&] {
  12593. svr.stop();
  12594. t.join();
  12595. });
  12596. svr.wait_until_ready();
  12597. bool verify_callback_called = false;
  12598. bool leftmost_wildcard_matched = false;
  12599. bool wildcard_spanned_labels = true;
  12600. bool inner_wildcard_matched = true;
  12601. SSLClient cli(HOST, port);
  12602. cli.enable_server_certificate_verification(true);
  12603. cli.set_ca_cert_path(CA_CERT_FILE);
  12604. cli.set_connection_timeout(5);
  12605. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12606. verify_callback_called = true;
  12607. if (!ctx.cert) return false;
  12608. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12609. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12610. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12611. return true; // Accept for the purpose of this test
  12612. });
  12613. cli.Get("/test");
  12614. ASSERT_TRUE(verify_callback_called)
  12615. << "Verify callback should have been called";
  12616. EXPECT_TRUE(leftmost_wildcard_matched)
  12617. << "A leftmost wildcard should match a single label";
  12618. EXPECT_FALSE(wildcard_spanned_labels)
  12619. << "A wildcard label must not match more than one label";
  12620. EXPECT_FALSE(inner_wildcard_matched)
  12621. << "A wildcard outside the leftmost label must not be honoured";
  12622. }
  12623. // sans() must report each SAN entry under its own type.
  12624. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12625. using namespace httplib::tls;
  12626. // SANs: DNS:a.zz, IP:42.46.122.122
  12627. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12628. ASSERT_TRUE(svr.is_valid());
  12629. svr.Get("/test", [](const Request &, Response &res) {
  12630. res.set_content("ok", "text/plain");
  12631. });
  12632. auto port = svr.bind_to_any_port(HOST);
  12633. thread t([&]() { svr.listen_after_bind(); });
  12634. auto se = detail::scope_exit([&] {
  12635. svr.stop();
  12636. t.join();
  12637. });
  12638. svr.wait_until_ready();
  12639. bool verify_callback_called = false;
  12640. std::vector<SanEntry> sans;
  12641. SSLClient cli(HOST, port);
  12642. cli.enable_server_certificate_verification(true);
  12643. cli.set_ca_cert_path(CA_CERT_FILE);
  12644. cli.set_connection_timeout(5);
  12645. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12646. verify_callback_called = true;
  12647. if (!ctx.cert) return false;
  12648. sans = ctx.sans();
  12649. return true; // Accept for the purpose of this test
  12650. });
  12651. cli.Get("/test");
  12652. ASSERT_TRUE(verify_callback_called)
  12653. << "Verify callback should have been called";
  12654. auto has_san = [&](SanType type, const std::string &value) {
  12655. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12656. return san.type == type && san.value == value;
  12657. });
  12658. };
  12659. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12660. << "sans() should report the dNSName SAN";
  12661. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12662. << "sans() should report the iPAddress SAN";
  12663. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12664. << "sans() must not report the dNSName SAN as an address";
  12665. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12666. << "sans() must not report the iPAddress SAN as a DNS name";
  12667. }
  12668. #endif
  12669. // mbedTLS-specific callback constructor test
  12670. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12671. #ifdef CPPHTTPLIB_SSL_ENABLED
  12672. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12674. ASSERT_TRUE(svr.is_valid());
  12675. // Set up a handler to verify client certificate is present
  12676. bool client_cert_verified = false;
  12677. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12678. // Verify that client certificate was provided
  12679. client_cert_verified = true;
  12680. res.set_content("success", "text/plain");
  12681. });
  12682. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12683. auto se = detail::scope_exit([&] {
  12684. svr.stop();
  12685. t.join();
  12686. ASSERT_FALSE(svr.is_running());
  12687. });
  12688. svr.wait_until_ready();
  12689. // Client with certificate
  12690. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12691. cli.enable_server_certificate_verification(false);
  12692. cli.set_connection_timeout(30);
  12693. auto res = cli.Get("/test");
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. ASSERT_EQ(StatusCode::OK_200, res->status);
  12696. ASSERT_TRUE(client_cert_verified);
  12697. EXPECT_EQ("success", res->body);
  12698. }
  12699. #endif
  12700. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12701. // backends
  12702. #ifdef CPPHTTPLIB_SSL_ENABLED
  12703. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12704. using namespace httplib::tls;
  12705. // Test that when client CA cert file is provided,
  12706. // the server properly requests and validates client certificates
  12707. // Create a server with client authentication
  12708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12709. ASSERT_TRUE(svr.is_valid());
  12710. bool handler_called = false;
  12711. svr.Get("/test", [&](const Request &req, Response &res) {
  12712. handler_called = true;
  12713. // Verify that a client certificate was provided
  12714. auto cert = req.peer_cert();
  12715. ASSERT_TRUE(static_cast<bool>(cert));
  12716. // Get the issuer name
  12717. std::string issuer_str = cert.issuer_name();
  12718. ASSERT_FALSE(issuer_str.empty());
  12719. // The client certificate should be issued by our test CA
  12720. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12721. res.set_content("authenticated", "text/plain");
  12722. });
  12723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12724. auto se = detail::scope_exit([&] {
  12725. svr.stop();
  12726. t.join();
  12727. ASSERT_FALSE(svr.is_running());
  12728. });
  12729. svr.wait_until_ready();
  12730. // Connect with a client certificate issued by the CA
  12731. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12732. cli.enable_server_certificate_verification(false);
  12733. cli.set_connection_timeout(30);
  12734. auto res = cli.Get("/test");
  12735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12736. ASSERT_EQ(StatusCode::OK_200, res->status);
  12737. ASSERT_TRUE(handler_called);
  12738. EXPECT_EQ("authenticated", res->body);
  12739. }
  12740. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12741. using namespace httplib::tls;
  12742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12743. ASSERT_TRUE(svr.is_valid());
  12744. svr.Get("/test", [](const Request &, Response &res) {
  12745. res.set_content("ok", "text/plain");
  12746. });
  12747. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12748. auto se = detail::scope_exit([&] {
  12749. svr.stop();
  12750. t.join();
  12751. });
  12752. svr.wait_until_ready();
  12753. SSLClient cli(HOST, PORT);
  12754. cli.enable_server_certificate_verification(false);
  12755. cli.set_connection_timeout(30);
  12756. bool cert_checked = false;
  12757. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12758. if (ctx.cert) {
  12759. auto sans = ctx.sans();
  12760. // Test certificate may or may not have SANs - just verify the API
  12761. // works If SANs exist, verify the types are valid
  12762. for (const auto &san : sans) {
  12763. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12764. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12765. san.type == SanType::OTHER);
  12766. EXPECT_FALSE(san.value.empty());
  12767. }
  12768. cert_checked = true;
  12769. }
  12770. return true;
  12771. });
  12772. auto res = cli.Get("/test");
  12773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12774. EXPECT_TRUE(cert_checked);
  12775. }
  12776. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12777. using namespace httplib::tls;
  12778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12779. ASSERT_TRUE(svr.is_valid());
  12780. svr.Get("/test", [](const Request &, Response &res) {
  12781. res.set_content("ok", "text/plain");
  12782. });
  12783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12784. auto se = detail::scope_exit([&] {
  12785. svr.stop();
  12786. t.join();
  12787. });
  12788. svr.wait_until_ready();
  12789. SSLClient cli(HOST, PORT);
  12790. cli.enable_server_certificate_verification(false);
  12791. cli.set_connection_timeout(30);
  12792. bool validity_checked = false;
  12793. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12794. if (ctx.cert) {
  12795. time_t not_before = 0, not_after = 0;
  12796. bool result = ctx.validity(not_before, not_after);
  12797. EXPECT_TRUE(result);
  12798. // Verify that not_before < now < not_after for a valid cert
  12799. time_t now = time(nullptr);
  12800. EXPECT_LT(not_before, now);
  12801. EXPECT_GT(not_after, now);
  12802. validity_checked = true;
  12803. }
  12804. return true;
  12805. });
  12806. auto res = cli.Get("/test");
  12807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12808. EXPECT_TRUE(validity_checked);
  12809. }
  12810. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12811. using namespace httplib::tls;
  12812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12813. ASSERT_TRUE(svr.is_valid());
  12814. svr.Get("/test", [](const Request &, Response &res) {
  12815. res.set_content("ok", "text/plain");
  12816. });
  12817. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12818. auto se = detail::scope_exit([&] {
  12819. svr.stop();
  12820. t.join();
  12821. });
  12822. svr.wait_until_ready();
  12823. SSLClient cli(HOST, PORT);
  12824. cli.enable_server_certificate_verification(false);
  12825. cli.set_connection_timeout(30);
  12826. bool serial_checked = false;
  12827. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12828. if (ctx.cert) {
  12829. std::string serial = ctx.serial();
  12830. EXPECT_FALSE(serial.empty());
  12831. // Serial should be a hex string
  12832. for (char c : serial) {
  12833. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12834. (c >= 'a' && c <= 'f'));
  12835. }
  12836. serial_checked = true;
  12837. }
  12838. return true;
  12839. });
  12840. auto res = cli.Get("/test");
  12841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12842. EXPECT_TRUE(serial_checked);
  12843. }
  12844. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12845. // Test 1: Valid CA file - no error should be recorded
  12846. {
  12847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12848. CLIENT_CA_CERT_FILE);
  12849. ASSERT_TRUE(svr.is_valid());
  12850. // With valid setup, last_ssl_error should be 0
  12851. EXPECT_EQ(0, svr.ssl_last_error());
  12852. }
  12853. // Test 2: Invalid CA file content
  12854. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12855. {
  12856. // Create a temporary file with completely invalid content
  12857. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12858. {
  12859. std::ofstream ofs(temp_invalid_ca);
  12860. ofs << "This is not a certificate file at all\n";
  12861. ofs << "Just plain text content\n";
  12862. }
  12863. // Create server with invalid CA file
  12864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12865. // Clean up temporary file
  12866. std::remove(temp_invalid_ca);
  12867. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12868. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12869. // Note: SSL_CTX_load_verify_locations typically fails first,
  12870. // but our error handling code path is still exercised
  12871. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12872. }
  12873. }
  12874. TEST(VerifyCallbackTest, VerifyContextFields) {
  12875. using namespace httplib::tls;
  12876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12877. ASSERT_TRUE(svr.is_valid());
  12878. svr.Get("/test", [](const Request &, Response &res) {
  12879. res.set_content("ok", "text/plain");
  12880. });
  12881. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12882. auto se = detail::scope_exit([&] {
  12883. svr.stop();
  12884. t.join();
  12885. });
  12886. svr.wait_until_ready();
  12887. SSLClient cli(HOST, PORT);
  12888. cli.enable_server_certificate_verification(false);
  12889. cli.set_connection_timeout(30);
  12890. int callback_count = 0;
  12891. bool saw_leaf_cert = false;
  12892. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12893. if (ctx.cert) {
  12894. callback_count++;
  12895. // We should see at least one certificate (the leaf)
  12896. std::string cn = ctx.subject_cn();
  12897. if (!cn.empty()) { saw_leaf_cert = true; }
  12898. // Verify context fields are populated
  12899. EXPECT_NE(ctx.session, nullptr);
  12900. EXPECT_GE(ctx.depth, 0);
  12901. }
  12902. return true;
  12903. });
  12904. auto res = cli.Get("/test");
  12905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12906. EXPECT_GT(callback_count, 0);
  12907. EXPECT_TRUE(saw_leaf_cert);
  12908. }
  12909. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12910. using httplib::tls::TlsError;
  12911. // Test that verify_error_to_string returns empty for success
  12912. std::string success_str = TlsError::verify_error_to_string(0);
  12913. EXPECT_TRUE(success_str.empty());
  12914. // Test that verify_error_to_string returns non-empty for error codes
  12915. // Using a common error code (certificate expired)
  12916. std::string error_str =
  12917. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12918. EXPECT_FALSE(error_str.empty());
  12919. }
  12920. TEST(SessionVerifierTest, CertificateAccepted) {
  12921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12922. ASSERT_TRUE(svr.is_valid());
  12923. svr.Get("/test", [](const Request &, Response &res) {
  12924. res.set_content("ok", "text/plain");
  12925. });
  12926. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12927. auto se = detail::scope_exit([&] {
  12928. svr.stop();
  12929. t.join();
  12930. });
  12931. svr.wait_until_ready();
  12932. SSLClient cli(HOST, PORT);
  12933. cli.enable_server_certificate_verification(false);
  12934. cli.set_connection_timeout(30);
  12935. bool callback_called = false;
  12936. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12937. EXPECT_NE(session, nullptr);
  12938. callback_called = true;
  12939. return SSLVerifierResponse::CertificateAccepted;
  12940. });
  12941. auto res = cli.Get("/test");
  12942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12943. EXPECT_EQ(200, res->status);
  12944. EXPECT_TRUE(callback_called);
  12945. }
  12946. TEST(SessionVerifierTest, CertificateRejected) {
  12947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12948. ASSERT_TRUE(svr.is_valid());
  12949. svr.Get("/test", [](const Request &, Response &res) {
  12950. res.set_content("ok", "text/plain");
  12951. });
  12952. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12953. auto se = detail::scope_exit([&] {
  12954. svr.stop();
  12955. t.join();
  12956. });
  12957. svr.wait_until_ready();
  12958. SSLClient cli(HOST, PORT);
  12959. cli.enable_server_certificate_verification(false);
  12960. cli.set_connection_timeout(30);
  12961. bool callback_called = false;
  12962. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12963. EXPECT_NE(session, nullptr);
  12964. callback_called = true;
  12965. return SSLVerifierResponse::CertificateRejected;
  12966. });
  12967. auto res = cli.Get("/test");
  12968. EXPECT_FALSE(res);
  12969. EXPECT_TRUE(callback_called);
  12970. }
  12971. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12972. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12973. ASSERT_TRUE(svr.is_valid());
  12974. svr.Get("/test", [](const Request &, Response &res) {
  12975. res.set_content("ok", "text/plain");
  12976. });
  12977. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12978. auto se = detail::scope_exit([&] {
  12979. svr.stop();
  12980. t.join();
  12981. });
  12982. svr.wait_until_ready();
  12983. // NoDecisionMade with verification disabled should succeed (no default check)
  12984. SSLClient cli(HOST, PORT);
  12985. cli.enable_server_certificate_verification(false);
  12986. cli.set_connection_timeout(30);
  12987. bool callback_called = false;
  12988. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12989. EXPECT_NE(session, nullptr);
  12990. callback_called = true;
  12991. return SSLVerifierResponse::NoDecisionMade;
  12992. });
  12993. auto res = cli.Get("/test");
  12994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12995. EXPECT_EQ(200, res->status);
  12996. EXPECT_TRUE(callback_called);
  12997. }
  12998. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12999. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13000. ASSERT_TRUE(svr.is_valid());
  13001. svr.Get("/test", [](const Request &, Response &res) {
  13002. res.set_content("ok", "text/plain");
  13003. });
  13004. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13005. auto se = detail::scope_exit([&] {
  13006. svr.stop();
  13007. t.join();
  13008. });
  13009. svr.wait_until_ready();
  13010. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13011. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13012. // so we only check that the request fails, not whether the callback was
  13013. // called.
  13014. SSLClient cli(HOST, PORT);
  13015. cli.enable_server_certificate_verification(true);
  13016. cli.set_connection_timeout(30);
  13017. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13018. EXPECT_NE(session, nullptr);
  13019. return SSLVerifierResponse::NoDecisionMade;
  13020. });
  13021. auto res = cli.Get("/test");
  13022. EXPECT_FALSE(res);
  13023. }
  13024. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13025. // Test SSL server using PemMemory constructor with client CA certificates
  13026. // Read PEM files
  13027. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13028. read_file(SERVER_CERT_FILE, server_cert_pem);
  13029. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13030. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13031. // Create SSLServer with PemMemory constructor including client CA
  13032. SSLServer::PemMemory server_pem = {
  13033. server_cert_pem.c_str(),
  13034. server_cert_pem.size(),
  13035. server_key_pem.c_str(),
  13036. server_key_pem.size(),
  13037. client_ca_pem.c_str(),
  13038. client_ca_pem.size(),
  13039. nullptr // no password for server key
  13040. };
  13041. SSLServer svr(server_pem);
  13042. ASSERT_TRUE(svr.is_valid());
  13043. // No SSL error should be recorded for valid setup
  13044. EXPECT_EQ(0, svr.ssl_last_error());
  13045. // Set up server endpoints
  13046. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13047. res.set_content("ok", "text/plain");
  13048. });
  13049. // Start server in a thread
  13050. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13051. svr.wait_until_ready();
  13052. // Connect with client certificate (using constructor with paths)
  13053. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13054. cli.enable_server_certificate_verification(false);
  13055. auto res = cli.Get("/test-pem-ca");
  13056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13057. EXPECT_EQ(200, res->status);
  13058. EXPECT_EQ("ok", res->body);
  13059. svr.stop();
  13060. server_thread.join();
  13061. }
  13062. #endif
  13063. #ifdef _WIN32
  13064. TEST(CleanupTest, WSACleanup) {
  13065. int ret = WSACleanup();
  13066. ASSERT_EQ(0, ret);
  13067. }
  13068. #endif
  13069. #ifndef CPPHTTPLIB_SSL_ENABLED
  13070. TEST(NoSSLSupport, SimpleInterface) {
  13071. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13072. }
  13073. #endif
  13074. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13075. TEST(InvalidScheme, SimpleInterface) {
  13076. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13077. }
  13078. #endif
  13079. TEST(NoScheme, SimpleInterface) {
  13080. Client cli("yahoo.com:80");
  13081. ASSERT_TRUE(cli.is_valid());
  13082. }
  13083. TEST(SendAPI, SimpleInterface_Online) {
  13084. Client cli("http://yahoo.com");
  13085. Request req;
  13086. req.method = "GET";
  13087. req.path = "/";
  13088. auto res = cli.send(req);
  13089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13090. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13091. }
  13092. TEST(SendAPI, WithParamsInRequest) {
  13093. Server svr;
  13094. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13095. EXPECT_TRUE(req.has_param("test"));
  13096. EXPECT_EQ("test_value", req.get_param_value("test"));
  13097. });
  13098. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13099. auto se = detail::scope_exit([&] {
  13100. svr.stop();
  13101. t.join();
  13102. ASSERT_FALSE(svr.is_running());
  13103. });
  13104. svr.wait_until_ready();
  13105. Client cli(HOST, PORT);
  13106. {
  13107. Request req;
  13108. req.method = "GET";
  13109. req.path = "/";
  13110. req.params.emplace("test", "test_value");
  13111. auto res = cli.send(req);
  13112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13113. }
  13114. {
  13115. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13117. }
  13118. }
  13119. TEST(ClientImplMethods, GetSocketTest) {
  13120. httplib::Server svr;
  13121. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13122. res.status = StatusCode::OK_200;
  13123. });
  13124. auto port = svr.bind_to_any_port("127.0.0.1");
  13125. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13126. auto se = detail::scope_exit([&] {
  13127. svr.stop();
  13128. thread.join();
  13129. ASSERT_FALSE(svr.is_running());
  13130. });
  13131. svr.wait_until_ready();
  13132. {
  13133. httplib::Client cli("127.0.0.1", port);
  13134. cli.set_keep_alive(true);
  13135. // Use the behavior of cpp-httplib of opening the connection
  13136. // only when the first request happens. If that changes,
  13137. // this test would be obsolete.
  13138. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13139. // This also implicitly tests the server. But other tests would fail much
  13140. // earlier than this one to be considered.
  13141. auto res = cli.Get("/");
  13142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13143. EXPECT_EQ(StatusCode::OK_200, res->status);
  13144. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13145. }
  13146. }
  13147. #ifdef CPPHTTPLIB_SSL_ENABLED
  13148. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13149. Client cli("http://yahoo.com");
  13150. auto res = cli.Get("/");
  13151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13152. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13153. cli.set_follow_location(true);
  13154. res = cli.Get("/");
  13155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13156. EXPECT_EQ(StatusCode::OK_200, res->status);
  13157. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13158. }
  13159. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13160. Client cli("https://yahoo.com");
  13161. auto res = cli.Get("/");
  13162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13163. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13164. cli.set_follow_location(true);
  13165. res = cli.Get("/");
  13166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13167. EXPECT_EQ(StatusCode::OK_200, res->status);
  13168. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13169. }
  13170. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13171. Client cli("https://yahoo.com");
  13172. auto res = cli.Get("/");
  13173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13174. ASSERT_FALSE(!res);
  13175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13176. ASSERT_FALSE(res == nullptr);
  13177. ASSERT_TRUE(res != nullptr);
  13178. EXPECT_EQ(Error::Success, res.error());
  13179. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13180. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13181. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13182. cli.set_follow_location(true);
  13183. res = cli.Get("/");
  13184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13185. EXPECT_EQ(Error::Success, res.error());
  13186. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13187. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13188. EXPECT_EQ(StatusCode::OK_200, res->status);
  13189. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13190. }
  13191. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13192. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13193. Client cli("https://cdnjs.cloudflare.com");
  13194. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13195. Headers{{"Accept-Encoding", "br"}});
  13196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13197. EXPECT_EQ(StatusCode::OK_200, res->status);
  13198. EXPECT_EQ(287630U, res->body.size());
  13199. EXPECT_EQ("application/javascript; charset=utf-8",
  13200. res->get_header_value("Content-Type"));
  13201. }
  13202. #endif
  13203. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13204. #undef REDIR_HOST // Silence compiler warning
  13205. #define REDIR_HOST "https://httpbingo.org"
  13206. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13207. Client cli(REDIR_HOST);
  13208. cli.set_follow_location(true);
  13209. auto res =
  13210. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13212. EXPECT_EQ(StatusCode::OK_200, res->status);
  13213. }
  13214. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13215. Client cli(REDIR_HOST);
  13216. cli.set_follow_location(true);
  13217. Params params;
  13218. params.emplace("url", "http://example.com");
  13219. params.emplace("status_code", "302");
  13220. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13222. EXPECT_EQ(StatusCode::OK_200, res->status);
  13223. }
  13224. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13225. Client cli(REDIR_HOST);
  13226. cli.set_follow_location(true);
  13227. Params params;
  13228. params.emplace("url", "http://example.com");
  13229. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13231. EXPECT_EQ(StatusCode::OK_200, res->status);
  13232. }
  13233. TEST(HttpToHttpsRedirectTest, CertFile) {
  13234. auto ssl_port = PORT + 1;
  13235. Server svr;
  13236. ASSERT_TRUE(svr.is_valid());
  13237. svr.Get("/index", [&](const Request &, Response &res) {
  13238. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13239. "/index");
  13240. svr.stop();
  13241. });
  13242. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13243. ASSERT_TRUE(ssl_svr.is_valid());
  13244. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13245. res.set_content("test", "text/plain");
  13246. ssl_svr.stop();
  13247. });
  13248. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13249. thread t2 =
  13250. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13251. auto se = detail::scope_exit([&] {
  13252. t2.join();
  13253. t.join();
  13254. ASSERT_FALSE(svr.is_running());
  13255. });
  13256. svr.wait_until_ready();
  13257. ssl_svr.wait_until_ready();
  13258. Client cli("127.0.0.1", PORT);
  13259. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13260. cli.enable_server_certificate_verification(true);
  13261. cli.set_follow_location(true);
  13262. cli.set_connection_timeout(30);
  13263. auto res = cli.Get("/index");
  13264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13265. ASSERT_EQ(StatusCode::OK_200, res->status);
  13266. }
  13267. TEST(SSLClientRedirectTest, CertFile) {
  13268. auto ssl_port = PORT + 1;
  13269. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13270. ASSERT_TRUE(ssl_svr1.is_valid());
  13271. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13272. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13273. "/index");
  13274. ssl_svr1.stop();
  13275. });
  13276. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13277. ASSERT_TRUE(ssl_svr2.is_valid());
  13278. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13279. res.set_content("test", "text/plain");
  13280. ssl_svr2.stop();
  13281. });
  13282. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13283. thread t2 =
  13284. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13285. auto se = detail::scope_exit([&] {
  13286. t2.join();
  13287. t.join();
  13288. ASSERT_FALSE(ssl_svr1.is_running());
  13289. });
  13290. ssl_svr1.wait_until_ready();
  13291. ssl_svr2.wait_until_ready();
  13292. SSLClient cli("127.0.0.1", PORT);
  13293. std::string cert;
  13294. read_file(SERVER_CERT2_FILE, cert);
  13295. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13296. cli.enable_server_certificate_verification(true);
  13297. cli.set_follow_location(true);
  13298. cli.set_connection_timeout(30);
  13299. auto res = cli.Get("/index");
  13300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13301. ASSERT_EQ(StatusCode::OK_200, res->status);
  13302. }
  13303. #endif
  13304. #ifdef CPPHTTPLIB_SSL_ENABLED
  13305. // Test that set_ca_cert_store() skips system certs (consistent with
  13306. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13307. // should be trusted - system certs should NOT be loaded.
  13308. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13309. // Load a specific cert that is NOT a system CA cert
  13310. std::string cert;
  13311. read_file(SERVER_CERT2_FILE, cert);
  13312. SSLClient cli("google.com");
  13313. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13314. cli.enable_server_certificate_verification(true);
  13315. // This should FAIL because:
  13316. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13317. // 2. System certs should NOT be loaded when custom store is set
  13318. // If system certs WERE loaded, this would succeed
  13319. auto res = cli.Get("/");
  13320. ASSERT_FALSE(res);
  13321. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13322. }
  13323. // Same as above, but through the native store handle path. Regression test:
  13324. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13325. // merged system certs into the user-provided store.
  13326. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13327. std::string cert;
  13328. read_file(SERVER_CERT2_FILE, cert);
  13329. SSLClient cli("google.com");
  13330. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13331. cli.enable_server_certificate_verification(true);
  13332. auto res = cli.Get("/");
  13333. ASSERT_FALSE(res);
  13334. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13335. }
  13336. // A custom store set via the native handle must still verify a server whose
  13337. // cert it does contain.
  13338. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13339. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13340. ASSERT_TRUE(svr.is_valid());
  13341. svr.Get("/test", [&](const Request &, Response &res) {
  13342. res.set_content("test", "text/plain");
  13343. });
  13344. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13345. auto se = detail::scope_exit([&] {
  13346. svr.stop();
  13347. t.join();
  13348. ASSERT_FALSE(svr.is_running());
  13349. });
  13350. svr.wait_until_ready();
  13351. SSLClient cli("127.0.0.1", PORT);
  13352. std::string cert;
  13353. read_file(SERVER_CERT2_FILE, cert);
  13354. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13355. cli.enable_server_certificate_verification(true);
  13356. cli.set_connection_timeout(30);
  13357. auto res = cli.Get("/test");
  13358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13359. ASSERT_EQ(StatusCode::OK_200, res->status);
  13360. }
  13361. // CA certs loaded through the universal Client must be transferred to the
  13362. // client created internally for following an HTTPS redirect. Regression test:
  13363. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13364. // the CA data for redirect transfer.
  13365. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13366. auto ssl_port = PORT + 1;
  13367. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13368. ASSERT_TRUE(ssl_svr1.is_valid());
  13369. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13370. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13371. "/index");
  13372. });
  13373. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13374. ASSERT_TRUE(ssl_svr2.is_valid());
  13375. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13376. res.set_content("test", "text/plain");
  13377. });
  13378. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13379. thread t2 =
  13380. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13381. auto se = detail::scope_exit([&] {
  13382. ssl_svr2.stop();
  13383. ssl_svr1.stop();
  13384. t2.join();
  13385. t.join();
  13386. ASSERT_FALSE(ssl_svr1.is_running());
  13387. });
  13388. ssl_svr1.wait_until_ready();
  13389. ssl_svr2.wait_until_ready();
  13390. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13391. std::string cert;
  13392. read_file(SERVER_CERT2_FILE, cert);
  13393. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13394. cli.enable_server_certificate_verification(true);
  13395. cli.set_follow_location(true);
  13396. cli.set_connection_timeout(30);
  13397. auto res = cli.Get("/index");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. ASSERT_EQ(StatusCode::OK_200, res->status);
  13400. }
  13401. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13402. // so a host signed by a system CA verifies even though a custom CA is set
  13403. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13404. std::string cert;
  13405. read_file(SERVER_CERT2_FILE, cert);
  13406. SSLClient cli("google.com");
  13407. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13408. cli.enable_system_ca(true);
  13409. cli.enable_server_certificate_verification(true);
  13410. auto res = cli.Get("/");
  13411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13412. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13413. }
  13414. // The custom CA remains effective when combined with the system CA
  13415. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13416. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13417. ASSERT_TRUE(svr.is_valid());
  13418. svr.Get("/test", [&](const Request &, Response &res) {
  13419. res.set_content("test", "text/plain");
  13420. });
  13421. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13422. auto se = detail::scope_exit([&] {
  13423. svr.stop();
  13424. t.join();
  13425. ASSERT_FALSE(svr.is_running());
  13426. });
  13427. svr.wait_until_ready();
  13428. SSLClient cli("127.0.0.1", PORT);
  13429. std::string cert;
  13430. read_file(SERVER_CERT2_FILE, cert);
  13431. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13432. cli.enable_system_ca(true);
  13433. cli.enable_server_certificate_verification(true);
  13434. cli.set_connection_timeout(30);
  13435. auto res = cli.Get("/test");
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. ASSERT_EQ(StatusCode::OK_200, res->status);
  13438. }
  13439. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13440. // skip chain verification entirely (only the certificate identity was
  13441. // checked), so a server presenting an untrusted certificate with a matching
  13442. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13443. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13444. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13445. ASSERT_TRUE(svr.is_valid());
  13446. svr.Get("/test", [&](const Request &, Response &res) {
  13447. res.set_content("test", "text/plain");
  13448. });
  13449. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13450. auto se = detail::scope_exit([&] {
  13451. svr.stop();
  13452. t.join();
  13453. ASSERT_FALSE(svr.is_running());
  13454. });
  13455. svr.wait_until_ready();
  13456. SSLClient cli("127.0.0.1", PORT);
  13457. std::string cert;
  13458. // A trusted CA that did not sign the server certificate. The server cert
  13459. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13460. // this connection.
  13461. read_file(CLIENT_CA_CERT_FILE, cert);
  13462. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13463. cli.enable_server_certificate_verification(true);
  13464. cli.set_connection_timeout(30);
  13465. auto res = cli.Get("/test");
  13466. ASSERT_FALSE(res);
  13467. }
  13468. // enable_system_ca(false) prevents system CA loading entirely
  13469. TEST(SSLClientTest, DisableSystemCa_Online) {
  13470. SSLClient cli("google.com");
  13471. cli.enable_system_ca(false);
  13472. cli.enable_server_certificate_verification(true);
  13473. auto res = cli.Get("/");
  13474. ASSERT_FALSE(res);
  13475. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13476. // itself when the CA chain is empty
  13477. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13478. res.error() == Error::SSLConnection);
  13479. }
  13480. // The universal Client forwards enable_system_ca()
  13481. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13482. std::string cert;
  13483. read_file(SERVER_CERT2_FILE, cert);
  13484. Client cli("https://google.com");
  13485. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13486. cli.enable_system_ca(true);
  13487. cli.enable_server_certificate_verification(true);
  13488. auto res = cli.Get("/");
  13489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13490. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13491. }
  13492. // The system CA policy must carry over to the client created internally for
  13493. // following a cross-host HTTPS redirect
  13494. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13495. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13496. ASSERT_TRUE(svr.is_valid());
  13497. svr.Get("/index", [&](const Request &, Response &res) {
  13498. res.set_redirect("https://www.google.com/");
  13499. });
  13500. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13501. auto se = detail::scope_exit([&] {
  13502. svr.stop();
  13503. t.join();
  13504. ASSERT_FALSE(svr.is_running());
  13505. });
  13506. svr.wait_until_ready();
  13507. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13508. std::string cert;
  13509. read_file(SERVER_CERT2_FILE, cert);
  13510. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13511. cli.enable_system_ca(true);
  13512. cli.enable_server_certificate_verification(true);
  13513. cli.set_follow_location(true);
  13514. cli.set_connection_timeout(30);
  13515. // Receiving any response proves the redirect client completed the TLS
  13516. // handshake with a system-CA-signed host
  13517. auto res = cli.Get("/index");
  13518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13519. }
  13520. TEST(MultipartFormDataTest, LargeData) {
  13521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13522. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13523. const ContentReader &content_reader) {
  13524. if (req.is_multipart_form_data()) {
  13525. std::vector<FormData> items;
  13526. content_reader(
  13527. [&](const FormData &file) {
  13528. items.push_back(file);
  13529. return true;
  13530. },
  13531. [&](const char *data, size_t data_length) {
  13532. items.back().content.append(data, data_length);
  13533. return true;
  13534. });
  13535. EXPECT_TRUE(std::string(items[0].name) == "document");
  13536. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13537. EXPECT_TRUE(items[0].filename == "2MB_data");
  13538. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13539. EXPECT_TRUE(items[1].name == "hello");
  13540. EXPECT_TRUE(items[1].content == "world");
  13541. EXPECT_TRUE(items[1].filename == "");
  13542. EXPECT_TRUE(items[1].content_type == "");
  13543. } else {
  13544. std::string body;
  13545. content_reader([&](const char *data, size_t data_length) {
  13546. body.append(data, data_length);
  13547. return true;
  13548. });
  13549. }
  13550. });
  13551. auto port = svr.bind_to_any_port(HOST);
  13552. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13553. auto se = detail::scope_exit([&] {
  13554. svr.stop();
  13555. t.join();
  13556. ASSERT_FALSE(svr.is_running());
  13557. });
  13558. svr.wait_until_ready();
  13559. {
  13560. std::string data(1024 * 1024 * 2, '.');
  13561. std::stringstream buffer;
  13562. buffer << data;
  13563. SSLClient cli(HOST, port);
  13564. cli.enable_server_certificate_verification(false);
  13565. UploadFormDataItems items{
  13566. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13567. {"hello", "world", "", ""},
  13568. };
  13569. auto res = cli.Post("/post", items);
  13570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13571. ASSERT_EQ(StatusCode::OK_200, res->status);
  13572. }
  13573. }
  13574. TEST(MultipartFormDataTest, DataProviderItems) {
  13575. std::random_device seed_gen;
  13576. std::mt19937 random(seed_gen());
  13577. std::string rand1;
  13578. rand1.resize(1000);
  13579. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13580. std::string rand2;
  13581. rand2.resize(3000);
  13582. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13584. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13585. const ContentReader &content_reader) {
  13586. ASSERT_FALSE(req.is_multipart_form_data());
  13587. std::string body;
  13588. content_reader([&](const char *data, size_t data_length) {
  13589. body.append(data, data_length);
  13590. return true;
  13591. });
  13592. EXPECT_EQ(body, "");
  13593. });
  13594. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13595. const ContentReader &content_reader) {
  13596. ASSERT_TRUE(req.is_multipart_form_data());
  13597. std::vector<FormData> items;
  13598. content_reader(
  13599. [&](const FormData &file) {
  13600. items.push_back(file);
  13601. return true;
  13602. },
  13603. [&](const char *data, size_t data_length) {
  13604. items.back().content.append(data, data_length);
  13605. return true;
  13606. });
  13607. ASSERT_TRUE(items.size() == 2);
  13608. EXPECT_EQ(std::string(items[0].name), "name1");
  13609. EXPECT_EQ(items[0].content, "Testing123");
  13610. EXPECT_EQ(items[0].filename, "filename1");
  13611. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13612. EXPECT_EQ(items[1].name, "name2");
  13613. EXPECT_EQ(items[1].content, "Testing456");
  13614. EXPECT_EQ(items[1].filename, "");
  13615. EXPECT_EQ(items[1].content_type, "");
  13616. });
  13617. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13618. const ContentReader &content_reader) {
  13619. ASSERT_TRUE(req.is_multipart_form_data());
  13620. std::vector<FormData> items;
  13621. content_reader(
  13622. [&](const FormData &file) {
  13623. items.push_back(file);
  13624. return true;
  13625. },
  13626. [&](const char *data, size_t data_length) {
  13627. items.back().content.append(data, data_length);
  13628. return true;
  13629. });
  13630. ASSERT_TRUE(items.size() == 2);
  13631. EXPECT_EQ(items[0].name, "name3");
  13632. EXPECT_EQ(items[0].content, rand1);
  13633. EXPECT_EQ(items[0].filename, "filename3");
  13634. EXPECT_EQ(items[0].content_type, "");
  13635. EXPECT_EQ(items[1].name, "name4");
  13636. EXPECT_EQ(items[1].content, rand2);
  13637. EXPECT_EQ(items[1].filename, "filename4");
  13638. EXPECT_EQ(items[1].content_type, "");
  13639. });
  13640. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13641. const ContentReader &content_reader) {
  13642. ASSERT_TRUE(req.is_multipart_form_data());
  13643. std::vector<FormData> items;
  13644. content_reader(
  13645. [&](const FormData &file) {
  13646. items.push_back(file);
  13647. return true;
  13648. },
  13649. [&](const char *data, size_t data_length) {
  13650. items.back().content.append(data, data_length);
  13651. return true;
  13652. });
  13653. ASSERT_TRUE(items.size() == 4);
  13654. EXPECT_EQ(std::string(items[0].name), "name1");
  13655. EXPECT_EQ(items[0].content, "Testing123");
  13656. EXPECT_EQ(items[0].filename, "filename1");
  13657. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13658. EXPECT_EQ(items[1].name, "name2");
  13659. EXPECT_EQ(items[1].content, "Testing456");
  13660. EXPECT_EQ(items[1].filename, "");
  13661. EXPECT_EQ(items[1].content_type, "");
  13662. EXPECT_EQ(items[2].name, "name3");
  13663. EXPECT_EQ(items[2].content, rand1);
  13664. EXPECT_EQ(items[2].filename, "filename3");
  13665. EXPECT_EQ(items[2].content_type, "");
  13666. EXPECT_EQ(items[3].name, "name4");
  13667. EXPECT_EQ(items[3].content, rand2);
  13668. EXPECT_EQ(items[3].filename, "filename4");
  13669. EXPECT_EQ(items[3].content_type, "");
  13670. });
  13671. auto port = svr.bind_to_any_port("localhost");
  13672. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13673. auto se = detail::scope_exit([&] {
  13674. svr.stop();
  13675. t.join();
  13676. ASSERT_FALSE(svr.is_running());
  13677. });
  13678. svr.wait_until_ready();
  13679. {
  13680. SSLClient cli("localhost", port);
  13681. cli.enable_server_certificate_verification(false);
  13682. UploadFormDataItems items{
  13683. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13684. {"name2", "Testing456", "", ""}, // not a file
  13685. };
  13686. {
  13687. auto res = cli.Post("/post-none", {}, {}, {});
  13688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13689. ASSERT_EQ(StatusCode::OK_200, res->status);
  13690. }
  13691. FormDataProviderItems providers;
  13692. {
  13693. auto res =
  13694. cli.Post("/post-items", {}, items, providers); // empty providers
  13695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13696. ASSERT_EQ(StatusCode::OK_200, res->status);
  13697. }
  13698. providers.push_back({"name3",
  13699. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13700. // test the offset is given correctly at each step
  13701. if (!offset)
  13702. sink.os.write(rand1.data(), 30);
  13703. else if (offset == 30)
  13704. sink.os.write(rand1.data() + 30, 300);
  13705. else if (offset == 330)
  13706. sink.os.write(rand1.data() + 330, 670);
  13707. else if (offset == rand1.size())
  13708. sink.done();
  13709. return true;
  13710. },
  13711. "filename3",
  13712. {}});
  13713. providers.push_back({"name4",
  13714. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13715. // test the offset is given correctly at each step
  13716. if (!offset)
  13717. sink.os.write(rand2.data(), 2000);
  13718. else if (offset == 2000)
  13719. sink.os.write(rand2.data() + 2000, 1);
  13720. else if (offset == 2001)
  13721. sink.os.write(rand2.data() + 2001, 999);
  13722. else if (offset == rand2.size())
  13723. sink.done();
  13724. return true;
  13725. },
  13726. "filename4",
  13727. {}});
  13728. {
  13729. auto res = cli.Post("/post-providers", {}, {}, providers);
  13730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13731. ASSERT_EQ(StatusCode::OK_200, res->status);
  13732. }
  13733. {
  13734. auto res = cli.Post("/post-both", {}, items, providers);
  13735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13736. ASSERT_EQ(StatusCode::OK_200, res->status);
  13737. }
  13738. }
  13739. }
  13740. TEST(MultipartFormDataTest, BadHeader) {
  13741. Server svr;
  13742. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13743. res.set_content("ok", "text/plain");
  13744. });
  13745. thread t = thread([&] { svr.listen(HOST, PORT); });
  13746. auto se = detail::scope_exit([&] {
  13747. svr.stop();
  13748. t.join();
  13749. ASSERT_FALSE(svr.is_running());
  13750. });
  13751. svr.wait_until_ready();
  13752. const std::string body =
  13753. "This is the preamble. It is to be ignored, though it\r\n"
  13754. "is a handy place for composition agents to include an\r\n"
  13755. "explanatory note to non-MIME conformant readers.\r\n"
  13756. "\r\n"
  13757. "\r\n"
  13758. "--simple boundary\r\n"
  13759. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13760. ": BAD...\r\n"
  13761. "\r\n"
  13762. "value1\r\n"
  13763. "--simple boundary\r\n"
  13764. "Content-Disposition: form-data; name=\"field2\"; "
  13765. "filename=\"example.txt\"\r\n"
  13766. "\r\n"
  13767. "value2\r\n"
  13768. "--simple boundary--\r\n"
  13769. "This is the epilogue. It is also to be ignored.\r\n";
  13770. std::string content_type =
  13771. R"(multipart/form-data; boundary="simple boundary")";
  13772. Client cli(HOST, PORT);
  13773. auto res = cli.Post("/post", body, content_type.c_str());
  13774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13775. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13776. }
  13777. TEST(MultipartFormDataTest, WithPreamble) {
  13778. Server svr;
  13779. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13780. res.set_content("ok", "text/plain");
  13781. });
  13782. thread t = thread([&] { svr.listen(HOST, PORT); });
  13783. auto se = detail::scope_exit([&] {
  13784. svr.stop();
  13785. t.join();
  13786. ASSERT_FALSE(svr.is_running());
  13787. });
  13788. svr.wait_until_ready();
  13789. const std::string body =
  13790. "This is the preamble. It is to be ignored, though it\r\n"
  13791. "is a handy place for composition agents to include an\r\n"
  13792. "explanatory note to non-MIME conformant readers.\r\n"
  13793. "\r\n"
  13794. "\r\n"
  13795. "--simple boundary\r\n"
  13796. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13797. "\r\n"
  13798. "value1\r\n"
  13799. "--simple boundary\r\n"
  13800. "Content-Disposition: form-data; name=\"field2\"; "
  13801. "filename=\"example.txt\"\r\n"
  13802. "\r\n"
  13803. "value2\r\n"
  13804. "--simple boundary--\r\n"
  13805. "This is the epilogue. It is also to be ignored.\r\n";
  13806. std::string content_type =
  13807. R"(multipart/form-data; boundary="simple boundary")";
  13808. Client cli(HOST, PORT);
  13809. auto res = cli.Post("/post", body, content_type.c_str());
  13810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13811. EXPECT_EQ(StatusCode::OK_200, res->status);
  13812. }
  13813. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13815. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13816. const ContentReader &content_reader) {
  13817. if (req.is_multipart_form_data()) {
  13818. std::vector<FormData> items;
  13819. content_reader(
  13820. [&](const FormData &file) {
  13821. items.push_back(file);
  13822. return true;
  13823. },
  13824. [&](const char *data, size_t data_length) {
  13825. items.back().content.append(data, data_length);
  13826. return true;
  13827. });
  13828. EXPECT_TRUE(std::string(items[0].name) == "document");
  13829. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13830. EXPECT_TRUE(items[0].filename == "2MB_data");
  13831. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13832. EXPECT_TRUE(items[1].name == "hello");
  13833. EXPECT_TRUE(items[1].content == "world");
  13834. EXPECT_TRUE(items[1].filename == "");
  13835. EXPECT_TRUE(items[1].content_type == "");
  13836. } else {
  13837. std::string body;
  13838. content_reader([&](const char *data, size_t data_length) {
  13839. body.append(data, data_length);
  13840. return true;
  13841. });
  13842. }
  13843. });
  13844. auto port = svr.bind_to_any_port("localhost");
  13845. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13846. auto se = detail::scope_exit([&] {
  13847. svr.stop();
  13848. t.join();
  13849. ASSERT_FALSE(svr.is_running());
  13850. });
  13851. svr.wait_until_ready();
  13852. {
  13853. std::string data(1024 * 1024 * 2, '.');
  13854. std::stringstream buffer;
  13855. buffer << data;
  13856. SSLClient cli("localhost", port);
  13857. cli.enable_server_certificate_verification(false);
  13858. UploadFormDataItems items{
  13859. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13860. {"hello", "world", "", ""},
  13861. };
  13862. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13864. ASSERT_EQ(StatusCode::OK_200, res->status);
  13865. }
  13866. }
  13867. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13868. std::string data(1024 * 1024 * 2, '&');
  13869. std::stringstream buffer;
  13870. buffer << data;
  13871. Client cli("https://localhost:8080");
  13872. UploadFormDataItems items{
  13873. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13874. {"hello", "world", "", ""},
  13875. };
  13876. for (const char &c : " \t\r\n") {
  13877. auto res =
  13878. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13879. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13880. ASSERT_FALSE(res);
  13881. }
  13882. }
  13883. TEST(MultipartFormDataTest, PutFormData) {
  13884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13885. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13886. const ContentReader &content_reader) {
  13887. if (req.is_multipart_form_data()) {
  13888. std::vector<FormData> items;
  13889. content_reader(
  13890. [&](const FormData &file) {
  13891. items.push_back(file);
  13892. return true;
  13893. },
  13894. [&](const char *data, size_t data_length) {
  13895. items.back().content.append(data, data_length);
  13896. return true;
  13897. });
  13898. EXPECT_TRUE(std::string(items[0].name) == "document");
  13899. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13900. EXPECT_TRUE(items[0].filename == "2MB_data");
  13901. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13902. EXPECT_TRUE(items[1].name == "hello");
  13903. EXPECT_TRUE(items[1].content == "world");
  13904. EXPECT_TRUE(items[1].filename == "");
  13905. EXPECT_TRUE(items[1].content_type == "");
  13906. } else {
  13907. std::string body;
  13908. content_reader([&](const char *data, size_t data_length) {
  13909. body.append(data, data_length);
  13910. return true;
  13911. });
  13912. }
  13913. });
  13914. auto port = svr.bind_to_any_port("localhost");
  13915. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13916. auto se = detail::scope_exit([&] {
  13917. svr.stop();
  13918. t.join();
  13919. ASSERT_FALSE(svr.is_running());
  13920. });
  13921. svr.wait_until_ready();
  13922. {
  13923. std::string data(1024 * 1024 * 2, '&');
  13924. std::stringstream buffer;
  13925. buffer << data;
  13926. SSLClient cli("localhost", port);
  13927. cli.enable_server_certificate_verification(false);
  13928. UploadFormDataItems items{
  13929. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13930. {"hello", "world", "", ""},
  13931. };
  13932. auto res = cli.Put("/put", items);
  13933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13934. ASSERT_EQ(StatusCode::OK_200, res->status);
  13935. }
  13936. }
  13937. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13939. svr.Put("/put_customboundary",
  13940. [&](const Request &req, const Response & /*res*/,
  13941. const ContentReader &content_reader) {
  13942. if (req.is_multipart_form_data()) {
  13943. std::vector<FormData> items;
  13944. content_reader(
  13945. [&](const FormData &file) {
  13946. items.push_back(file);
  13947. return true;
  13948. },
  13949. [&](const char *data, size_t data_length) {
  13950. items.back().content.append(data, data_length);
  13951. return true;
  13952. });
  13953. EXPECT_TRUE(std::string(items[0].name) == "document");
  13954. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13955. EXPECT_TRUE(items[0].filename == "2MB_data");
  13956. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13957. EXPECT_TRUE(items[1].name == "hello");
  13958. EXPECT_TRUE(items[1].content == "world");
  13959. EXPECT_TRUE(items[1].filename == "");
  13960. EXPECT_TRUE(items[1].content_type == "");
  13961. } else {
  13962. std::string body;
  13963. content_reader([&](const char *data, size_t data_length) {
  13964. body.append(data, data_length);
  13965. return true;
  13966. });
  13967. }
  13968. });
  13969. auto port = svr.bind_to_any_port("localhost");
  13970. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13971. auto se = detail::scope_exit([&] {
  13972. svr.stop();
  13973. t.join();
  13974. ASSERT_FALSE(svr.is_running());
  13975. });
  13976. svr.wait_until_ready();
  13977. {
  13978. std::string data(1024 * 1024 * 2, '&');
  13979. std::stringstream buffer;
  13980. buffer << data;
  13981. SSLClient cli("localhost", port);
  13982. cli.enable_server_certificate_verification(false);
  13983. UploadFormDataItems items{
  13984. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13985. {"hello", "world", "", ""},
  13986. };
  13987. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13989. ASSERT_EQ(StatusCode::OK_200, res->status);
  13990. }
  13991. }
  13992. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13993. std::string data(1024 * 1024 * 2, '&');
  13994. std::stringstream buffer;
  13995. buffer << data;
  13996. Client cli("https://localhost:8080");
  13997. cli.enable_server_certificate_verification(false);
  13998. UploadFormDataItems items{
  13999. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14000. {"hello", "world", "", ""},
  14001. };
  14002. for (const char &c : " \t\r\n") {
  14003. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14004. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14005. ASSERT_FALSE(res);
  14006. }
  14007. }
  14008. TEST(MultipartFormDataTest, AlternateFilename) {
  14009. auto handled = false;
  14010. Server svr;
  14011. svr.Post("/test", [&](const Request &req, Response &res) {
  14012. ASSERT_EQ(2u, req.form.files.size());
  14013. ASSERT_EQ(1u, req.form.fields.size());
  14014. // Test files
  14015. const auto &file1 = req.form.get_file("file1");
  14016. ASSERT_EQ("file1", file1.name);
  14017. ASSERT_EQ("A.txt", file1.filename);
  14018. ASSERT_EQ("text/plain", file1.content_type);
  14019. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14020. const auto &file2 = req.form.get_file("file2");
  14021. ASSERT_EQ("file2", file2.name);
  14022. ASSERT_EQ("a.html", file2.filename);
  14023. ASSERT_EQ("text/html", file2.content_type);
  14024. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14025. file2.content);
  14026. // Test text field
  14027. const auto &text = req.form.get_field("text");
  14028. ASSERT_EQ("text default", text);
  14029. res.set_content("ok", "text/plain");
  14030. handled = true;
  14031. });
  14032. thread t = thread([&] { svr.listen(HOST, PORT); });
  14033. auto se = detail::scope_exit([&] {
  14034. svr.stop();
  14035. t.join();
  14036. ASSERT_FALSE(svr.is_running());
  14037. ASSERT_TRUE(handled);
  14038. });
  14039. svr.wait_until_ready();
  14040. auto req = "POST /test HTTP/1.1\r\n"
  14041. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14042. "Content-Length: 399\r\n"
  14043. "\r\n"
  14044. "----------\r\n"
  14045. "Content-Disposition: form-data; name=\"text\"\r\n"
  14046. "\r\n"
  14047. "text default\r\n"
  14048. "----------\r\n"
  14049. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14050. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14051. "Content-Type: text/plain\r\n"
  14052. "\r\n"
  14053. "Content of a.txt.\r\n"
  14054. "\r\n"
  14055. "----------\r\n"
  14056. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14057. "\"a.html\"\r\n"
  14058. "Content-Type: text/html\r\n"
  14059. "\r\n"
  14060. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14061. "\r\n"
  14062. "------------\r\n";
  14063. ASSERT_TRUE(send_request(1, req));
  14064. }
  14065. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14066. auto handled = false;
  14067. Server svr;
  14068. svr.Post("/test", [&](const Request &req, Response &res) {
  14069. // Case-insensitive "utf-8''" prefix with a long value
  14070. const auto &file = req.form.get_file("file1");
  14071. ASSERT_EQ("file1", file.name);
  14072. // 8000 chars exercises both the Content-Disposition parser and the
  14073. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14074. // Prior to the fix, std::regex_match on this header would cause O(N)
  14075. // stack recursion in libstdc++, leading to SIGSEGV.
  14076. std::string expected_filename(8000, 'A');
  14077. ASSERT_EQ(expected_filename, file.filename);
  14078. res.set_content("ok", "text/plain");
  14079. handled = true;
  14080. });
  14081. thread t = thread([&] { svr.listen(HOST, PORT); });
  14082. auto se = detail::scope_exit([&] {
  14083. svr.stop();
  14084. t.join();
  14085. ASSERT_FALSE(svr.is_running());
  14086. ASSERT_TRUE(handled);
  14087. });
  14088. svr.wait_until_ready();
  14089. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14090. // Regression test for GHSA-qq6v-r583-3h69
  14091. std::string long_filename(8000, 'A');
  14092. std::string body = "----------\r\n"
  14093. "Content-Disposition: form-data; name=\"file1\"; "
  14094. "filename*=\"Utf-8''" +
  14095. long_filename +
  14096. "\"\r\n"
  14097. "\r\n"
  14098. "hello\r\n"
  14099. "------------\r\n";
  14100. auto req = "POST /test HTTP/1.1\r\n"
  14101. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14102. "Content-Length: " +
  14103. std::to_string(body.size()) + "\r\n\r\n" + body;
  14104. ASSERT_TRUE(send_request(1, req));
  14105. }
  14106. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14107. auto handled = false;
  14108. Server svr;
  14109. svr.Post("/test", [&](const Request &req, Response &) {
  14110. ASSERT_EQ(2u, req.form.fields.size());
  14111. const auto &text1 = req.form.get_field("text1");
  14112. ASSERT_EQ("text1", text1);
  14113. const auto &text2 = req.form.get_field("text2");
  14114. ASSERT_EQ("text2", text2);
  14115. handled = true;
  14116. });
  14117. thread t = thread([&] { svr.listen(HOST, PORT); });
  14118. auto se = detail::scope_exit([&] {
  14119. svr.stop();
  14120. t.join();
  14121. ASSERT_FALSE(svr.is_running());
  14122. ASSERT_TRUE(handled);
  14123. });
  14124. svr.wait_until_ready();
  14125. auto req = "POST /test HTTP/1.1\r\n"
  14126. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14127. "Content-Length: 146\r\n"
  14128. "\r\n----------\r\n"
  14129. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14130. "\r\n"
  14131. "text1"
  14132. "\r\n----------\r\n"
  14133. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14134. "\r\n"
  14135. "text2"
  14136. "\r\n------------";
  14137. std::string response;
  14138. ASSERT_TRUE(send_request(1, req, &response));
  14139. ASSERT_EQ("200", response.substr(9, 3));
  14140. }
  14141. TEST(MultipartFormDataTest, ContentLength) {
  14142. auto handled = false;
  14143. Server svr;
  14144. svr.Post("/test", [&](const Request &req, Response &) {
  14145. ASSERT_EQ(2u, req.form.fields.size());
  14146. const auto &text1 = req.form.get_field("text1");
  14147. ASSERT_EQ("text1", text1);
  14148. const auto &text2 = req.form.get_field("text2");
  14149. ASSERT_EQ("text2", text2);
  14150. handled = true;
  14151. });
  14152. thread t = thread([&] { svr.listen(HOST, PORT); });
  14153. auto se = detail::scope_exit([&] {
  14154. svr.stop();
  14155. t.join();
  14156. ASSERT_FALSE(svr.is_running());
  14157. ASSERT_TRUE(handled);
  14158. });
  14159. svr.wait_until_ready();
  14160. auto req = "POST /test HTTP/1.1\r\n"
  14161. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14162. "Content-Length: 167\r\n"
  14163. "\r\n----------\r\n"
  14164. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14165. "Content-Length: 5\r\n"
  14166. "\r\n"
  14167. "text1"
  14168. "\r\n----------\r\n"
  14169. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14170. "\r\n"
  14171. "text2"
  14172. "\r\n------------\r\n";
  14173. std::string response;
  14174. ASSERT_TRUE(send_request(1, req, &response));
  14175. ASSERT_EQ("200", response.substr(9, 3));
  14176. }
  14177. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14178. auto handled = false;
  14179. Server svr;
  14180. svr.Post("/test", [&](const Request &req, Response &) {
  14181. ASSERT_EQ(2u, req.form.fields.size());
  14182. const auto &text1 = req.form.get_field("text1");
  14183. ASSERT_EQ("text1", text1);
  14184. // TODO: Add header access for text fields if needed
  14185. const auto &text2 = req.form.get_field("text2");
  14186. ASSERT_EQ("text2", text2);
  14187. // TODO: Header access for text fields needs to be implemented
  14188. // auto &headers = it->second.headers;
  14189. // ASSERT_EQ(3U, headers.size());
  14190. // auto custom_header = headers.find("x-whatever");
  14191. // ASSERT_TRUE(custom_header != headers.end());
  14192. // ASSERT_NE("customvalue", custom_header->second);
  14193. // ASSERT_EQ("CustomValue", custom_header->second);
  14194. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14195. handled = true;
  14196. });
  14197. thread t = thread([&] { svr.listen(HOST, PORT); });
  14198. auto se = detail::scope_exit([&] {
  14199. svr.stop();
  14200. t.join();
  14201. ASSERT_FALSE(svr.is_running());
  14202. ASSERT_TRUE(handled);
  14203. });
  14204. svr.wait_until_ready();
  14205. auto req = "POST /test HTTP/1.1\r\n"
  14206. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14207. "Content-Length: 232\r\n"
  14208. "\r\n----------\r\n"
  14209. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14210. "Content-Length: 5\r\n"
  14211. "X-Test: 1\r\n"
  14212. "\r\n"
  14213. "text1"
  14214. "\r\n----------\r\n"
  14215. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14216. "Content-Type: text/plain\r\n"
  14217. "X-Whatever: CustomValue\r\n"
  14218. "\r\n"
  14219. "text2"
  14220. "\r\n------------\r\n"
  14221. "That should be disregarded. Not even read";
  14222. std::string response;
  14223. ASSERT_TRUE(send_request(1, req, &response));
  14224. ASSERT_EQ("200", response.substr(9, 3));
  14225. }
  14226. TEST(MultipartFormDataTest, LargeHeader) {
  14227. auto handled = false;
  14228. Server svr;
  14229. svr.Post("/test", [&](const Request &req, Response &) {
  14230. ASSERT_EQ(1u, req.form.fields.size());
  14231. const auto &text = req.form.get_field("name1");
  14232. ASSERT_EQ("text1", text);
  14233. handled = true;
  14234. });
  14235. thread t = thread([&] { svr.listen(HOST, PORT); });
  14236. auto se = detail::scope_exit([&] {
  14237. svr.stop();
  14238. t.join();
  14239. ASSERT_FALSE(svr.is_running());
  14240. ASSERT_TRUE(handled);
  14241. });
  14242. svr.wait_until_ready();
  14243. auto boundary = std::string("cpp-httplib-multipart-data");
  14244. std::string content = "--" + boundary +
  14245. "\r\n"
  14246. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14247. "\r\n"
  14248. "text1\r\n"
  14249. "--" +
  14250. boundary + "--\r\n";
  14251. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14252. "Content-Type: multipart/form-data;boundary=" +
  14253. boundary +
  14254. "\r\n"
  14255. "Content-Length: " +
  14256. std::to_string(content.size()) +
  14257. "\r\n"
  14258. "Dummy-Header: ";
  14259. std::string header_suffix = "\r\n"
  14260. "\r\n";
  14261. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14262. size_t header_dummy_size =
  14263. read_buff_size -
  14264. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14265. auto header_dummy = std::string(header_dummy_size, '@');
  14266. auto req = header_prefix + header_dummy + header_suffix + content;
  14267. std::string response;
  14268. ASSERT_TRUE(send_request(1, req, &response));
  14269. ASSERT_EQ("200", response.substr(9, 3));
  14270. }
  14271. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14272. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14273. // (not chunked Transfer-Encoding) after the streaming refactor.
  14274. auto handled = false;
  14275. Server svr;
  14276. svr.Post("/upload", [&](const Request &req, Response &res) {
  14277. auto cl_it = req.headers.find("Content-Length");
  14278. EXPECT_TRUE(cl_it != req.headers.end());
  14279. auto te_it = req.headers.find("Transfer-Encoding");
  14280. EXPECT_TRUE(te_it == req.headers.end());
  14281. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14282. res.set_content("ok", "text/plain");
  14283. handled = true;
  14284. });
  14285. auto port = svr.bind_to_any_port(HOST);
  14286. auto t = thread([&] { svr.listen_after_bind(); });
  14287. auto se = detail::scope_exit([&] {
  14288. svr.stop();
  14289. t.join();
  14290. ASSERT_FALSE(svr.is_running());
  14291. ASSERT_TRUE(handled);
  14292. });
  14293. svr.wait_until_ready();
  14294. UploadFormDataItems items = {
  14295. {"field1", "hello", "", "text/plain"},
  14296. {"file1", "world", "test.txt", "application/octet-stream"},
  14297. };
  14298. Client cli(HOST, port);
  14299. auto res = cli.Post("/upload", {}, items);
  14300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14301. EXPECT_EQ(StatusCode::OK_200, res->status);
  14302. }
  14303. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14304. // Verify that make_multipart_content_provider coalesces many small segments
  14305. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14306. constexpr size_t kItemCount = 1000;
  14307. UploadFormDataItems items;
  14308. items.reserve(kItemCount);
  14309. for (size_t i = 0; i < kItemCount; i++) {
  14310. items.push_back(
  14311. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14312. }
  14313. const std::string boundary = "----test-boundary";
  14314. auto content_length = detail::get_multipart_content_length(items, boundary);
  14315. auto provider = detail::make_multipart_content_provider(items, boundary);
  14316. // Drive the provider the same way write_content_with_progress does
  14317. size_t write_count = 0;
  14318. size_t total_bytes = 0;
  14319. DataSink sink;
  14320. size_t offset = 0;
  14321. sink.write = [&](const char *d, size_t l) -> bool {
  14322. (void)d;
  14323. write_count++;
  14324. total_bytes += l;
  14325. offset += l;
  14326. return true;
  14327. };
  14328. sink.is_writable = []() -> bool { return true; };
  14329. while (offset < content_length) {
  14330. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14331. }
  14332. EXPECT_EQ(content_length, total_bytes);
  14333. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14334. // With buffering into 64KB blocks, write_count should be much smaller.
  14335. auto segment_count = 3 * kItemCount + 1;
  14336. EXPECT_LT(write_count, segment_count / 10);
  14337. }
  14338. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14339. // Integration test: send many UploadFormDataItems and verify the server
  14340. // receives all of them correctly (#2410).
  14341. constexpr size_t kItemCount = 500;
  14342. auto handled = false;
  14343. Server svr;
  14344. svr.Post("/upload", [&](const Request &req, Response &res) {
  14345. EXPECT_EQ(kItemCount, req.form.fields.size());
  14346. for (size_t i = 0; i < kItemCount; i++) {
  14347. auto key = "field" + std::to_string(i);
  14348. auto val = "value" + std::to_string(i);
  14349. auto it = req.form.fields.find(key);
  14350. if (it != req.form.fields.end()) {
  14351. EXPECT_EQ(val, it->second.content);
  14352. } else {
  14353. ADD_FAILURE() << "Missing field: " << key;
  14354. }
  14355. }
  14356. res.set_content("ok", "text/plain");
  14357. handled = true;
  14358. });
  14359. auto port = svr.bind_to_any_port(HOST);
  14360. auto t = thread([&] { svr.listen_after_bind(); });
  14361. auto se = detail::scope_exit([&] {
  14362. svr.stop();
  14363. t.join();
  14364. ASSERT_FALSE(svr.is_running());
  14365. ASSERT_TRUE(handled);
  14366. });
  14367. svr.wait_until_ready();
  14368. UploadFormDataItems items;
  14369. items.reserve(kItemCount);
  14370. for (size_t i = 0; i < kItemCount; i++) {
  14371. items.push_back(
  14372. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14373. }
  14374. Client cli(HOST, port);
  14375. auto res = cli.Post("/upload", items);
  14376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14377. EXPECT_EQ(StatusCode::OK_200, res->status);
  14378. }
  14379. TEST(MultipartFormDataTest, MakeFileProvider) {
  14380. // Verify make_file_provider sends a file's contents correctly.
  14381. const std::string file_content(4096, 'Z');
  14382. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14383. {
  14384. std::ofstream ofs(tmp_path, std::ios::binary);
  14385. ofs.write(file_content.data(),
  14386. static_cast<std::streamsize>(file_content.size()));
  14387. }
  14388. auto handled = false;
  14389. Server svr;
  14390. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14391. const ContentReader &content_reader) {
  14392. ASSERT_TRUE(req.is_multipart_form_data());
  14393. std::vector<FormData> items;
  14394. content_reader(
  14395. [&](const FormData &file) {
  14396. items.push_back(file);
  14397. return true;
  14398. },
  14399. [&](const char *data, size_t data_length) {
  14400. items.back().content.append(data, data_length);
  14401. return true;
  14402. });
  14403. ASSERT_EQ(1u, items.size());
  14404. EXPECT_EQ("myfile", items[0].name);
  14405. EXPECT_EQ("data.bin", items[0].filename);
  14406. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14407. EXPECT_EQ(file_content, items[0].content);
  14408. handled = true;
  14409. });
  14410. auto port = svr.bind_to_any_port(HOST);
  14411. auto t = thread([&] { svr.listen_after_bind(); });
  14412. auto se = detail::scope_exit([&] {
  14413. svr.stop();
  14414. t.join();
  14415. ASSERT_FALSE(svr.is_running());
  14416. ASSERT_TRUE(handled);
  14417. std::remove(tmp_path.c_str());
  14418. });
  14419. svr.wait_until_ready();
  14420. FormDataProviderItems providers;
  14421. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14422. "application/octet-stream"));
  14423. Client cli(HOST, port);
  14424. auto res = cli.Post("/upload", {}, {}, providers);
  14425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14426. EXPECT_EQ(StatusCode::OK_200, res->status);
  14427. }
  14428. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14429. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14430. // (100) headers is rejected with a 400 Bad Request response.
  14431. Server svr;
  14432. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14433. res.set_content("ok", "text/plain");
  14434. });
  14435. thread t = thread([&] { svr.listen(HOST, PORT); });
  14436. auto se = detail::scope_exit([&] {
  14437. svr.stop();
  14438. t.join();
  14439. ASSERT_FALSE(svr.is_running());
  14440. });
  14441. svr.wait_until_ready();
  14442. // Build a multipart part with 101 custom headers (exceeding
  14443. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14444. std::stringstream body;
  14445. body << "--simpleboundary\r\n"
  14446. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14447. for (int i = 0; i < 101; i++) {
  14448. body << "X-Custom-Header-" << i << ": value\r\n";
  14449. }
  14450. body << "\r\n"
  14451. << "value1\r\n"
  14452. << "--simpleboundary--\r\n";
  14453. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14454. Client cli(HOST, PORT);
  14455. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14458. }
  14459. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14460. // A body that never contains the declared boundary must not be accumulated
  14461. // while the parser waits for it. Buffering it would also make every read
  14462. // rescan everything seen so far, which is quadratic in the body size.
  14463. Server svr;
  14464. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14465. res.set_content("ok", "text/plain");
  14466. });
  14467. auto port = svr.bind_to_any_port(HOST);
  14468. thread t = thread([&] { svr.listen_after_bind(); });
  14469. auto se = detail::scope_exit([&] {
  14470. svr.stop();
  14471. t.join();
  14472. ASSERT_FALSE(svr.is_running());
  14473. });
  14474. svr.wait_until_ready();
  14475. Client cli(HOST, port);
  14476. cli.set_read_timeout(60, 0);
  14477. cli.set_write_timeout(60, 0);
  14478. // '-' is the worst case: it matches the first character of the boundary, so
  14479. // every position has to be checked against it.
  14480. auto post_dashes = [&](size_t size) {
  14481. const std::string body(size, '-');
  14482. auto start = std::chrono::steady_clock::now();
  14483. auto res =
  14484. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14485. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14486. std::chrono::steady_clock::now() - start)
  14487. .count();
  14488. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14489. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14490. return ms;
  14491. };
  14492. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14493. // Windows.
  14494. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14495. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14496. // Comparing the two sizes rather than checking an absolute duration keeps
  14497. // this meaningful across build types and CI load, both of which move the
  14498. // absolute numbers by more than an order of magnitude. Four times the bytes
  14499. // costs about four times the time when parsing is linear, and about sixteen
  14500. // times when the body is buffered and rescanned.
  14501. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14502. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14503. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14504. << "ms, which suggests the body is being buffered and rescanned";
  14505. }
  14506. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14507. // A boundary can only be followed by CRLF or by "--", so anything else is
  14508. // malformed no matter what comes next. The parser must say so right away
  14509. // instead of buffering the rest of the declared body.
  14510. Server svr;
  14511. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14512. res.set_content("ok", "text/plain");
  14513. });
  14514. auto port = svr.bind_to_any_port(HOST);
  14515. thread t = thread([&] { svr.listen_after_bind(); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. ASSERT_FALSE(svr.is_running());
  14520. });
  14521. svr.wait_until_ready();
  14522. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14523. // buffers instead of failing would still be waiting for the remaining bytes.
  14524. const std::string body = "--zzzz\r\n"
  14525. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14526. "\r\n"
  14527. "text1"
  14528. "\r\n--zzzzXX";
  14529. const std::string req = "POST /post HTTP/1.1\r\n"
  14530. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14531. "Content-Length: 1048576\r\n"
  14532. "\r\n" +
  14533. body;
  14534. std::string response;
  14535. ASSERT_TRUE(send_request(3, req, &response, port));
  14536. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14537. EXPECT_EQ("400", response.substr(9, 3));
  14538. }
  14539. // Posts a multipart body split into two writes, so that the server sees the
  14540. // split at whatever offset the caller chose, and expects the single "text1"
  14541. // field to come through.
  14542. static void expect_split_multipart_ok(const std::string &body1,
  14543. const std::string &body2) {
  14544. auto handled = false;
  14545. Server svr;
  14546. svr.Post("/post", [&](const Request &req, Response &) {
  14547. EXPECT_EQ(1u, req.form.fields.size());
  14548. EXPECT_EQ("text1", req.form.get_field("text1"));
  14549. handled = true;
  14550. });
  14551. auto port = svr.bind_to_any_port(HOST);
  14552. thread t = thread([&] { svr.listen_after_bind(); });
  14553. auto se = detail::scope_exit([&] {
  14554. svr.stop();
  14555. t.join();
  14556. ASSERT_FALSE(svr.is_running());
  14557. ASSERT_TRUE(handled);
  14558. });
  14559. svr.wait_until_ready();
  14560. // "Connection: close" makes the server close once it has answered, so the
  14561. // response drain ends immediately instead of idling until the read timeout.
  14562. const std::string head =
  14563. "POST /post HTTP/1.1\r\n"
  14564. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14565. "Connection: close\r\n"
  14566. "Content-Length: " +
  14567. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14568. std::string response;
  14569. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14570. ASSERT_GE(response.size(), 12u) << "no response";
  14571. EXPECT_EQ("200", response.substr(9, 3));
  14572. }
  14573. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14574. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14575. // ignored, including when it does not arrive in the same read as the
  14576. // close-delimiter itself.
  14577. expect_split_multipart_ok("--zzzz\r\n"
  14578. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14579. "\r\n"
  14580. "text1"
  14581. "\r\n--zzzz--",
  14582. "\r\nthis epilogue must be ignored\r\n");
  14583. }
  14584. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14585. // The initial boundary may be preceded by a preamble of any length and may
  14586. // straddle a read boundary. Discarding data while waiting for it must not
  14587. // throw away a partial boundary sitting at the end of the buffer.
  14588. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14589. "zz\r\n"
  14590. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14591. "\r\n"
  14592. "text1"
  14593. "\r\n--zzzz--\r\n");
  14594. }
  14595. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14596. // The received boundary was only checked for being non-empty, so it could be
  14597. // as long as a header is allowed to be. The parser scans the body for
  14598. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14599. // costs a nearly full comparison at nearly every position, making the
  14600. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14601. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14602. Server svr;
  14603. svr.Post("/post", [](const Request &req, Response &res) {
  14604. EXPECT_EQ(1u, req.form.fields.size());
  14605. EXPECT_EQ("text1", req.form.get_field("text1"));
  14606. res.set_content("ok", "text/plain");
  14607. });
  14608. auto port = svr.bind_to_any_port(HOST);
  14609. thread t = thread([&] { svr.listen_after_bind(); });
  14610. auto se = detail::scope_exit([&] {
  14611. svr.stop();
  14612. t.join();
  14613. ASSERT_FALSE(svr.is_running());
  14614. });
  14615. svr.wait_until_ready();
  14616. Client cli(HOST, port);
  14617. auto post_with_boundary_of_length = [&](size_t len) {
  14618. const std::string boundary(len, 'a');
  14619. const std::string body =
  14620. "--" + boundary +
  14621. "\r\n"
  14622. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14623. "\r\n"
  14624. "text1"
  14625. "\r\n--" +
  14626. boundary + "--\r\n";
  14627. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14628. };
  14629. auto res = post_with_boundary_of_length(70);
  14630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14631. EXPECT_EQ(StatusCode::OK_200, res->status);
  14632. res = post_with_boundary_of_length(71);
  14633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14634. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14635. }
  14636. TEST(MakeFileBodyTest, Basic) {
  14637. const std::string file_content(4096, 'Z');
  14638. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14639. {
  14640. std::ofstream ofs(tmp_path, std::ios::binary);
  14641. ofs.write(file_content.data(),
  14642. static_cast<std::streamsize>(file_content.size()));
  14643. }
  14644. auto handled = false;
  14645. Server svr;
  14646. svr.Post("/upload", [&](const Request &req, Response &res) {
  14647. EXPECT_EQ(file_content, req.body);
  14648. handled = true;
  14649. res.status = StatusCode::OK_200;
  14650. });
  14651. auto port = svr.bind_to_any_port(HOST);
  14652. auto t = thread([&] { svr.listen_after_bind(); });
  14653. auto se = detail::scope_exit([&] {
  14654. svr.stop();
  14655. t.join();
  14656. ASSERT_FALSE(svr.is_running());
  14657. ASSERT_TRUE(handled);
  14658. std::remove(tmp_path.c_str());
  14659. });
  14660. svr.wait_until_ready();
  14661. auto fb = make_file_body(tmp_path);
  14662. ASSERT_GT(fb.first, 0u);
  14663. Client cli(HOST, port);
  14664. auto res =
  14665. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14667. EXPECT_EQ(StatusCode::OK_200, res->status);
  14668. }
  14669. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14670. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14671. {
  14672. std::ofstream ofs(path, std::ios::binary);
  14673. const std::string content(100, 'A');
  14674. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14675. }
  14676. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14677. auto body = make_file_body(path);
  14678. ASSERT_EQ(100u, body.first);
  14679. ASSERT_TRUE(static_cast<bool>(body.second));
  14680. // Rewritten shorter after its length was measured - and, on a server, after
  14681. // that length has already gone out as Content-Length.
  14682. {
  14683. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14684. const std::string content(10, 'A');
  14685. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14686. }
  14687. std::string written;
  14688. DataSink sink;
  14689. sink.write = [&](const char *d, size_t l) {
  14690. written.append(d, l);
  14691. return true;
  14692. };
  14693. // The provider has to report failure. write_content_with_progress() advances
  14694. // its offset only by what was written, so a provider that returns true
  14695. // without completing the length it promised is called again straight away,
  14696. // and again.
  14697. EXPECT_FALSE(body.second(0, body.first, sink));
  14698. EXPECT_EQ(std::string(10, 'A'), written);
  14699. }
  14700. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14701. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14702. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14703. {
  14704. std::ofstream ofs(path, std::ios::binary);
  14705. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14706. }
  14707. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14708. auto body = make_file_body(path);
  14709. ASSERT_EQ(content.size(), body.first);
  14710. ASSERT_TRUE(static_cast<bool>(body.second));
  14711. std::string written;
  14712. DataSink sink;
  14713. sink.write = [&](const char *d, size_t l) {
  14714. written.append(d, l);
  14715. return true;
  14716. };
  14717. EXPECT_TRUE(body.second(0, body.first, sink));
  14718. EXPECT_EQ(content, written);
  14719. }
  14720. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14721. static constexpr unsigned int number_of_tasks{1000000};
  14722. std::atomic_uint count{0};
  14723. std::unique_ptr<TaskQueue> task_queue{
  14724. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14725. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14726. auto queued = task_queue->enqueue(
  14727. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14728. EXPECT_TRUE(queued);
  14729. }
  14730. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14731. task_queue->shutdown();
  14732. #else
  14733. EXPECT_NO_THROW(task_queue->shutdown());
  14734. #endif
  14735. EXPECT_EQ(number_of_tasks, count.load());
  14736. }
  14737. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14738. static constexpr unsigned int number_of_tasks{1000000};
  14739. static constexpr unsigned int qlimit{2};
  14740. unsigned int queued_count{0};
  14741. std::atomic_uint count{0};
  14742. std::unique_ptr<TaskQueue> task_queue{
  14743. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14744. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14745. if (task_queue->enqueue(
  14746. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14747. queued_count++;
  14748. }
  14749. }
  14750. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14751. task_queue->shutdown();
  14752. #else
  14753. EXPECT_NO_THROW(task_queue->shutdown());
  14754. #endif
  14755. EXPECT_EQ(queued_count, count.load());
  14756. EXPECT_TRUE(queued_count <= number_of_tasks);
  14757. EXPECT_TRUE(queued_count >= qlimit);
  14758. }
  14759. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14760. // Use a short idle timeout so a dynamic thread spawns, times out and
  14761. // exits during the test, and the pool keeps working afterwards.
  14762. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14763. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14764. /*idle_timeout_sec=*/1}};
  14765. std::atomic_uint count{0};
  14766. std::condition_variable cv;
  14767. std::mutex mtx;
  14768. bool release = false;
  14769. // Block the base thread so the second task spawns a dynamic thread.
  14770. EXPECT_TRUE(task_queue->enqueue([&] {
  14771. std::unique_lock<std::mutex> lock(mtx);
  14772. while (!release) {
  14773. cv.wait(lock);
  14774. }
  14775. count++;
  14776. }));
  14777. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14778. // Let the dynamic thread finish its task and exceed the idle timeout.
  14779. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14780. {
  14781. std::unique_lock<std::mutex> lock(mtx);
  14782. release = true;
  14783. }
  14784. cv.notify_all();
  14785. // The pool must still accept and run tasks after the dynamic thread exited.
  14786. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14787. task_queue->shutdown();
  14788. EXPECT_EQ(3u, count.load());
  14789. }
  14790. TEST(TaskQueueTest, MaxQueuedRequests) {
  14791. static constexpr unsigned int qlimit{3};
  14792. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14793. std::condition_variable sem_cv;
  14794. std::mutex sem_mtx;
  14795. int credits = 0;
  14796. bool queued;
  14797. /* Fill up the queue with tasks that will block until we give them credits to
  14798. * complete. */
  14799. for (unsigned int n = 0; n <= qlimit;) {
  14800. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14801. std::unique_lock<std::mutex> lock(sem_mtx);
  14802. while (credits <= 0) {
  14803. sem_cv.wait(lock);
  14804. }
  14805. /* Consume the credit and signal the test code if they are all gone. */
  14806. if (--credits == 0) { sem_cv.notify_one(); }
  14807. });
  14808. if (n < qlimit) {
  14809. /* The first qlimit enqueues must succeed. */
  14810. EXPECT_TRUE(queued);
  14811. } else {
  14812. /* The last one will succeed only when the worker thread
  14813. * starts and dequeues the first blocking task. Although
  14814. * not necessary for the correctness of this test, we sleep for
  14815. * a short while to avoid busy waiting. */
  14816. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14817. }
  14818. if (queued) { n++; }
  14819. }
  14820. /* Further enqueues must fail since the queue is full. */
  14821. for (auto i = 0; i < 4; i++) {
  14822. queued = task_queue->enqueue([] {});
  14823. EXPECT_FALSE(queued);
  14824. }
  14825. /* Give the credits to allow the previous tasks to complete. */
  14826. {
  14827. std::unique_lock<std::mutex> lock(sem_mtx);
  14828. credits += qlimit + 1;
  14829. }
  14830. sem_cv.notify_all();
  14831. /* Wait for all the credits to be consumed. */
  14832. {
  14833. std::unique_lock<std::mutex> lock(sem_mtx);
  14834. while (credits > 0) {
  14835. sem_cv.wait(lock);
  14836. }
  14837. }
  14838. /* Check that we are able again to enqueue at least qlimit tasks. */
  14839. for (unsigned int i = 0; i < qlimit; i++) {
  14840. queued = task_queue->enqueue([] {});
  14841. EXPECT_TRUE(queued);
  14842. }
  14843. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14844. task_queue->shutdown();
  14845. #else
  14846. EXPECT_NO_THROW(task_queue->shutdown());
  14847. #endif
  14848. }
  14849. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14850. Server svr;
  14851. std::string method;
  14852. std::string body;
  14853. auto has_content_length = false;
  14854. auto has_transfer_encoding = false;
  14855. std::atomic<int> bad_requests{0};
  14856. // Leftover body bytes get parsed as a malformed request and answered with
  14857. // 400
  14858. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14859. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14860. });
  14861. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14862. res.set_redirect("/down", StatusCode::SeeOther_303);
  14863. });
  14864. svr.Get("/down", [&](const Request &req, Response &res) {
  14865. method = req.method;
  14866. body = req.body;
  14867. has_content_length = req.has_header("Content-Length");
  14868. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14869. res.set_content("ok", "text/plain");
  14870. });
  14871. auto port = svr.bind_to_any_port(HOST);
  14872. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14873. auto se = detail::scope_exit([&] {
  14874. svr.stop();
  14875. thread.join();
  14876. ASSERT_FALSE(svr.is_running());
  14877. });
  14878. svr.wait_until_ready();
  14879. const std::string payload = "SECRET-BODY";
  14880. auto check = [&](Client &cli, const Result &res) {
  14881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14882. EXPECT_EQ(StatusCode::OK_200, res->status);
  14883. EXPECT_EQ("ok", res->body);
  14884. EXPECT_EQ("GET", method);
  14885. EXPECT_TRUE(body.empty());
  14886. EXPECT_FALSE(has_content_length);
  14887. EXPECT_FALSE(has_transfer_encoding);
  14888. // Nothing of the original body may be left on the connection
  14889. auto res2 = cli.Get("/down");
  14890. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14891. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14892. EXPECT_EQ("ok", res2->body);
  14893. EXPECT_EQ(0, bad_requests);
  14894. };
  14895. // With content length
  14896. {
  14897. Client cli(HOST, port);
  14898. cli.set_keep_alive(true);
  14899. cli.set_follow_location(true);
  14900. auto res = cli.Post(
  14901. "/up", payload.size(),
  14902. [&](size_t offset, size_t length, DataSink &sink) {
  14903. return sink.write(payload.data() + offset, length);
  14904. },
  14905. "text/plain");
  14906. check(cli, res);
  14907. }
  14908. // Without content length (chunked)
  14909. {
  14910. Client cli(HOST, port);
  14911. cli.set_keep_alive(true);
  14912. cli.set_follow_location(true);
  14913. auto res = cli.Post(
  14914. "/up",
  14915. [&](size_t /*offset*/, DataSink &sink) {
  14916. sink.write(payload.data(), payload.size());
  14917. sink.done();
  14918. return true;
  14919. },
  14920. "text/plain");
  14921. check(cli, res);
  14922. }
  14923. }
  14924. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14925. Server svr;
  14926. std::string target;
  14927. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14928. // Echo the still-encoded name back in the Location
  14929. const std::string prefix = "/start/";
  14930. res.status = StatusCode::Found_302;
  14931. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14932. });
  14933. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14934. target = req.target;
  14935. res.set_content("ok", "text/plain");
  14936. });
  14937. auto port = svr.bind_to_any_port(HOST);
  14938. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14939. auto se = detail::scope_exit([&] {
  14940. svr.stop();
  14941. thread.join();
  14942. ASSERT_FALSE(svr.is_running());
  14943. });
  14944. svr.wait_until_ready();
  14945. // Decoding the Location path would turn the first four into a path
  14946. // separator, a query delimiter, a fragment delimiter and a different
  14947. // percent-encoded octet. The rest must keep reaching the server as they are.
  14948. const std::vector<std::string> names = {
  14949. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14950. };
  14951. for (auto path_encode : {true, false}) {
  14952. Client cli(HOST, port);
  14953. cli.set_follow_location(true);
  14954. cli.set_path_encode(path_encode);
  14955. for (const auto &name : names) {
  14956. target.clear();
  14957. auto res = cli.Get("/start/" + name);
  14958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14959. EXPECT_EQ(StatusCode::OK_200, res->status);
  14960. EXPECT_EQ("/dest/" + name, target);
  14961. }
  14962. }
  14963. }
  14964. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14965. Server svr;
  14966. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14967. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14968. });
  14969. svr.Get("/hello", [](const Request &req, Response &res) {
  14970. res.set_content(req.get_param_value("key"), "text/plain");
  14971. });
  14972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14973. auto se = detail::scope_exit([&] {
  14974. svr.stop();
  14975. thread.join();
  14976. ASSERT_FALSE(svr.is_running());
  14977. });
  14978. svr.wait_until_ready();
  14979. {
  14980. Client cli(HOST, PORT);
  14981. cli.set_follow_location(true);
  14982. auto res = cli.Get("/");
  14983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14984. EXPECT_EQ(StatusCode::OK_200, res->status);
  14985. EXPECT_EQ("val&key2=val2", res->body);
  14986. }
  14987. }
  14988. #endif
  14989. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14990. Server svr;
  14991. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14992. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14993. });
  14994. svr.Get("/hello", [](const Request &req, Response &res) {
  14995. res.set_content(req.get_param_value("key"), "text/plain");
  14996. });
  14997. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14998. auto se = detail::scope_exit([&] {
  14999. svr.stop();
  15000. thread.join();
  15001. ASSERT_FALSE(svr.is_running());
  15002. });
  15003. svr.wait_until_ready();
  15004. {
  15005. Client cli(HOST, PORT);
  15006. cli.set_follow_location(true);
  15007. auto res = cli.Get("/");
  15008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15009. EXPECT_EQ(StatusCode::OK_200, res->status);
  15010. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15011. }
  15012. }
  15013. TEST(RedirectTest, RedirectWithPlusInPath) {
  15014. Server svr;
  15015. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15016. res.set_redirect("/a+b");
  15017. });
  15018. // Route pattern uses regex; escape + as \\+
  15019. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15020. res.set_content(req.path, "text/plain");
  15021. });
  15022. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15023. auto se = detail::scope_exit([&] {
  15024. svr.stop();
  15025. thread.join();
  15026. ASSERT_FALSE(svr.is_running());
  15027. });
  15028. svr.wait_until_ready();
  15029. {
  15030. Client cli(HOST, PORT);
  15031. cli.set_follow_location(true);
  15032. auto res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. EXPECT_EQ(StatusCode::OK_200, res->status);
  15035. EXPECT_EQ("/a+b", res->body);
  15036. }
  15037. }
  15038. TEST(RedirectTest, ResolveRelativeLocation) {
  15039. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15040. const std::vector<std::pair<std::string, std::string>> cases = {
  15041. {"g", "/b/c/g"},
  15042. {"./g", "/b/c/g"},
  15043. {"g/", "/b/c/g/"},
  15044. {"?y", "/b/c/d;p?y"},
  15045. {"g?y", "/b/c/g?y"},
  15046. {"#s", "/b/c/d;p?q#s"},
  15047. {"g#s", "/b/c/g#s"},
  15048. {"g?y#s", "/b/c/g?y#s"},
  15049. {";x", "/b/c/;x"},
  15050. {"g;x", "/b/c/g;x"},
  15051. {".", "/b/c/"},
  15052. {"./", "/b/c/"},
  15053. {"..", "/b/"},
  15054. {"../", "/b/"},
  15055. {"../g", "/b/g"},
  15056. {"../..", "/"},
  15057. {"../../", "/"},
  15058. {"../../g", "/g"},
  15059. {"../../../g", "/g"},
  15060. {"g.", "/b/c/g."},
  15061. {".g", "/b/c/.g"},
  15062. {"g..", "/b/c/g.."},
  15063. {"..g", "/b/c/..g"},
  15064. {"./../g", "/b/g"},
  15065. {"./g/.", "/b/c/g/"},
  15066. {"g/./h", "/b/c/g/h"},
  15067. {"g/../h", "/b/c/h"},
  15068. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15069. {"g;x=1/../y", "/b/c/y"},
  15070. {"g?y/./x", "/b/c/g?y/./x"},
  15071. {"g#s/../x", "/b/c/g#s/../x"},
  15072. // Not relative-path references, so left for parse_url.
  15073. {"/g", "/g"},
  15074. {"//g", "//g"},
  15075. {"http://g/x", "http://g/x"},
  15076. {"g:h", "g:h"},
  15077. };
  15078. for (const auto &c : cases) {
  15079. EXPECT_EQ(c.second,
  15080. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15081. << c.first;
  15082. }
  15083. }
  15084. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15085. Server svr;
  15086. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15087. res.set_redirect(req.get_param_value("to"));
  15088. });
  15089. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15090. res.set_content(req.target, "text/plain");
  15091. });
  15092. svr.Get("/other", [](const Request &req, Response &res) {
  15093. res.set_content(req.target, "text/plain");
  15094. });
  15095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15096. auto se = detail::scope_exit([&] {
  15097. svr.stop();
  15098. thread.join();
  15099. ASSERT_FALSE(svr.is_running());
  15100. });
  15101. svr.wait_until_ready();
  15102. const std::vector<std::pair<std::string, std::string>> cases = {
  15103. {"next", "/dir/next"},
  15104. {"./next?x=1", "/dir/next?x=1"},
  15105. {"../other", "/other"},
  15106. };
  15107. for (const auto &c : cases) {
  15108. Client cli(HOST, PORT);
  15109. cli.set_follow_location(true);
  15110. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15111. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15112. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15113. EXPECT_EQ(c.second, res->body) << c.first;
  15114. }
  15115. }
  15116. #ifdef CPPHTTPLIB_SSL_ENABLED
  15117. TEST(RedirectTest, Issue2185_Online) {
  15118. SSLClient client("github.com");
  15119. client.set_follow_location(true);
  15120. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15121. "Coollab-Windows.zip");
  15122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15123. EXPECT_EQ(StatusCode::OK_200, res->status);
  15124. EXPECT_EQ(9920427U, res->body.size());
  15125. }
  15126. #endif
  15127. TEST(VulnerabilityTest, CRLFInjection) {
  15128. Server svr;
  15129. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15130. res.set_content("Hello 1", "text/plain");
  15131. });
  15132. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15133. res.set_content("Hello 2", "text/plain");
  15134. });
  15135. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15136. res.set_content("Hello 3", "text/plain");
  15137. });
  15138. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15139. res.set_content("Hello 4", "text/plain");
  15140. });
  15141. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15142. for (const auto &x : req.headers) {
  15143. auto key = x.first;
  15144. EXPECT_STRNE("evil", key.c_str());
  15145. }
  15146. });
  15147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15148. auto se = detail::scope_exit([&] {
  15149. svr.stop();
  15150. thread.join();
  15151. ASSERT_FALSE(svr.is_running());
  15152. });
  15153. svr.wait_until_ready();
  15154. {
  15155. Client cli(HOST, PORT);
  15156. cli.Post("/test1", "A=B",
  15157. "application/x-www-form-urlencoded\r\nevil: hello1");
  15158. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15159. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15160. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15161. }
  15162. }
  15163. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15164. auto server_thread = std::thread([] {
  15165. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15166. default_socket_options(srv);
  15167. sockaddr_in addr{};
  15168. addr.sin_family = AF_INET;
  15169. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15170. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15171. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15172. ::listen(srv, 1);
  15173. sockaddr_in cli_addr{};
  15174. socklen_t cli_len = sizeof(cli_addr);
  15175. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15176. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15177. std::string buf_all;
  15178. char buf[2048];
  15179. ssize_t n;
  15180. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15181. buf_all.append(buf, static_cast<size_t>(n));
  15182. size_t pos;
  15183. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15184. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15185. auto e = request_block.find("\r\n");
  15186. if (e != std::string::npos) {
  15187. auto request_line = request_block.substr(0, e);
  15188. std::string msg =
  15189. "CRLF injection detected in request line: '" + request_line + "'";
  15190. EXPECT_FALSE(true) << msg;
  15191. }
  15192. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15193. ::send(cli,
  15194. #ifdef _WIN32
  15195. static_cast<const char *>(resp.c_str()),
  15196. static_cast<int>(resp.size()),
  15197. #else
  15198. resp.c_str(), resp.size(),
  15199. #endif
  15200. 0);
  15201. buf_all.erase(0, pos + 4);
  15202. }
  15203. }
  15204. detail::close_socket(cli);
  15205. detail::close_socket(srv);
  15206. });
  15207. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15208. auto cli = Client("127.0.0.1", PORT + 1);
  15209. auto headers = Headers{
  15210. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15211. {"Connection", "keep-alive"}};
  15212. auto res = cli.Get("/hi", headers);
  15213. EXPECT_FALSE(res);
  15214. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15215. server_thread.join();
  15216. }
  15217. // A request rejected before any byte reaches the socket must fail right away
  15218. // instead of waiting for a response the server will never send.
  15219. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15220. // The kernel completes the TCP handshake from the listen backlog, so the
  15221. // client connects, but nothing ever reads, responds or closes.
  15222. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15223. default_socket_options(srv);
  15224. sockaddr_in addr{};
  15225. addr.sin_family = AF_INET;
  15226. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15227. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15228. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15229. ASSERT_EQ(0, ::listen(srv, 8));
  15230. auto cli = Client("127.0.0.1", PORT + 1);
  15231. cli.set_read_timeout(10, 0);
  15232. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15233. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15234. std::chrono::steady_clock::now() - start)
  15235. .count();
  15236. };
  15237. {
  15238. Request req;
  15239. req.method = "GE T";
  15240. req.path = "/";
  15241. auto start = std::chrono::steady_clock::now();
  15242. auto res = cli.send(req);
  15243. EXPECT_FALSE(res);
  15244. EXPECT_EQ(Error::Write, res.error());
  15245. EXPECT_LT(elapsed_ms(start), 1000);
  15246. }
  15247. {
  15248. auto start = std::chrono::steady_clock::now();
  15249. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15250. EXPECT_FALSE(res);
  15251. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15252. EXPECT_LT(elapsed_ms(start), 1000);
  15253. }
  15254. EXPECT_FALSE(cli.is_socket_open());
  15255. detail::close_socket(srv);
  15256. }
  15257. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15258. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15259. default_socket_options(srv);
  15260. sockaddr_in addr{};
  15261. addr.sin_family = AF_INET;
  15262. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15263. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15264. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15265. ASSERT_EQ(0, ::listen(srv, 1));
  15266. std::string received;
  15267. auto server_thread = std::thread([&] {
  15268. auto sock = ::accept(srv, nullptr, nullptr);
  15269. if (sock == INVALID_SOCKET) { return; }
  15270. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15271. char buf[2048];
  15272. ssize_t n;
  15273. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15274. received.append(buf, static_cast<size_t>(n));
  15275. }
  15276. detail::close_socket(sock);
  15277. });
  15278. {
  15279. auto cli = Client("127.0.0.1", PORT + 1);
  15280. // "Z" sorts after the default headers, so writing straight to the socket
  15281. // would have sent the request line and those headers before the rejection.
  15282. auto handle =
  15283. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15284. EXPECT_FALSE(handle.is_valid());
  15285. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15286. }
  15287. server_thread.join();
  15288. detail::close_socket(srv);
  15289. EXPECT_TRUE(received.empty()) << received;
  15290. }
  15291. TEST(PathParamsTest, StaticMatch) {
  15292. const auto pattern = "/users/all";
  15293. detail::PathParamsMatcher matcher(pattern);
  15294. Request request;
  15295. request.path = "/users/all";
  15296. ASSERT_TRUE(matcher.match(request));
  15297. std::unordered_map<std::string, std::string> expected_params = {};
  15298. EXPECT_EQ(request.path_params, expected_params);
  15299. }
  15300. TEST(PathParamsTest, StaticMismatch) {
  15301. const auto pattern = "/users/all";
  15302. detail::PathParamsMatcher matcher(pattern);
  15303. Request request;
  15304. request.path = "/users/1";
  15305. ASSERT_FALSE(matcher.match(request));
  15306. }
  15307. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15308. const auto pattern = "/users/:id/subscriptions";
  15309. detail::PathParamsMatcher matcher(pattern);
  15310. Request request;
  15311. request.path = "/users/42/subscriptions";
  15312. ASSERT_TRUE(matcher.match(request));
  15313. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15314. EXPECT_EQ(request.path_params, expected_params);
  15315. }
  15316. TEST(PathParamsTest, SingleParamInTheEnd) {
  15317. const auto pattern = "/users/:id";
  15318. detail::PathParamsMatcher matcher(pattern);
  15319. Request request;
  15320. request.path = "/users/24";
  15321. ASSERT_TRUE(matcher.match(request));
  15322. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15323. EXPECT_EQ(request.path_params, expected_params);
  15324. }
  15325. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15326. const auto pattern = "/users/:id/";
  15327. detail::PathParamsMatcher matcher(pattern);
  15328. Request request;
  15329. request.path = "/users/42/";
  15330. ASSERT_TRUE(matcher.match(request));
  15331. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15332. EXPECT_EQ(request.path_params, expected_params);
  15333. }
  15334. TEST(PathParamsTest, EmptyParam) {
  15335. const auto pattern = "/users/:id/";
  15336. detail::PathParamsMatcher matcher(pattern);
  15337. Request request;
  15338. request.path = "/users//";
  15339. ASSERT_TRUE(matcher.match(request));
  15340. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15341. EXPECT_EQ(request.path_params, expected_params);
  15342. }
  15343. TEST(PathParamsTest, FragmentMismatch) {
  15344. const auto pattern = "/users/:id/";
  15345. detail::PathParamsMatcher matcher(pattern);
  15346. Request request;
  15347. request.path = "/admins/24/";
  15348. ASSERT_FALSE(matcher.match(request));
  15349. }
  15350. TEST(PathParamsTest, ExtraFragments) {
  15351. const auto pattern = "/users/:id";
  15352. detail::PathParamsMatcher matcher(pattern);
  15353. Request request;
  15354. request.path = "/users/42/subscriptions";
  15355. ASSERT_FALSE(matcher.match(request));
  15356. }
  15357. TEST(PathParamsTest, MissingTrailingParam) {
  15358. const auto pattern = "/users/:id";
  15359. detail::PathParamsMatcher matcher(pattern);
  15360. Request request;
  15361. request.path = "/users";
  15362. ASSERT_FALSE(matcher.match(request));
  15363. }
  15364. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15365. const auto pattern = "/users/:id/subscriptions";
  15366. detail::PathParamsMatcher matcher(pattern);
  15367. Request request;
  15368. request.path = "/users/subscriptions";
  15369. ASSERT_FALSE(matcher.match(request));
  15370. }
  15371. TEST(PathParamsTest, MultipleParams) {
  15372. const auto pattern = "/users/:userid/subscriptions/:subid";
  15373. detail::PathParamsMatcher matcher(pattern);
  15374. Request request;
  15375. request.path = "/users/42/subscriptions/2";
  15376. ASSERT_TRUE(matcher.match(request));
  15377. std::unordered_map<std::string, std::string> expected_params = {
  15378. {"userid", "42"}, {"subid", "2"}};
  15379. EXPECT_EQ(request.path_params, expected_params);
  15380. }
  15381. TEST(PathParamsTest, SequenceOfParams) {
  15382. const auto pattern = "/values/:x/:y/:z";
  15383. detail::PathParamsMatcher matcher(pattern);
  15384. Request request;
  15385. request.path = "/values/1/2/3";
  15386. ASSERT_TRUE(matcher.match(request));
  15387. std::unordered_map<std::string, std::string> expected_params = {
  15388. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15389. EXPECT_EQ(request.path_params, expected_params);
  15390. }
  15391. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15392. const auto pattern = "/prefix:suffix";
  15393. detail::PathParamsMatcher matcher(pattern);
  15394. Request request;
  15395. request.path = "/prefix:suffix";
  15396. ASSERT_TRUE(matcher.match(request));
  15397. const std::unordered_map<std::string, std::string> expected_params = {};
  15398. EXPECT_EQ(request.path_params, expected_params);
  15399. }
  15400. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15401. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15402. // calling thread's stack on a long enough path for a quantified pattern;
  15403. // RegexMatcher must refuse to run regex matching on paths beyond
  15404. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15405. detail::RegexMatcher matcher("/files/(.*)");
  15406. Request within_limit;
  15407. within_limit.path = "/files/" + std::string(10, 'A');
  15408. EXPECT_TRUE(matcher.match(within_limit));
  15409. Request over_limit;
  15410. over_limit.path =
  15411. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15412. EXPECT_FALSE(matcher.match(over_limit));
  15413. }
  15414. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15415. Server svr;
  15416. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15417. res.set_content("ok", "text/plain");
  15418. });
  15419. auto port = svr.bind_to_any_port(HOST);
  15420. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15421. auto se = detail::scope_exit([&] {
  15422. svr.stop();
  15423. thread.join();
  15424. ASSERT_FALSE(svr.is_running());
  15425. });
  15426. svr.wait_until_ready();
  15427. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15428. // request URI limit; this used to be able to crash the process.
  15429. std::string path =
  15430. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15431. std::string req = "GET " + path +
  15432. " HTTP/1.1\r\n"
  15433. "Host: " +
  15434. std::string(HOST) + ":" + std::to_string(port) +
  15435. "\r\n"
  15436. "Connection: close\r\n"
  15437. "\r\n";
  15438. std::string response;
  15439. ASSERT_TRUE(send_request(5, req, &response, port));
  15440. EXPECT_NE(std::string::npos, response.find("404"));
  15441. }
  15442. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15443. Server svr;
  15444. auto handler = [](const Request & /*req*/, Response &res) {
  15445. res.set_content("hit", "text/plain");
  15446. };
  15447. // No regex metacharacter, so this one is compared literally
  15448. svr.Get("/literal/route", handler);
  15449. // '.' is a regex metacharacter, so this one must keep regex semantics
  15450. svr.Get("/a.c", handler);
  15451. auto port = svr.bind_to_any_port(HOST);
  15452. std::thread t([&]() { svr.listen_after_bind(); });
  15453. auto se = detail::scope_exit([&] {
  15454. svr.stop();
  15455. t.join();
  15456. ASSERT_FALSE(svr.is_running());
  15457. });
  15458. svr.wait_until_ready();
  15459. Client cli(HOST, port);
  15460. struct {
  15461. const char *path;
  15462. int status;
  15463. } cases[] = {
  15464. {"/literal/route", StatusCode::OK_200},
  15465. {"/literal/routes", StatusCode::NotFound_404},
  15466. {"/literal/rout", StatusCode::NotFound_404},
  15467. {"/abc", StatusCode::OK_200},
  15468. {"/a.c", StatusCode::OK_200},
  15469. };
  15470. for (const auto &x : cases) {
  15471. auto res = cli.Get(x.path);
  15472. ASSERT_TRUE(res) << x.path;
  15473. EXPECT_EQ(x.status, res->status) << x.path;
  15474. }
  15475. }
  15476. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15477. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15478. // from exhausting the stack, so it must only constrain routes that actually
  15479. // run a regular expression. A literal route is matched by comparison and
  15480. // stays usable at any length.
  15481. Server svr;
  15482. const std::string pattern =
  15483. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15484. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15485. res.set_content("hit", "text/plain");
  15486. });
  15487. auto port = svr.bind_to_any_port(HOST);
  15488. std::thread t([&]() { svr.listen_after_bind(); });
  15489. auto se = detail::scope_exit([&] {
  15490. svr.stop();
  15491. t.join();
  15492. ASSERT_FALSE(svr.is_running());
  15493. });
  15494. svr.wait_until_ready();
  15495. Client cli(HOST, port);
  15496. auto res = cli.Get(pattern);
  15497. ASSERT_TRUE(res);
  15498. EXPECT_EQ(StatusCode::OK_200, res->status);
  15499. }
  15500. TEST(ParseUrlTest, VariousPatterns) {
  15501. {
  15502. detail::UrlComponents uc;
  15503. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15504. EXPECT_EQ("http", uc.scheme);
  15505. EXPECT_EQ("example.com", uc.host);
  15506. EXPECT_EQ("8080", uc.port);
  15507. EXPECT_EQ("/path", uc.path);
  15508. EXPECT_EQ("?q=1", uc.query);
  15509. }
  15510. {
  15511. detail::UrlComponents uc;
  15512. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15513. EXPECT_EQ("https", uc.scheme);
  15514. EXPECT_EQ("example.com", uc.host);
  15515. EXPECT_TRUE(uc.port.empty());
  15516. EXPECT_EQ("/path", uc.path);
  15517. }
  15518. {
  15519. detail::UrlComponents uc;
  15520. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15521. EXPECT_EQ("::1", uc.host);
  15522. EXPECT_EQ("8080", uc.port);
  15523. EXPECT_EQ("/path", uc.path);
  15524. }
  15525. {
  15526. detail::UrlComponents uc;
  15527. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15528. }
  15529. {
  15530. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15531. // the path while the connection still targets the bracketed host.
  15532. detail::UrlComponents uc;
  15533. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15534. }
  15535. {
  15536. detail::UrlComponents uc;
  15537. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15538. }
  15539. {
  15540. detail::UrlComponents uc;
  15541. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15542. EXPECT_EQ("::1", uc.host);
  15543. EXPECT_TRUE(uc.port.empty());
  15544. EXPECT_EQ("/path", uc.path);
  15545. }
  15546. {
  15547. detail::UrlComponents uc;
  15548. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15549. EXPECT_TRUE(uc.scheme.empty());
  15550. EXPECT_EQ("example.com", uc.host);
  15551. EXPECT_EQ("/path", uc.path);
  15552. EXPECT_EQ("?q=1", uc.query);
  15553. }
  15554. {
  15555. detail::UrlComponents uc;
  15556. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15557. EXPECT_TRUE(uc.host.empty());
  15558. EXPECT_EQ("/path", uc.path);
  15559. EXPECT_EQ("?q=1", uc.query);
  15560. }
  15561. {
  15562. detail::UrlComponents uc;
  15563. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15564. EXPECT_EQ("example.com", uc.host);
  15565. EXPECT_EQ("8080", uc.port);
  15566. }
  15567. {
  15568. // Unix socket path — must not be parsed as host
  15569. detail::UrlComponents uc;
  15570. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15571. EXPECT_TRUE(uc.host.empty());
  15572. }
  15573. {
  15574. detail::UrlComponents uc;
  15575. ASSERT_TRUE(detail::parse_url("", uc));
  15576. EXPECT_TRUE(uc.host.empty());
  15577. EXPECT_TRUE(uc.path.empty());
  15578. }
  15579. {
  15580. detail::UrlComponents uc;
  15581. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15582. }
  15583. {
  15584. detail::UrlComponents uc;
  15585. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15586. }
  15587. {
  15588. // Accepted by parse_url; callers restrict to http/https
  15589. detail::UrlComponents uc;
  15590. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15591. EXPECT_EQ("ftp", uc.scheme);
  15592. }
  15593. {
  15594. detail::UrlComponents uc;
  15595. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15596. }
  15597. {
  15598. detail::UrlComponents uc;
  15599. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15600. }
  15601. }
  15602. TEST(ParseUrlTest, FragmentHandling) {
  15603. {
  15604. detail::UrlComponents uc;
  15605. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15606. EXPECT_EQ("/path", uc.path);
  15607. EXPECT_TRUE(uc.query.empty());
  15608. }
  15609. {
  15610. detail::UrlComponents uc;
  15611. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15612. EXPECT_TRUE(uc.path.empty());
  15613. EXPECT_TRUE(uc.query.empty());
  15614. }
  15615. }
  15616. TEST(ParseUrlTest, UserinfoHandling) {
  15617. // Userinfo with @ but no colon — host includes @
  15618. detail::UrlComponents uc;
  15619. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15620. EXPECT_EQ("user@host.com", uc.host);
  15621. EXPECT_EQ("/path", uc.path);
  15622. }
  15623. TEST(ParseUrlTest, IPv6EdgeCases) {
  15624. {
  15625. detail::UrlComponents uc;
  15626. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15627. EXPECT_TRUE(uc.scheme.empty());
  15628. EXPECT_EQ("::1", uc.host);
  15629. EXPECT_EQ("8080", uc.port);
  15630. }
  15631. {
  15632. // Zone ID '%25' is not in [a-fA-F0-9:]
  15633. detail::UrlComponents uc;
  15634. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15635. }
  15636. }
  15637. TEST(ParseUrlTest, SchemeEdgeCases) {
  15638. {
  15639. detail::UrlComponents uc;
  15640. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15641. }
  15642. {
  15643. detail::UrlComponents uc;
  15644. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15645. }
  15646. {
  15647. detail::UrlComponents uc;
  15648. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15649. }
  15650. }
  15651. TEST(ParseUrlTest, PortEdgeCases) {
  15652. {
  15653. detail::UrlComponents uc;
  15654. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15655. EXPECT_TRUE(uc.port.empty());
  15656. EXPECT_EQ("/path", uc.path);
  15657. }
  15658. {
  15659. // parse_url accepts any port string; validation is done by parse_port
  15660. detail::UrlComponents uc;
  15661. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15662. EXPECT_EQ("abc", uc.port);
  15663. }
  15664. }
  15665. TEST(ParseUrlTest, WebSocketPatterns) {
  15666. {
  15667. detail::UrlComponents uc;
  15668. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15669. EXPECT_EQ("ws", uc.scheme);
  15670. EXPECT_EQ("echo.example.com", uc.host);
  15671. EXPECT_EQ("8080", uc.port);
  15672. EXPECT_EQ("/ws", uc.path);
  15673. }
  15674. {
  15675. detail::UrlComponents uc;
  15676. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15677. EXPECT_EQ("wss", uc.scheme);
  15678. EXPECT_EQ("echo.example.com", uc.host);
  15679. EXPECT_TRUE(uc.port.empty());
  15680. EXPECT_EQ("/ws", uc.path);
  15681. }
  15682. }
  15683. TEST(ParseUrlTest, QueryOnly) {
  15684. detail::UrlComponents uc;
  15685. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15686. EXPECT_TRUE(uc.host.empty());
  15687. EXPECT_TRUE(uc.path.empty());
  15688. EXPECT_EQ("?q=1&r=2", uc.query);
  15689. }
  15690. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15691. detail::UrlComponents uc;
  15692. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15693. EXPECT_TRUE(uc.scheme.empty());
  15694. EXPECT_EQ("example.com", uc.host);
  15695. EXPECT_EQ("443", uc.port);
  15696. EXPECT_EQ("/path", uc.path);
  15697. }
  15698. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15699. // If ipv6 regex working, regex match codepath is taken.
  15700. // else port will default to 80 in Client impl
  15701. int clientImplMagicPort = 80;
  15702. int port = 4321;
  15703. // above ports must be different to avoid false negative
  15704. EXPECT_NE(clientImplMagicPort, port);
  15705. std::string ipV6TestURL = "http://[ff06::c3]";
  15706. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15707. CLIENT_PRIVATE_KEY_FILE);
  15708. EXPECT_EQ(cli.port(), port);
  15709. }
  15710. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15711. auto file_path = "./www/dir/index.html";
  15712. auto dir_path = "./www/dir";
  15713. detail::FileStat stat_file(file_path);
  15714. EXPECT_TRUE(stat_file.is_file());
  15715. EXPECT_FALSE(stat_file.is_dir());
  15716. detail::FileStat stat_dir(dir_path);
  15717. EXPECT_FALSE(stat_dir.is_file());
  15718. EXPECT_TRUE(stat_dir.is_dir());
  15719. }
  15720. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15721. // IPv4 with default HTTP port (80)
  15722. EXPECT_EQ("example.com",
  15723. detail::make_host_and_port_string("example.com", 80, false));
  15724. // IPv4 with default HTTPS port (443)
  15725. EXPECT_EQ("example.com",
  15726. detail::make_host_and_port_string("example.com", 443, true));
  15727. // IPv4 with non-default HTTP port
  15728. EXPECT_EQ("example.com:8080",
  15729. detail::make_host_and_port_string("example.com", 8080, false));
  15730. // IPv4 with non-default HTTPS port
  15731. EXPECT_EQ("example.com:8443",
  15732. detail::make_host_and_port_string("example.com", 8443, true));
  15733. // IPv6 with default HTTP port (80)
  15734. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15735. // IPv6 with default HTTPS port (443)
  15736. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15737. // IPv6 with non-default HTTP port
  15738. EXPECT_EQ("[::1]:8080",
  15739. detail::make_host_and_port_string("::1", 8080, false));
  15740. // IPv6 with non-default HTTPS port
  15741. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15742. // IPv6 full address with default port
  15743. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15744. detail::make_host_and_port_string(
  15745. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15746. // IPv6 full address with non-default port
  15747. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15748. detail::make_host_and_port_string(
  15749. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15750. // IPv6 localhost with non-default port
  15751. EXPECT_EQ("[::1]:3000",
  15752. detail::make_host_and_port_string("::1", 3000, false));
  15753. // IPv6 with zone ID (link-local address) with default port
  15754. EXPECT_EQ("[fe80::1%eth0]",
  15755. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15756. // IPv6 with zone ID (link-local address) with non-default port
  15757. EXPECT_EQ("[fe80::1%eth0]:8080",
  15758. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15759. // Edge case: Port 443 with is_ssl=false (should add port)
  15760. EXPECT_EQ("example.com:443",
  15761. detail::make_host_and_port_string("example.com", 443, false));
  15762. // Edge case: Port 80 with is_ssl=true (should add port)
  15763. EXPECT_EQ("example.com:80",
  15764. detail::make_host_and_port_string("example.com", 80, true));
  15765. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15766. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15767. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15768. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15769. // Security fix: Already bracketed IPv6 should not get double brackets
  15770. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15771. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15772. EXPECT_EQ("[::1]:8080",
  15773. detail::make_host_and_port_string("[::1]", 8080, false));
  15774. EXPECT_EQ("[2001:db8::1]:8080",
  15775. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15776. EXPECT_EQ("[fe80::1%eth0]",
  15777. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15778. EXPECT_EQ("[fe80::1%eth0]:8080",
  15779. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15780. // Edge case: Empty host (should return as-is)
  15781. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15782. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15783. // This is a known limitation but shouldn't crash
  15784. EXPECT_EQ("[host:name]",
  15785. detail::make_host_and_port_string("host:name", 80, false));
  15786. // Port number edge cases (no validation, but should not crash)
  15787. EXPECT_EQ("example.com:0",
  15788. detail::make_host_and_port_string("example.com", 0, false));
  15789. EXPECT_EQ("example.com:-1",
  15790. detail::make_host_and_port_string("example.com", -1, false));
  15791. EXPECT_EQ("example.com:65535",
  15792. detail::make_host_and_port_string("example.com", 65535, false));
  15793. EXPECT_EQ("example.com:65536",
  15794. detail::make_host_and_port_string("example.com", 65536, false));
  15795. }
  15796. #ifdef CPPHTTPLIB_SSL_ENABLED
  15797. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15798. httplib::SSLClient cli("roblox.com", 443);
  15799. cli.set_follow_location(true);
  15800. auto res = cli.Get("/");
  15801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15802. EXPECT_EQ(StatusCode::OK_200, res->status);
  15803. }
  15804. #endif
  15805. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15806. Server svr;
  15807. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15808. EXPECT_EQ(res.status, 400);
  15809. });
  15810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15811. auto se = detail::scope_exit([&] {
  15812. svr.stop();
  15813. thread.join();
  15814. ASSERT_FALSE(svr.is_running());
  15815. });
  15816. svr.wait_until_ready();
  15817. Client cli(HOST, PORT);
  15818. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15819. }
  15820. TEST(InvalidHeaderCharsTest, is_field_name) {
  15821. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15822. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15823. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15824. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15825. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15826. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15827. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15828. EXPECT_FALSE(detail::fields::is_field_name(""));
  15829. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15830. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15831. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15832. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15833. }
  15834. TEST(InvalidHeaderCharsTest, is_field_value) {
  15835. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15836. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15837. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15838. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15839. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15840. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15841. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15842. EXPECT_TRUE(detail::fields::is_field_value(""));
  15843. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15844. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15845. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15846. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15847. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15848. }
  15849. TEST(InvalidHeaderCharsTest, OnServer) {
  15850. Server svr;
  15851. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15852. std::string header = "Not Set";
  15853. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15854. res.set_header(header, "value");
  15855. res.set_content("Page Content Page Content", "text/plain");
  15856. });
  15857. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15858. std::string header = "Not Set";
  15859. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15860. res.set_header("X-Test", header);
  15861. res.set_content("Page Content Page Content", "text/plain");
  15862. });
  15863. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15864. auto se = detail::scope_exit([&] {
  15865. svr.stop();
  15866. thread.join();
  15867. ASSERT_FALSE(svr.is_running());
  15868. });
  15869. svr.wait_until_ready();
  15870. Client cli(HOST, PORT);
  15871. {
  15872. auto res = cli.Get(
  15873. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15875. EXPECT_EQ("Page Content Page Content", res->body);
  15876. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15877. }
  15878. {
  15879. auto res = cli.Get(
  15880. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15882. EXPECT_EQ("Page Content Page Content", res->body);
  15883. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15884. }
  15885. }
  15886. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15887. auto handled = false;
  15888. Server svr;
  15889. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15890. thread t = thread([&] { svr.listen(HOST, PORT); });
  15891. auto se = detail::scope_exit([&] {
  15892. svr.stop();
  15893. t.join();
  15894. ASSERT_FALSE(svr.is_running());
  15895. ASSERT_FALSE(handled);
  15896. });
  15897. svr.wait_until_ready();
  15898. auto req = "POST /test HTTP/1.1\r\n"
  15899. "Content-Length: x\r\n"
  15900. "\r\n";
  15901. std::string response;
  15902. ASSERT_TRUE(send_request(1, req, &response));
  15903. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15904. response.substr(0, response.find("\r\n")));
  15905. }
  15906. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15907. // case-insensitive, and a server that receives a 100-continue expectation in
  15908. // an HTTP/1.0 request MUST ignore it.
  15909. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15910. std::string response;
  15911. ASSERT_TRUE(send_request(1, req, &response, port));
  15912. *got_100 = response.find("100 Continue") != std::string::npos;
  15913. }
  15914. class ExpectTokenTest : public ::testing::Test {
  15915. protected:
  15916. void SetUp() override {
  15917. svr_.Post("/p", [](const Request &, Response &res) {
  15918. res.set_content("ok", "text/plain");
  15919. });
  15920. port_ = svr_.bind_to_any_port(HOST);
  15921. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15922. svr_.wait_until_ready();
  15923. }
  15924. void TearDown() override {
  15925. svr_.stop();
  15926. if (thread_.joinable()) { thread_.join(); }
  15927. }
  15928. std::string request(const char *version, const char *expect_value) const {
  15929. return std::string("POST /p ") + version +
  15930. "\r\n"
  15931. "Host: localhost\r\n"
  15932. "Content-Length: 2\r\n"
  15933. "Connection: close\r\n"
  15934. "Expect: " +
  15935. expect_value +
  15936. "\r\n"
  15937. "\r\n"
  15938. "hi";
  15939. }
  15940. Server svr_;
  15941. int port_ = 0;
  15942. thread thread_;
  15943. };
  15944. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15945. bool got_100 = false;
  15946. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15947. EXPECT_TRUE(got_100);
  15948. }
  15949. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15950. bool got_100 = true;
  15951. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15952. EXPECT_FALSE(got_100);
  15953. }
  15954. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15955. bool got_100 = false;
  15956. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15957. EXPECT_TRUE(got_100);
  15958. }
  15959. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15960. bool got_100 = false;
  15961. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15962. EXPECT_TRUE(got_100);
  15963. }
  15964. // `100 Continue` is sent only when the server starts reading the body, so a
  15965. // request rejected before that never invites the client to send it. The
  15966. // requests below carry the expectation but withhold the body, as a client
  15967. // waiting for `100 Continue` would.
  15968. // A POST that expects `100 Continue` and withholds its two-byte body.
  15969. static std::string expect_headers_only(const std::string &path) {
  15970. return "POST " + path +
  15971. " HTTP/1.1\r\n"
  15972. "Host: localhost\r\n"
  15973. "Content-Length: 2\r\n"
  15974. "Expect: 100-continue\r\n"
  15975. "\r\n";
  15976. }
  15977. class ExpectLazyContinueTest : public ::testing::Test {
  15978. protected:
  15979. void SetUp() override {
  15980. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15981. if (req.path == "/pre-routing") {
  15982. res.status = StatusCode::Unauthorized_401;
  15983. return Server::HandlerResponse::Handled;
  15984. }
  15985. return Server::HandlerResponse::Unhandled;
  15986. });
  15987. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15988. if (req.matched_route == "/pre-request") {
  15989. res.status = StatusCode::Forbidden_403;
  15990. return Server::HandlerResponse::Handled;
  15991. }
  15992. return Server::HandlerResponse::Unhandled;
  15993. });
  15994. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15995. res.set_content("ok", "text/plain");
  15996. });
  15997. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15998. res.set_content("ok", "text/plain");
  15999. });
  16000. svr_.Post("/reader-used", [](const Request &, Response &res,
  16001. const ContentReader &content_reader) {
  16002. std::string body;
  16003. content_reader([&](const char *data, size_t len) {
  16004. body.append(data, len);
  16005. return true;
  16006. });
  16007. res.set_content(body, "text/plain");
  16008. });
  16009. svr_.Post("/reader-unused",
  16010. [](const Request &, Response &res, const ContentReader &) {
  16011. res.set_content("ignored", "text/plain");
  16012. });
  16013. port_ = svr_.bind_to_any_port(HOST);
  16014. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16015. svr_.wait_until_ready();
  16016. }
  16017. void TearDown() override {
  16018. svr_.stop();
  16019. if (thread_.joinable()) { thread_.join(); }
  16020. }
  16021. // Sends `req` and reads until the server closes the connection. Returns
  16022. // false if the read had to wait for the client-side timeout instead.
  16023. bool send_until_closed(const std::string &req, std::string *resp) const {
  16024. auto start = std::chrono::steady_clock::now();
  16025. if (!send_request(3, req, resp, port_)) { return false; }
  16026. auto elapsed = std::chrono::steady_clock::now() - start;
  16027. return elapsed < std::chrono::seconds(2);
  16028. }
  16029. // The final response comes without `100 Continue`, and the server closes
  16030. // the connection since the body may or may not follow.
  16031. void expect_final_without_interim(const std::string &path,
  16032. const char *status_line) const {
  16033. std::string resp;
  16034. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16035. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16036. EXPECT_EQ(0u, resp.find(status_line));
  16037. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16038. }
  16039. Server svr_;
  16040. int port_ = 0;
  16041. thread thread_;
  16042. };
  16043. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16044. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16045. }
  16046. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16047. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16048. }
  16049. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16050. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16051. }
  16052. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16053. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16054. }
  16055. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16056. // The body follows once `100 Continue` has had time to arrive.
  16057. auto req = expect_headers_only("/reader-used");
  16058. req.insert(req.size() - 2, "Connection: close\r\n");
  16059. std::string resp;
  16060. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16061. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16062. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16063. EXPECT_NE(std::string::npos, resp.find("hi"));
  16064. }
  16065. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16066. // Large enough for the client to add `Expect: 100-continue` itself.
  16067. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16068. std::atomic<bool> body_sent{false};
  16069. Client cli(HOST, port_);
  16070. auto res = cli.Post(
  16071. "/pre-request", length,
  16072. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16073. body_sent = true;
  16074. std::string chunk(len, 'x');
  16075. sink.write(chunk.data(), chunk.size());
  16076. return true;
  16077. },
  16078. "application/octet-stream");
  16079. ASSERT_TRUE(res);
  16080. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16081. EXPECT_FALSE(body_sent);
  16082. }
  16083. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16084. Server svr;
  16085. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16086. return StatusCode::ExpectationFailed_417;
  16087. });
  16088. svr.Post("/p", [](const Request &, Response &res) {
  16089. res.set_content("ok", "text/plain");
  16090. });
  16091. auto port = svr.bind_to_any_port(HOST);
  16092. thread t = thread([&] { svr.listen_after_bind(); });
  16093. auto se = detail::scope_exit([&] {
  16094. svr.stop();
  16095. t.join();
  16096. });
  16097. svr.wait_until_ready();
  16098. std::string resp;
  16099. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16100. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16101. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16102. // Exactly one response: the route handler must not run after the 417.
  16103. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16104. }
  16105. #ifndef _WIN32
  16106. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16107. static constexpr char reject[] = "Unauthorized";
  16108. static constexpr char accept[] = "Upload accepted";
  16109. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16110. Server svr;
  16111. svr.set_expect_100_continue_handler(
  16112. [](const Request & /*req*/, Response &res) {
  16113. res.status = StatusCode::Unauthorized_401;
  16114. res.set_content(reject, "text/plain");
  16115. return res.status;
  16116. });
  16117. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16118. res.set_content(accept, "text/plain");
  16119. });
  16120. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16121. auto se = detail::scope_exit([&] {
  16122. svr.stop();
  16123. thread.join();
  16124. ASSERT_FALSE(svr.is_running());
  16125. });
  16126. svr.wait_until_ready();
  16127. {
  16128. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16129. curl_easy_init(), &curl_easy_cleanup};
  16130. ASSERT_NE(curl, nullptr);
  16131. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16132. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16133. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16134. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16135. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16136. &curl_slist_free_all};
  16137. ASSERT_NE(list, nullptr);
  16138. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16139. struct read_data {
  16140. size_t read_size;
  16141. size_t total_size;
  16142. } data = {0, total_size};
  16143. using read_callback_t =
  16144. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16145. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16146. void *userdata) -> size_t {
  16147. read_data *d = (read_data *)userdata;
  16148. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16149. std::fill_n(ptr, size * nmemb, 'A');
  16150. d->read_size += size * nmemb;
  16151. return size * nmemb;
  16152. };
  16153. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16154. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16155. std::vector<char> buffer;
  16156. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16157. using write_callback_t =
  16158. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16159. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16160. void *userdata) -> size_t {
  16161. std::vector<char> *buf = (std::vector<char> *)userdata;
  16162. buf->reserve(buf->size() + size * nmemb + 1);
  16163. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16164. return size * nmemb;
  16165. };
  16166. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16167. {
  16168. const auto res = curl_easy_perform(curl.get());
  16169. ASSERT_EQ(res, CURLE_OK);
  16170. }
  16171. {
  16172. auto response_code = long{};
  16173. const auto res =
  16174. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16175. ASSERT_EQ(res, CURLE_OK);
  16176. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16177. }
  16178. {
  16179. auto dl = curl_off_t{};
  16180. const auto res =
  16181. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16182. ASSERT_EQ(res, CURLE_OK);
  16183. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16184. }
  16185. {
  16186. buffer.push_back('\0');
  16187. ASSERT_STRCASEEQ(buffer.data(), reject);
  16188. }
  16189. }
  16190. }
  16191. #endif
  16192. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16193. // Regression test for #2458.
  16194. //
  16195. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16196. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16197. // ticket can make the client socket spuriously readable during the
  16198. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16199. // the client withholds the body and then blocks reading a response that never
  16200. // comes, failing with `Failed to read connection`.
  16201. //
  16202. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16203. // within the timeout. This raw OpenSSL server deliberately never sends
  16204. // `100 Continue`; the client must still deliver the body and receive 200.
  16205. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16206. signal(SIGPIPE, SIG_IGN);
  16207. const auto port = PORT + 4;
  16208. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16209. ASSERT_NE(srv, INVALID_SOCKET);
  16210. int opt = 1;
  16211. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16212. sockaddr_in addr{};
  16213. addr.sin_family = AF_INET;
  16214. addr.sin_port = htons(static_cast<uint16_t>(port));
  16215. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16216. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16217. ASSERT_EQ(0, ::listen(srv, 1));
  16218. std::atomic<size_t> server_body_bytes{0};
  16219. auto server_thread = std::thread([&] {
  16220. sockaddr_in cli_addr{};
  16221. socklen_t cli_len = sizeof(cli_addr);
  16222. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16223. if (cli == INVALID_SOCKET) { return; }
  16224. // Bound the lifetime of the server side so a buggy client (which never
  16225. // sends the body) cannot make this thread block forever on join.
  16226. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16227. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16228. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16229. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16230. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16231. SSL *ssl = SSL_new(ctx);
  16232. SSL_set_fd(ssl, static_cast<int>(cli));
  16233. if (SSL_accept(ssl) > 0) {
  16234. // Read the request headers. Reading here also flushes the TLS 1.3
  16235. // session tickets to the client. Deliberately do NOT send
  16236. // `100 Continue`.
  16237. std::string buf;
  16238. char tmp[1024];
  16239. while (buf.find("\r\n\r\n") == std::string::npos) {
  16240. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16241. if (n <= 0) { break; }
  16242. buf.append(tmp, static_cast<size_t>(n));
  16243. }
  16244. // A correct client sends the body now; count what arrives.
  16245. auto pos = buf.find("\r\n\r\n");
  16246. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16247. while (body < 4096) {
  16248. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16249. if (n <= 0) { break; }
  16250. body += static_cast<size_t>(n);
  16251. }
  16252. server_body_bytes = body;
  16253. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16254. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16255. SSL_shutdown(ssl);
  16256. }
  16257. SSL_free(ssl);
  16258. detail::close_socket(cli);
  16259. SSL_CTX_free(ctx);
  16260. });
  16261. auto se = detail::scope_exit([&] {
  16262. server_thread.join();
  16263. detail::close_socket(srv);
  16264. });
  16265. SSLClient cli("127.0.0.1", port);
  16266. cli.enable_server_certificate_verification(false);
  16267. cli.set_connection_timeout(5, 0);
  16268. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16269. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16270. std::string body(4096, 'A');
  16271. auto res = cli.Put("/api/test", body, "application/json");
  16272. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16273. EXPECT_EQ(StatusCode::OK_200, res->status);
  16274. EXPECT_EQ(body.size(), server_body_bytes.load());
  16275. }
  16276. #endif
  16277. template <typename S, typename C>
  16278. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16279. svr.Get("/stream", [&](const Request &, Response &res) {
  16280. auto data = new std::string("01234567890123456789");
  16281. res.set_content_provider(
  16282. data->size(), "text/plain",
  16283. [&, data](size_t offset, size_t length, DataSink &sink) {
  16284. const size_t DATA_CHUNK_SIZE = 4;
  16285. const auto &d = *data;
  16286. std::this_thread::sleep_for(std::chrono::seconds(1));
  16287. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16288. return true;
  16289. },
  16290. [data](bool success) {
  16291. EXPECT_FALSE(success);
  16292. delete data;
  16293. });
  16294. });
  16295. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16296. auto i = new size_t(0);
  16297. res.set_content_provider(
  16298. "text/plain",
  16299. [i](size_t, DataSink &sink) {
  16300. if (*i < 5) {
  16301. std::this_thread::sleep_for(std::chrono::seconds(1));
  16302. sink.write("abcd", 4);
  16303. (*i)++;
  16304. } else {
  16305. sink.done();
  16306. }
  16307. return true;
  16308. },
  16309. [i](bool success) {
  16310. EXPECT_FALSE(success);
  16311. delete i;
  16312. });
  16313. });
  16314. svr.Get("/chunked", [&](const Request &, Response &res) {
  16315. auto i = new size_t(0);
  16316. res.set_chunked_content_provider(
  16317. "text/plain",
  16318. [i](size_t, DataSink &sink) {
  16319. if (*i < 5) {
  16320. std::this_thread::sleep_for(std::chrono::seconds(1));
  16321. sink.os << "abcd";
  16322. (*i)++;
  16323. } else {
  16324. sink.done();
  16325. }
  16326. return true;
  16327. },
  16328. [i](bool success) {
  16329. EXPECT_FALSE(success);
  16330. delete i;
  16331. });
  16332. });
  16333. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16334. auto se = detail::scope_exit([&] {
  16335. svr.stop();
  16336. listen_thread.join();
  16337. ASSERT_FALSE(svr.is_running());
  16338. });
  16339. svr.wait_until_ready();
  16340. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16341. {
  16342. auto start = std::chrono::steady_clock::now();
  16343. auto res = cli.Get("/stream");
  16344. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16345. std::chrono::steady_clock::now() - start)
  16346. .count();
  16347. ASSERT_FALSE(res);
  16348. EXPECT_EQ(Error::Read, res.error());
  16349. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16350. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16351. }
  16352. {
  16353. auto start = std::chrono::steady_clock::now();
  16354. auto res = cli.Get("/stream_without_length");
  16355. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16356. std::chrono::steady_clock::now() - start)
  16357. .count();
  16358. ASSERT_FALSE(res);
  16359. EXPECT_EQ(Error::Read, res.error());
  16360. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16361. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16362. }
  16363. {
  16364. auto start = std::chrono::steady_clock::now();
  16365. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16366. EXPECT_EQ("abcd", string(data, data_length));
  16367. return true;
  16368. });
  16369. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16370. std::chrono::steady_clock::now() - start)
  16371. .count();
  16372. ASSERT_FALSE(res);
  16373. EXPECT_EQ(Error::Read, res.error());
  16374. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16375. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16376. }
  16377. }
  16378. TEST(MaxTimeoutTest, ContentStream) {
  16379. time_t timeout = 2000;
  16380. time_t threshold = 200;
  16381. Server svr;
  16382. Client cli("localhost", PORT);
  16383. max_timeout_test(svr, cli, timeout, threshold);
  16384. }
  16385. #ifdef CPPHTTPLIB_SSL_ENABLED
  16386. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16387. time_t timeout = 2000;
  16388. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16389. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16390. SSLClient cli("localhost", PORT);
  16391. cli.enable_server_certificate_verification(false);
  16392. max_timeout_test(svr, cli, timeout, threshold);
  16393. }
  16394. #endif
  16395. class EventDispatcher {
  16396. public:
  16397. EventDispatcher() {}
  16398. bool wait_event(DataSink *sink) {
  16399. unique_lock<mutex> lk(m_);
  16400. int id = id_;
  16401. // Wait with timeout to prevent hanging if client disconnects
  16402. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16403. [&] { return cid_ == id; })) {
  16404. return false; // Timeout occurred
  16405. }
  16406. sink->write(message_.data(), message_.size());
  16407. return true;
  16408. }
  16409. void send_event(const string &message) {
  16410. lock_guard<mutex> lk(m_);
  16411. cid_ = id_++;
  16412. message_ = message;
  16413. cv_.notify_all();
  16414. }
  16415. private:
  16416. mutex m_;
  16417. condition_variable cv_;
  16418. atomic_int id_{0};
  16419. atomic_int cid_{-1};
  16420. string message_;
  16421. };
  16422. TEST(ClientInThreadTest, Issue2068) {
  16423. EventDispatcher ed;
  16424. Server svr;
  16425. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16426. res.set_chunked_content_provider("text/event-stream",
  16427. [&](size_t /*offset*/, DataSink &sink) {
  16428. return ed.wait_event(&sink);
  16429. });
  16430. });
  16431. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16432. svr.wait_until_ready();
  16433. thread event_thread([&] {
  16434. int id = 0;
  16435. while (svr.is_running()) {
  16436. this_thread::sleep_for(chrono::milliseconds(500));
  16437. std::stringstream ss;
  16438. ss << "data: " << id << "\n\n";
  16439. ed.send_event(ss.str());
  16440. id++;
  16441. }
  16442. });
  16443. auto se = detail::scope_exit([&] {
  16444. svr.stop();
  16445. listen_thread.join();
  16446. event_thread.join();
  16447. ASSERT_FALSE(svr.is_running());
  16448. });
  16449. {
  16450. auto client = detail::make_unique<Client>(HOST, PORT);
  16451. client->set_read_timeout(std::chrono::minutes(10));
  16452. std::atomic<bool> stop{false};
  16453. std::thread t([&] {
  16454. client->Get("/event1",
  16455. [&](const char *, size_t) -> bool { return !stop; });
  16456. });
  16457. std::this_thread::sleep_for(std::chrono::seconds(2));
  16458. stop = true;
  16459. client->stop();
  16460. t.join();
  16461. // Reset client after thread has finished
  16462. client.reset();
  16463. }
  16464. }
  16465. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16466. auto handled = false;
  16467. Server svr;
  16468. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16469. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16470. auto se = detail::scope_exit([&] {
  16471. svr.stop();
  16472. t.join();
  16473. ASSERT_FALSE(svr.is_running());
  16474. ASSERT_FALSE(handled);
  16475. });
  16476. svr.wait_until_ready();
  16477. // Two Content-Length headers with different values — must be rejected
  16478. auto req = "POST /test HTTP/1.1\r\n"
  16479. "Content-Length: 5\r\n"
  16480. "Content-Length: 10\r\n"
  16481. "\r\n"
  16482. "hello";
  16483. std::string response;
  16484. ASSERT_TRUE(send_request(1, req, &response));
  16485. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16486. response.substr(0, response.find("\r\n")));
  16487. }
  16488. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16489. auto handled = false;
  16490. Server svr;
  16491. svr.Post("/test", [&](const Request &, Response &res) {
  16492. handled = true;
  16493. res.set_content("ok", "text/plain");
  16494. });
  16495. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16496. auto se = detail::scope_exit([&] {
  16497. svr.stop();
  16498. t.join();
  16499. ASSERT_FALSE(svr.is_running());
  16500. ASSERT_TRUE(handled);
  16501. });
  16502. svr.wait_until_ready();
  16503. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16504. auto req = "POST /test HTTP/1.1\r\n"
  16505. "Content-Length: 5\r\n"
  16506. "Content-Length: 5\r\n"
  16507. "\r\n"
  16508. "hello";
  16509. std::string response;
  16510. ASSERT_TRUE(send_request(1, req, &response));
  16511. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16512. }
  16513. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16514. Server svr;
  16515. svr.Get("/test", [](const Request &, Response &res) {
  16516. res.set_content("ok", "text/plain");
  16517. });
  16518. auto port = svr.bind_to_any_port(HOST);
  16519. thread t = thread([&] { svr.listen_after_bind(); });
  16520. auto se = detail::scope_exit([&] {
  16521. svr.stop();
  16522. t.join();
  16523. ASSERT_FALSE(svr.is_running());
  16524. });
  16525. svr.wait_until_ready();
  16526. auto status_line = [&](const std::string &host_lines) {
  16527. std::string res;
  16528. send_request(
  16529. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16530. &res, port);
  16531. return res.substr(0, res.find("\r\n"));
  16532. };
  16533. const char *accepted[] = {
  16534. "Host: localhost\r\n",
  16535. "Host: a.example:8080\r\n",
  16536. "Host: my_service\r\n",
  16537. "Host: [::1]:8080\r\n",
  16538. "Host: [fe80::1%25eth0]\r\n",
  16539. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16540. };
  16541. for (auto host_lines : accepted) {
  16542. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16543. }
  16544. const char *rejected[] = {
  16545. "Host: a.example\r\nHost: b.example\r\n",
  16546. "Host: a.example\r\nHost: a.example\r\n",
  16547. "Host: a@b.example\r\n",
  16548. "Host: a.example/b\r\n",
  16549. "Host: a.example\\b\r\n",
  16550. "Host: a.example?b\r\n",
  16551. "Host: a.example#b\r\n",
  16552. "Host: a.example b.example\r\n",
  16553. };
  16554. for (auto host_lines : rejected) {
  16555. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16556. << host_lines;
  16557. }
  16558. }
  16559. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16560. Server svr;
  16561. svr.Get("/", [](const Request &req, Response &res) {
  16562. EXPECT_EQ(2U, req.trailers.size());
  16563. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16564. // Denied
  16565. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16566. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16567. // Accepted
  16568. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16569. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16570. EXPECT_TRUE(req.has_trailer("X-World"));
  16571. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16572. res.set_content("ok", "text/plain");
  16573. });
  16574. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16575. auto se = detail::scope_exit([&] {
  16576. svr.stop();
  16577. t.join();
  16578. ASSERT_FALSE(svr.is_running());
  16579. });
  16580. svr.wait_until_ready();
  16581. const std::string req = "GET / HTTP/1.1\r\n"
  16582. "Transfer-Encoding: chunked\r\n"
  16583. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16584. "\r\n"
  16585. "0\r\n"
  16586. "Content-Length: 10\r\n"
  16587. "Host: internal.local\r\n"
  16588. "Content-Type: malicious/content\r\n"
  16589. "Cookie: any\r\n"
  16590. "Set-Cookie: any\r\n"
  16591. "X-Forwarded-For: attacker.com\r\n"
  16592. "X-Real-Ip: 1.1.1.1\r\n"
  16593. "X-Hello: hello\r\n"
  16594. "X-World: world\r\n"
  16595. "\r\n";
  16596. std::string res;
  16597. ASSERT_TRUE(send_request(1, req, &res));
  16598. }
  16599. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16600. // several field lines, and the combined value is what has to be parsed. A
  16601. // Trailer field split across lines therefore declares every name it lists;
  16602. // reading only the first line silently drops the trailers the later lines
  16603. // declare. The prohibited-trailer filter still applies to every line.
  16604. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16605. Server svr;
  16606. size_t observed_trailer_count = 0;
  16607. std::string observed_hello;
  16608. std::string observed_world;
  16609. bool observed_content_length = true;
  16610. svr.Get("/", [&](const Request &req, Response &res) {
  16611. observed_trailer_count = req.trailers.size();
  16612. observed_hello = req.get_trailer_value("X-Hello");
  16613. observed_world = req.get_trailer_value("X-World");
  16614. observed_content_length = req.has_trailer("Content-Length");
  16615. res.set_content("ok", "text/plain");
  16616. });
  16617. auto port = svr.bind_to_any_port(HOST);
  16618. thread t = thread([&]() { svr.listen_after_bind(); });
  16619. auto se = detail::scope_exit([&] {
  16620. svr.stop();
  16621. t.join();
  16622. ASSERT_FALSE(svr.is_running());
  16623. });
  16624. svr.wait_until_ready();
  16625. const std::string req = "GET / HTTP/1.1\r\n"
  16626. "Transfer-Encoding: chunked\r\n"
  16627. "Trailer: X-Hello\r\n"
  16628. "Trailer: X-World, Content-Length\r\n"
  16629. "\r\n"
  16630. "0\r\n"
  16631. "X-Hello: hello\r\n"
  16632. "X-World: world\r\n"
  16633. "Content-Length: 10\r\n"
  16634. "\r\n";
  16635. std::string res;
  16636. ASSERT_TRUE(send_request(1, req, &res, port));
  16637. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16638. // Accepted: both field lines contribute to the declared set
  16639. EXPECT_EQ(2U, observed_trailer_count);
  16640. EXPECT_EQ(observed_hello, "hello");
  16641. EXPECT_EQ(observed_world, "world");
  16642. // Denied: a prohibited name stays prohibited on a later field line
  16643. EXPECT_FALSE(observed_content_length);
  16644. }
  16645. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16646. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16647. // unbounded run of fields that are never declared, because the counter would
  16648. // only advance for declared fields.
  16649. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16650. Server svr;
  16651. bool handler_called = false;
  16652. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16653. handler_called = true;
  16654. res.set_content("ok", "text/plain");
  16655. });
  16656. auto port = svr.bind_to_any_port(HOST);
  16657. thread t = thread([&]() { svr.listen_after_bind(); });
  16658. auto se = detail::scope_exit([&] {
  16659. svr.stop();
  16660. t.join();
  16661. ASSERT_FALSE(svr.is_running());
  16662. });
  16663. svr.wait_until_ready();
  16664. // Declare nothing, then send far more undeclared trailer fields than the
  16665. // header-count limit. Parsing must stop and reject the request rather than
  16666. // read every line.
  16667. std::string req = "GET / HTTP/1.1\r\n"
  16668. "Transfer-Encoding: chunked\r\n"
  16669. "\r\n"
  16670. "0\r\n";
  16671. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16672. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16673. }
  16674. req += "\r\n";
  16675. std::string res;
  16676. ASSERT_TRUE(send_request(1, req, &res, port));
  16677. // The request is rejected before the handler runs.
  16678. EXPECT_FALSE(handler_called);
  16679. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16680. }
  16681. // The set of declared trailer names is capped so a peer cannot grow it without
  16682. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16683. // declared past the cap is not honored, even if the field is actually sent.
  16684. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16685. Server svr;
  16686. // One name inside the cap and one past it, so the test tracks the cap rather
  16687. // than a fixed count.
  16688. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16689. const std::string within_cap_name = "X-T-0";
  16690. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16691. bool observed_within_cap = false;
  16692. bool observed_past_cap = false;
  16693. svr.Get("/", [&](const Request &req, Response &res) {
  16694. observed_within_cap = req.has_trailer(within_cap_name);
  16695. observed_past_cap = req.has_trailer(past_cap_name);
  16696. res.set_content("ok", "text/plain");
  16697. });
  16698. auto port = svr.bind_to_any_port(HOST);
  16699. thread t = thread([&]() { svr.listen_after_bind(); });
  16700. auto se = detail::scope_exit([&] {
  16701. svr.stop();
  16702. t.join();
  16703. ASSERT_FALSE(svr.is_running());
  16704. });
  16705. svr.wait_until_ready();
  16706. // Declare more trailer names than the cap in a single Trailer field, then
  16707. // actually send the first (within the cap) and the last (past it).
  16708. std::string trailer_decl = "Trailer: ";
  16709. for (int i = 0; i < declared_count; i++) {
  16710. if (i != 0) { trailer_decl += ", "; }
  16711. trailer_decl += "X-T-" + std::to_string(i);
  16712. }
  16713. trailer_decl += "\r\n";
  16714. const std::string req = "GET / HTTP/1.1\r\n"
  16715. "Transfer-Encoding: chunked\r\n" +
  16716. trailer_decl +
  16717. "\r\n"
  16718. "0\r\n" +
  16719. within_cap_name + ": a\r\n" + past_cap_name +
  16720. ": b\r\n"
  16721. "\r\n";
  16722. std::string res;
  16723. ASSERT_TRUE(send_request(1, req, &res, port));
  16724. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16725. // A name within the cap is honored; one declared past the cap is dropped.
  16726. EXPECT_TRUE(observed_within_cap);
  16727. EXPECT_FALSE(observed_past_cap);
  16728. }
  16729. // A direct client that is not listed in trusted_proxies must not be able to
  16730. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16731. // the peer address on the actual TCP connection determines whether the
  16732. // header is honored.
  16733. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16734. Server svr;
  16735. // Deliberately does NOT include the loopback address the test client
  16736. // actually connects from, so the direct connection is not a trusted proxy.
  16737. svr.set_trusted_proxies({"203.0.113.66"});
  16738. std::string observed_remote_addr;
  16739. svr.Get("/ip", [&](const Request &req, Response &res) {
  16740. observed_remote_addr = req.remote_addr;
  16741. res.set_content("ok", "text/plain");
  16742. });
  16743. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16744. auto se = detail::scope_exit([&] {
  16745. svr.stop();
  16746. t.join();
  16747. ASSERT_FALSE(svr.is_running());
  16748. });
  16749. svr.wait_until_ready();
  16750. Client cli(HOST, PORT);
  16751. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16753. EXPECT_EQ(StatusCode::OK_200, res->status);
  16754. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16755. // ignored entirely and the real connection-level address retained.
  16756. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16757. observed_remote_addr == "127.0.0.1");
  16758. }
  16759. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16760. Server svr;
  16761. std::string observed_remote_addr;
  16762. std::string observed_xff;
  16763. svr.Get("/ip", [&](const Request &req, Response &res) {
  16764. observed_remote_addr = req.remote_addr;
  16765. observed_xff = req.get_header_value("X-Forwarded-For");
  16766. res.set_content("ok", "text/plain");
  16767. });
  16768. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16769. auto se = detail::scope_exit([&] {
  16770. svr.stop();
  16771. t.join();
  16772. ASSERT_FALSE(svr.is_running());
  16773. });
  16774. svr.wait_until_ready();
  16775. Client cli(HOST, PORT);
  16776. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16778. EXPECT_EQ(StatusCode::OK_200, res->status);
  16779. EXPECT_EQ(observed_xff, "203.0.113.66");
  16780. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16781. observed_remote_addr == "127.0.0.1");
  16782. }
  16783. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16784. Server svr;
  16785. svr.set_trusted_proxies({"203.0.113.66"});
  16786. std::string observed_remote_addr;
  16787. std::string observed_xff;
  16788. svr.Get("/ip", [&](const Request &req, Response &res) {
  16789. observed_remote_addr = req.remote_addr;
  16790. observed_xff = req.get_header_value("X-Forwarded-For");
  16791. res.set_content("ok", "text/plain");
  16792. });
  16793. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16794. auto se = detail::scope_exit([&] {
  16795. svr.stop();
  16796. t.join();
  16797. ASSERT_FALSE(svr.is_running());
  16798. });
  16799. svr.wait_until_ready();
  16800. Client cli(HOST, PORT);
  16801. auto res = cli.Get("/ip");
  16802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16803. EXPECT_EQ(StatusCode::OK_200, res->status);
  16804. EXPECT_EQ(observed_xff, "");
  16805. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16806. observed_remote_addr == "127.0.0.1");
  16807. }
  16808. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16809. Server svr;
  16810. // Include the loopback address the test client actually connects from, so
  16811. // the direct connection itself is recognized as the trusted proxy hop.
  16812. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16813. std::string observed_remote_addr;
  16814. std::string observed_xff;
  16815. svr.Get("/ip", [&](const Request &req, Response &res) {
  16816. observed_remote_addr = req.remote_addr;
  16817. observed_xff = req.get_header_value("X-Forwarded-For");
  16818. res.set_content("ok", "text/plain");
  16819. });
  16820. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16821. auto se = detail::scope_exit([&] {
  16822. svr.stop();
  16823. t.join();
  16824. ASSERT_FALSE(svr.is_running());
  16825. });
  16826. svr.wait_until_ready();
  16827. Client cli(HOST, PORT);
  16828. auto res = cli.Get(
  16829. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16831. EXPECT_EQ(StatusCode::OK_200, res->status);
  16832. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16833. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16834. }
  16835. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16836. Server svr;
  16837. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16838. std::string observed_remote_addr;
  16839. std::string observed_xff;
  16840. svr.Get("/ip", [&](const Request &req, Response &res) {
  16841. observed_remote_addr = req.remote_addr;
  16842. observed_xff = req.get_header_value("X-Forwarded-For");
  16843. res.set_content("ok", "text/plain");
  16844. });
  16845. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16846. auto se = detail::scope_exit([&] {
  16847. svr.stop();
  16848. t.join();
  16849. ASSERT_FALSE(svr.is_running());
  16850. });
  16851. svr.wait_until_ready();
  16852. Client cli(HOST, PORT);
  16853. auto res = cli.Get(
  16854. "/ip",
  16855. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16857. EXPECT_EQ(StatusCode::OK_200, res->status);
  16858. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16859. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16860. }
  16861. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16862. Server svr;
  16863. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16864. std::string observed_remote_addr;
  16865. std::string observed_xff;
  16866. svr.Get("/ip", [&](const Request &req, Response &res) {
  16867. observed_remote_addr = req.remote_addr;
  16868. observed_xff = req.get_header_value("X-Forwarded-For");
  16869. res.set_content("ok", "text/plain");
  16870. });
  16871. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16872. auto se = detail::scope_exit([&] {
  16873. svr.stop();
  16874. t.join();
  16875. ASSERT_FALSE(svr.is_running());
  16876. });
  16877. svr.wait_until_ready();
  16878. Client cli(HOST, PORT);
  16879. auto res = cli.Get(
  16880. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16882. EXPECT_EQ(StatusCode::OK_200, res->status);
  16883. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16884. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16885. // and must not be selected.
  16886. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16887. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16888. }
  16889. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16890. Server svr;
  16891. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16892. std::string observed_remote_addr;
  16893. svr.Get("/ip", [&](const Request &req, Response &res) {
  16894. observed_remote_addr = req.remote_addr;
  16895. res.set_content("ok", "text/plain");
  16896. });
  16897. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16898. auto se = detail::scope_exit([&] {
  16899. svr.stop();
  16900. t.join();
  16901. ASSERT_FALSE(svr.is_running());
  16902. });
  16903. svr.wait_until_ready();
  16904. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16905. // a forged address and the trusted proxy's own address; the forged value must
  16906. // not win over the address the trusted proxy actually recorded.
  16907. Client cli(HOST, PORT);
  16908. auto res = cli.Get(
  16909. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16911. EXPECT_EQ(StatusCode::OK_200, res->status);
  16912. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16913. }
  16914. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16915. Server svr;
  16916. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16917. std::string observed_remote_addr;
  16918. std::string observed_xff;
  16919. svr.Get("/ip", [&](const Request &req, Response &res) {
  16920. observed_remote_addr = req.remote_addr;
  16921. observed_xff = req.get_header_value("X-Forwarded-For");
  16922. res.set_content("ok", "text/plain");
  16923. });
  16924. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16925. auto se = detail::scope_exit([&] {
  16926. svr.stop();
  16927. t.join();
  16928. ASSERT_FALSE(svr.is_running());
  16929. });
  16930. svr.wait_until_ready();
  16931. Client cli(HOST, PORT);
  16932. auto res = cli.Get(
  16933. "/ip",
  16934. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16936. EXPECT_EQ(StatusCode::OK_200, res->status);
  16937. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16938. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16939. }
  16940. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16941. Server svr;
  16942. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16943. std::string observed_remote_addr;
  16944. std::string observed_xff;
  16945. svr.Get("/ip", [&](const Request &req, Response &res) {
  16946. observed_remote_addr = req.remote_addr;
  16947. observed_xff = req.get_header_value("X-Forwarded-For");
  16948. res.set_content("ok", "text/plain");
  16949. });
  16950. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16951. auto se = detail::scope_exit([&] {
  16952. svr.stop();
  16953. t.join();
  16954. ASSERT_FALSE(svr.is_running());
  16955. });
  16956. svr.wait_until_ready();
  16957. std::string raw_req =
  16958. "GET /ip HTTP/1.1\r\n"
  16959. "Host: localhost\r\n"
  16960. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16961. "Connection: close\r\n"
  16962. "\r\n";
  16963. std::string out;
  16964. ASSERT_TRUE(send_request(5, raw_req, &out));
  16965. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16966. // Header parser trims surrounding whitespace of the header value
  16967. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16968. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16969. }
  16970. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16971. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16972. // their own X-Forwarded-For as a separate field line rather than extending the
  16973. // one the client sent, so every occurrence has to be taken into account.
  16974. // Reading only the first one hands back the address the client chose.
  16975. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16976. Server svr;
  16977. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16978. std::string observed_remote_addr;
  16979. size_t observed_xff_count = 0;
  16980. svr.Get("/ip", [&](const Request &req, Response &res) {
  16981. observed_remote_addr = req.remote_addr;
  16982. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16983. res.set_content("ok", "text/plain");
  16984. });
  16985. auto port = svr.bind_to_any_port(HOST);
  16986. thread t = thread([&]() { svr.listen_after_bind(); });
  16987. auto se = detail::scope_exit([&] {
  16988. svr.stop();
  16989. t.join();
  16990. ASSERT_FALSE(svr.is_running());
  16991. });
  16992. svr.wait_until_ready();
  16993. // The client supplies the first field line; the trusted proxy appends the
  16994. // address it observed as a second one.
  16995. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16996. "Host: localhost\r\n"
  16997. "X-Forwarded-For: 1.2.3.4\r\n"
  16998. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16999. "Connection: close\r\n"
  17000. "\r\n";
  17001. std::string out;
  17002. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17003. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17004. EXPECT_EQ(observed_xff_count, 2U);
  17005. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17006. // The same chain spread over one field line per hop derives the same client
  17007. // address, i.e. the split and the comma-joined representations agree.
  17008. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17009. "Host: localhost\r\n"
  17010. "X-Forwarded-For: 1.2.3.4\r\n"
  17011. "X-Forwarded-For: 198.51.100.23\r\n"
  17012. "X-Forwarded-For: 192.0.2.45\r\n"
  17013. "Connection: close\r\n"
  17014. "\r\n";
  17015. out.clear();
  17016. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17017. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17018. EXPECT_EQ(observed_xff_count, 3U);
  17019. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17020. }
  17021. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17022. // crash the server (it used to call front() on an empty vector inside
  17023. // get_client_ip). The connection-level remote address must be retained instead.
  17024. static void run_malformed_xff_test(const std::string &xff_value) {
  17025. Server svr;
  17026. svr.set_trusted_proxies({"192.0.2.45"});
  17027. std::string observed_remote_addr;
  17028. svr.Get("/ip", [&](const Request &req, Response &res) {
  17029. observed_remote_addr = req.remote_addr;
  17030. res.set_content("ok", "text/plain");
  17031. });
  17032. int port = 0;
  17033. thread t = thread([&]() {
  17034. port = svr.bind_to_any_port(HOST);
  17035. svr.listen_after_bind();
  17036. });
  17037. auto se = detail::scope_exit([&] {
  17038. svr.stop();
  17039. t.join();
  17040. ASSERT_FALSE(svr.is_running());
  17041. });
  17042. svr.wait_until_ready();
  17043. Client cli(HOST, port);
  17044. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17046. EXPECT_EQ(StatusCode::OK_200, res->status);
  17047. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17048. observed_remote_addr == "127.0.0.1");
  17049. }
  17050. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17051. run_malformed_xff_test("");
  17052. }
  17053. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17054. run_malformed_xff_test(",");
  17055. }
  17056. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17057. run_malformed_xff_test(", , ,");
  17058. }
  17059. // The same rule applies to Accept: a request whose acceptable types are spread
  17060. // over several field lines must be negotiated against all of them.
  17061. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17062. // case-insensitive connection options. Comparing the whole field value against
  17063. // one option misses a client that sends several of them, and misses every
  17064. // casing but the one written in the comparison.
  17065. //
  17066. // Sends req, reads the response, then reuses the same socket for a second
  17067. // request to find out whether the server kept the connection.
  17068. static void probe_connection_reuse(int port, const std::string &req,
  17069. bool *announced_close, bool *reusable) {
  17070. auto error = Error::Success;
  17071. auto sock = detail::create_client_socket(
  17072. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17073. /*connection_timeout_sec=*/5, 0,
  17074. /*read_timeout_sec=*/1, 0,
  17075. /*write_timeout_sec=*/5, 0, std::string(), error);
  17076. ASSERT_NE(sock, INVALID_SOCKET);
  17077. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17078. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17079. "Host: localhost\r\n"
  17080. "Connection: close\r\n"
  17081. "\r\n";
  17082. std::string first_response;
  17083. std::string second_response;
  17084. detail::process_client_socket(
  17085. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17086. [&](Stream &strm) {
  17087. if (strm.write(req.data(), req.size()) !=
  17088. static_cast<ssize_t>(req.size())) {
  17089. return false;
  17090. }
  17091. char buf[512];
  17092. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17093. // Headers plus the two-byte body of the handler below
  17094. while (reader.getline()) {
  17095. first_response += reader.ptr();
  17096. if (first_response.find("ok") != std::string::npos) { break; }
  17097. }
  17098. if (strm.write(second.data(), second.size()) !=
  17099. static_cast<ssize_t>(second.size())) {
  17100. return true;
  17101. }
  17102. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17103. while (reader2.getline()) {
  17104. second_response += reader2.ptr();
  17105. if (second_response.find("ok") != std::string::npos) { break; }
  17106. }
  17107. return true;
  17108. });
  17109. *announced_close =
  17110. first_response.find("Connection: close") != std::string::npos;
  17111. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17112. }
  17113. class ConnectionTokenTest : public ::testing::Test {
  17114. protected:
  17115. void SetUp() override {
  17116. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17117. res.set_content("ok", "text/plain");
  17118. });
  17119. port_ = svr_.bind_to_any_port(HOST);
  17120. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17121. svr_.wait_until_ready();
  17122. }
  17123. void TearDown() override {
  17124. svr_.stop();
  17125. if (thread_.joinable()) { thread_.join(); }
  17126. }
  17127. Server svr_;
  17128. int port_ = 0;
  17129. thread thread_;
  17130. };
  17131. // "close" alongside another option still closes the connection, and the
  17132. // response says so rather than leaving the peer to discover it.
  17133. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17134. bool announced_close = false;
  17135. bool reusable = true;
  17136. probe_connection_reuse(port_,
  17137. "GET /keepalive HTTP/1.1\r\n"
  17138. "Host: localhost\r\n"
  17139. "Connection: keep-alive, close\r\n"
  17140. "\r\n",
  17141. &announced_close, &reusable);
  17142. EXPECT_TRUE(announced_close);
  17143. EXPECT_FALSE(reusable);
  17144. }
  17145. // "close" split over two field lines is the same list, so it is honored too.
  17146. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17147. bool announced_close = false;
  17148. bool reusable = true;
  17149. probe_connection_reuse(port_,
  17150. "GET /keepalive HTTP/1.1\r\n"
  17151. "Host: localhost\r\n"
  17152. "Connection: keep-alive\r\n"
  17153. "Connection: close\r\n"
  17154. "\r\n",
  17155. &announced_close, &reusable);
  17156. EXPECT_TRUE(announced_close);
  17157. EXPECT_FALSE(reusable);
  17158. }
  17159. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17160. // keep-alive in the spelling everyone actually sends keeps its connection.
  17161. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17162. bool announced_close = false;
  17163. bool reusable = false;
  17164. probe_connection_reuse(port_,
  17165. "GET /keepalive HTTP/1.0\r\n"
  17166. "Host: localhost\r\n"
  17167. "Connection: keep-alive\r\n"
  17168. "\r\n",
  17169. &announced_close, &reusable);
  17170. EXPECT_FALSE(announced_close);
  17171. EXPECT_TRUE(reusable);
  17172. }
  17173. // A token the value merely contains is not the token itself.
  17174. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17175. bool announced_close = false;
  17176. bool reusable = false;
  17177. probe_connection_reuse(port_,
  17178. "GET /keepalive HTTP/1.1\r\n"
  17179. "Host: localhost\r\n"
  17180. "Connection: notclose\r\n"
  17181. "\r\n",
  17182. &announced_close, &reusable);
  17183. EXPECT_FALSE(announced_close);
  17184. EXPECT_TRUE(reusable);
  17185. }
  17186. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17187. Server svr;
  17188. std::vector<std::string> observed_types;
  17189. svr.Get("/", [&](const Request &req, Response &res) {
  17190. observed_types = req.accept_content_types;
  17191. res.set_content("ok", "text/plain");
  17192. });
  17193. auto port = svr.bind_to_any_port(HOST);
  17194. thread t = thread([&]() { svr.listen_after_bind(); });
  17195. auto se = detail::scope_exit([&] {
  17196. svr.stop();
  17197. t.join();
  17198. ASSERT_FALSE(svr.is_running());
  17199. });
  17200. svr.wait_until_ready();
  17201. Client cli(HOST, port);
  17202. Headers headers;
  17203. headers.emplace("Accept", "text/plain;q=0.5");
  17204. headers.emplace("Accept", "application/json");
  17205. auto res = cli.Get("/", headers);
  17206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17207. EXPECT_EQ(StatusCode::OK_200, res->status);
  17208. // Sorted by q-value, so the second field line's type comes first
  17209. ASSERT_EQ(2U, observed_types.size());
  17210. EXPECT_EQ("application/json", observed_types[0]);
  17211. EXPECT_EQ("text/plain", observed_types[1]);
  17212. }
  17213. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17214. // empty field line must not contribute a bare comma to the combined value.
  17215. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17216. Server svr;
  17217. std::vector<std::string> observed_types;
  17218. svr.Get("/", [&](const Request &req, Response &res) {
  17219. observed_types = req.accept_content_types;
  17220. res.set_content("ok", "text/plain");
  17221. });
  17222. auto port = svr.bind_to_any_port(HOST);
  17223. thread t = thread([&]() { svr.listen_after_bind(); });
  17224. auto se = detail::scope_exit([&] {
  17225. svr.stop();
  17226. t.join();
  17227. ASSERT_FALSE(svr.is_running());
  17228. });
  17229. svr.wait_until_ready();
  17230. // Empty first field line, then a real one
  17231. std::string raw_req = "GET / HTTP/1.1\r\n"
  17232. "Host: localhost\r\n"
  17233. "Accept:\r\n"
  17234. "Accept: application/json\r\n"
  17235. "Connection: close\r\n"
  17236. "\r\n";
  17237. std::string out;
  17238. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17239. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17240. ASSERT_EQ(1U, observed_types.size());
  17241. EXPECT_EQ("application/json", observed_types[0]);
  17242. }
  17243. // The skip in get_combined_header_value() is what keeps an empty field line
  17244. // from contributing a bare comma. Only a trailing empty field line exercises
  17245. // it: a leading one is already covered by the "combined is still empty" check,
  17246. // and parse_accept_header() now ignores the empty element either way, so the
  17247. // request-level test above can no longer tell the two apart.
  17248. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17249. Headers headers;
  17250. headers.emplace("Accept", "text/html");
  17251. headers.emplace("Accept", "");
  17252. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17253. headers.clear();
  17254. headers.emplace("Accept", "");
  17255. headers.emplace("Accept", "application/json");
  17256. EXPECT_EQ("application/json",
  17257. detail::get_combined_header_value(headers, "Accept"));
  17258. }
  17259. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17260. // An encoding offered on a later Accept-Encoding field line is still offered.
  17261. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17262. Server svr;
  17263. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17264. res.set_content(std::string(1024, 'x'), "text/plain");
  17265. });
  17266. auto port = svr.bind_to_any_port(HOST);
  17267. thread t = thread([&]() { svr.listen_after_bind(); });
  17268. auto se = detail::scope_exit([&] {
  17269. svr.stop();
  17270. t.join();
  17271. ASSERT_FALSE(svr.is_running());
  17272. });
  17273. svr.wait_until_ready();
  17274. Client cli(HOST, port);
  17275. cli.set_decompress(false);
  17276. Headers headers;
  17277. headers.emplace("Accept-Encoding", "identity");
  17278. headers.emplace("Accept-Encoding", "gzip");
  17279. auto res = cli.Get("/", headers);
  17280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17281. EXPECT_EQ(StatusCode::OK_200, res->status);
  17282. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17283. }
  17284. #endif
  17285. #ifndef _WIN32
  17286. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17287. Server svr;
  17288. svr.Post("/post", [&](const Request &req, Response &res) {
  17289. res.set_content(req.body, "text/plain");
  17290. });
  17291. svr.Put("/put", [&](const Request &req, Response &res) {
  17292. res.set_content(req.body, "text/plain");
  17293. });
  17294. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17295. res.set_content(req.body, "text/plain");
  17296. });
  17297. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17298. res.set_content(req.body, "text/plain");
  17299. });
  17300. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17301. auto se = detail::scope_exit([&] {
  17302. svr.stop();
  17303. t.join();
  17304. ASSERT_FALSE(svr.is_running());
  17305. });
  17306. svr.wait_until_ready();
  17307. std::string resp;
  17308. // POST without Content-Length
  17309. ASSERT_TRUE(send_request(5,
  17310. "POST /post HTTP/1.1\r\n"
  17311. "Host: localhost\r\n"
  17312. "Connection: close\r\n"
  17313. "\r\n",
  17314. &resp));
  17315. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17316. // PUT without Content-Length
  17317. resp.clear();
  17318. ASSERT_TRUE(send_request(5,
  17319. "PUT /put HTTP/1.1\r\n"
  17320. "Host: localhost\r\n"
  17321. "Connection: close\r\n"
  17322. "\r\n",
  17323. &resp));
  17324. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17325. // PATCH without Content-Length
  17326. resp.clear();
  17327. ASSERT_TRUE(send_request(5,
  17328. "PATCH /patch HTTP/1.1\r\n"
  17329. "Host: localhost\r\n"
  17330. "Connection: close\r\n"
  17331. "\r\n",
  17332. &resp));
  17333. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17334. // DELETE without Content-Length
  17335. resp.clear();
  17336. ASSERT_TRUE(send_request(5,
  17337. "DELETE /delete HTTP/1.1\r\n"
  17338. "Host: localhost\r\n"
  17339. "Connection: close\r\n"
  17340. "\r\n",
  17341. &resp));
  17342. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17343. }
  17344. #endif
  17345. //==============================================================================
  17346. // open_stream() Tests
  17347. //==============================================================================
  17348. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17349. std::string result;
  17350. char buf[8192];
  17351. ssize_t n;
  17352. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17353. result.append(buf, static_cast<size_t>(n));
  17354. }
  17355. return result;
  17356. }
  17357. // Mock stream for unit tests
  17358. class MockStream : public Stream {
  17359. public:
  17360. std::string data;
  17361. size_t pos = 0;
  17362. ssize_t error_after = -1; // -1 = no error
  17363. explicit MockStream(const std::string &d, ssize_t err = -1)
  17364. : data(d), error_after(err) {}
  17365. bool is_readable() const override { return true; }
  17366. bool wait_readable() const override { return true; }
  17367. bool wait_writable() const override { return true; }
  17368. ssize_t read(char *ptr, size_t size) override {
  17369. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17370. if (pos >= data.size()) return 0;
  17371. size_t limit =
  17372. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17373. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17374. std::memcpy(ptr, data.data() + pos, to_read);
  17375. pos += to_read;
  17376. return static_cast<ssize_t>(to_read);
  17377. }
  17378. ssize_t write(const char *, size_t) override { return -1; }
  17379. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17380. ip = "127.0.0.1";
  17381. port = 0;
  17382. }
  17383. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17384. ip = "127.0.0.1";
  17385. port = 0;
  17386. }
  17387. socket_t socket() const override { return INVALID_SOCKET; }
  17388. time_t duration() const override { return 0; }
  17389. };
  17390. TEST(StreamHandleTest, Basic) {
  17391. ClientImpl::StreamHandle handle;
  17392. EXPECT_FALSE(handle.is_valid());
  17393. handle.response = detail::make_unique<Response>();
  17394. handle.error = Error::Connection;
  17395. EXPECT_FALSE(handle.is_valid());
  17396. handle.error = Error::Success;
  17397. EXPECT_TRUE(handle.is_valid());
  17398. }
  17399. TEST(BodyReaderTest, Basic) {
  17400. MockStream stream("Hello, World!");
  17401. detail::BodyReader reader;
  17402. reader.stream = &stream;
  17403. reader.content_length = 13;
  17404. char buf[32];
  17405. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17406. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17407. EXPECT_TRUE(reader.eof);
  17408. }
  17409. TEST(BodyReaderTest, NoStream) {
  17410. detail::BodyReader reader;
  17411. char buf[32];
  17412. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17413. EXPECT_EQ(Error::Connection, reader.last_error);
  17414. }
  17415. TEST(BodyReaderTest, Error) {
  17416. MockStream stream("Hello, World!", 5);
  17417. detail::BodyReader reader;
  17418. reader.stream = &stream;
  17419. reader.content_length = 13;
  17420. char buf[32];
  17421. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17422. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17423. EXPECT_EQ(Error::Read, reader.last_error);
  17424. }
  17425. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17426. // Mock-based StreamHandle tests relying on private internals are removed.
  17427. class OpenStreamTest : public ::testing::Test {
  17428. protected:
  17429. void SetUp() override {
  17430. svr_.Get("/hello", [](const Request &, Response &res) {
  17431. res.set_content("Hello World!", "text/plain");
  17432. });
  17433. svr_.Get("/large", [](const Request &, Response &res) {
  17434. res.set_content(std::string(10000, 'X'), "text/plain");
  17435. });
  17436. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17437. res.set_content("Hello World!", "image/jpeg");
  17438. res.set_header("Content-Encoding", "UTF-8");
  17439. });
  17440. svr_.Get("/chunked", [](const Request &, Response &res) {
  17441. res.set_chunked_content_provider("text/plain",
  17442. [](size_t offset, DataSink &sink) {
  17443. if (offset < 15) {
  17444. sink.write("chunk", 5);
  17445. return true;
  17446. }
  17447. sink.done();
  17448. return true;
  17449. });
  17450. });
  17451. svr_.Get("/compressible", [](const Request &, Response &res) {
  17452. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17453. DataSink &sink) {
  17454. if (offset < 100 * 1024) {
  17455. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17456. sink.write(chunk.data(), chunk.size());
  17457. return true;
  17458. }
  17459. sink.done();
  17460. return true;
  17461. });
  17462. });
  17463. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17464. [](const Request & /*req*/, Response &res) {
  17465. auto i = new int(0);
  17466. res.set_header("Trailer", "Content-Length, X-Allowed");
  17467. res.set_chunked_content_provider(
  17468. "text/plain",
  17469. [i](size_t /*offset*/, DataSink &sink) {
  17470. switch (*i) {
  17471. case 0: sink.os << "123"; break;
  17472. case 1: sink.os << "456"; break;
  17473. case 2: sink.os << "789"; break;
  17474. case 3: {
  17475. sink.done_with_trailer(
  17476. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17477. } break;
  17478. }
  17479. (*i)++;
  17480. return true;
  17481. },
  17482. [i](bool success) {
  17483. EXPECT_TRUE(success);
  17484. delete i;
  17485. });
  17486. });
  17487. // Echo headers endpoint for header-related tests
  17488. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17489. std::string body;
  17490. for (const auto &h : req.headers) {
  17491. body.append(h.first);
  17492. body.push_back(':');
  17493. body.append(h.second);
  17494. body.push_back('\n');
  17495. }
  17496. res.set_content(body, "text/plain");
  17497. });
  17498. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17499. std::string body;
  17500. for (const auto &h : req.headers) {
  17501. body.append(h.first);
  17502. body.push_back(':');
  17503. body.append(h.second);
  17504. body.push_back('\n');
  17505. }
  17506. res.set_content(body, "text/plain");
  17507. });
  17508. port_ = svr_.bind_to_any_port("127.0.0.1");
  17509. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17510. svr_.wait_until_ready();
  17511. }
  17512. void TearDown() override {
  17513. svr_.stop();
  17514. if (thread_.joinable()) thread_.join();
  17515. }
  17516. Server svr_;
  17517. std::thread thread_;
  17518. int port_ = 0;
  17519. };
  17520. TEST_F(OpenStreamTest, Basic) {
  17521. Client cli("127.0.0.1", port_);
  17522. auto handle = cli.open_stream("GET", "/hello");
  17523. EXPECT_TRUE(handle.is_valid());
  17524. EXPECT_EQ("Hello World!", read_all(handle));
  17525. }
  17526. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17527. Client cli("127.0.0.1", port_);
  17528. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17529. ASSERT_TRUE(handle.is_valid());
  17530. EXPECT_EQ("Hello World!", read_all(handle));
  17531. }
  17532. TEST_F(OpenStreamTest, SmallBuffer) {
  17533. Client cli("127.0.0.1", port_);
  17534. auto handle = cli.open_stream("GET", "/hello");
  17535. std::string result;
  17536. char buf[4];
  17537. ssize_t n;
  17538. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17539. result.append(buf, static_cast<size_t>(n));
  17540. EXPECT_EQ("Hello World!", result);
  17541. }
  17542. TEST_F(OpenStreamTest, DefaultHeaders) {
  17543. Client cli("127.0.0.1", port_);
  17544. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17545. {
  17546. auto handle = cli.open_stream("GET", "/echo-headers");
  17547. ASSERT_TRUE(handle.is_valid());
  17548. auto body = read_all(handle);
  17549. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17550. std::string::npos);
  17551. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17552. std::string::npos);
  17553. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17554. }
  17555. // open_stream POST with body and no explicit content_type should NOT add
  17556. // text/plain Content-Type (behavior differs from non-streaming path), but
  17557. // should include Content-Length
  17558. {
  17559. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17560. ASSERT_TRUE(handle.is_valid());
  17561. auto body = read_all(handle);
  17562. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17563. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17564. }
  17565. // open_stream POST with explicit Content-Type should preserve it
  17566. {
  17567. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17568. {{"Content-Type", "application/custom"}},
  17569. "{}", "application/custom");
  17570. ASSERT_TRUE(handle.is_valid());
  17571. auto body = read_all(handle);
  17572. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17573. }
  17574. // User-specified User-Agent must not be overwritten for stream API
  17575. {
  17576. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17577. {{"User-Agent", "MyAgent/1.2"}});
  17578. ASSERT_TRUE(handle.is_valid());
  17579. auto body = read_all(handle);
  17580. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17581. }
  17582. }
  17583. TEST_F(OpenStreamTest, Large) {
  17584. Client cli("127.0.0.1", port_);
  17585. auto handle = cli.open_stream("GET", "/large");
  17586. EXPECT_EQ(10000u, read_all(handle).size());
  17587. }
  17588. TEST_F(OpenStreamTest, ConnectionError) {
  17589. Client cli("127.0.0.1", 9999);
  17590. auto handle = cli.open_stream("GET", "/hello");
  17591. EXPECT_FALSE(handle.is_valid());
  17592. }
  17593. TEST_F(OpenStreamTest, Chunked) {
  17594. Client cli("127.0.0.1", port_);
  17595. auto handle = cli.open_stream("GET", "/chunked");
  17596. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17597. "Transfer-Encoding") == "chunked");
  17598. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17599. }
  17600. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17601. Client cli("127.0.0.1", port_);
  17602. auto handle =
  17603. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17604. ASSERT_TRUE(handle.is_valid());
  17605. // Consume body to allow trailers to be received/parsed
  17606. auto body = read_all(handle);
  17607. // Explicitly parse trailers (ensure trailers are available for assertion)
  17608. handle.parse_trailers_if_needed();
  17609. EXPECT_EQ(std::string("123456789"), body);
  17610. // The response should include a Trailer header declaring both names
  17611. ASSERT_TRUE(handle.response);
  17612. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17613. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17614. handle.response->get_header_value("Trailer"));
  17615. // Prohibited trailer must not be present
  17616. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17617. // Allowed trailer should be present
  17618. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17619. EXPECT_EQ(std::string("yes"),
  17620. handle.response->get_trailer_value("X-Allowed"));
  17621. // Verify trailers are NOT present as regular headers
  17622. EXPECT_EQ(std::string(""),
  17623. handle.response->get_header_value("Content-Length"));
  17624. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17625. }
  17626. static std::thread serve_single_response(std::promise<int> &port_promise,
  17627. const std::string &response) {
  17628. return std::thread([&port_promise, response] {
  17629. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17630. default_socket_options(srv);
  17631. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17632. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17633. sockaddr_in addr{};
  17634. addr.sin_family = AF_INET;
  17635. addr.sin_port = htons(0); // Let OS assign a free port
  17636. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17637. int opt = 1;
  17638. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17639. #ifdef _WIN32
  17640. reinterpret_cast<const char *>(&opt),
  17641. #else
  17642. &opt,
  17643. #endif
  17644. sizeof(opt));
  17645. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17646. ::listen(srv, 1) != 0) {
  17647. port_promise.set_value(-1);
  17648. detail::close_socket(srv);
  17649. return;
  17650. }
  17651. socklen_t addr_len = sizeof(addr);
  17652. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17653. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17654. sockaddr_in cli_addr{};
  17655. socklen_t cli_len = sizeof(cli_addr);
  17656. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17657. if (cli != INVALID_SOCKET) {
  17658. // Read the complete HTTP request (until the blank line that terminates
  17659. // headers) before sending the response. If the server closes the socket
  17660. // while the client's request data is still unread in the kernel receive
  17661. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17662. // connection on both sides: it discards the client's receive buffer
  17663. // (which already holds our response) and causes any in-progress write on
  17664. // the client to fail with ECONNRESET. Reading all request data first
  17665. // ensures close() emits a graceful FIN.
  17666. {
  17667. char rbuf[256];
  17668. std::string req;
  17669. while (req.find("\r\n\r\n") == std::string::npos) {
  17670. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17671. if (n <= 0) { break; }
  17672. req.append(rbuf, static_cast<size_t>(n));
  17673. }
  17674. }
  17675. ::send(cli,
  17676. #ifdef _WIN32
  17677. static_cast<const char *>(response.c_str()),
  17678. static_cast<int>(response.size()),
  17679. #else
  17680. response.c_str(), response.size(),
  17681. #endif
  17682. 0);
  17683. detail::close_socket(cli);
  17684. }
  17685. detail::close_socket(srv);
  17686. });
  17687. }
  17688. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17689. #ifndef _WIN32
  17690. signal(SIGPIPE, SIG_IGN);
  17691. #endif
  17692. std::promise<int> port_promise;
  17693. auto port_future = port_promise.get_future();
  17694. auto server_thread =
  17695. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17696. "Content-Type: text/plain\r\n"
  17697. "Content-Length: not-a-number\r\n"
  17698. "Connection: close\r\n"
  17699. "\r\n"
  17700. "hello");
  17701. auto port = port_future.get();
  17702. ASSERT_GT(port, 0);
  17703. Client cli("127.0.0.1", port);
  17704. auto handle = cli.open_stream("GET", "/");
  17705. EXPECT_FALSE(handle.is_valid());
  17706. server_thread.join();
  17707. }
  17708. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17709. #ifndef _WIN32
  17710. signal(SIGPIPE, SIG_IGN);
  17711. #endif
  17712. std::promise<int> port_promise;
  17713. auto port_future = port_promise.get_future();
  17714. auto server_thread = serve_single_response(
  17715. port_promise, "HTTP/1.1 200 OK\r\n"
  17716. "Content-Type: text/plain\r\n"
  17717. "Content-Length: 99999999999999999999999999\r\n"
  17718. "Connection: close\r\n"
  17719. "\r\n"
  17720. "hello");
  17721. auto port = port_future.get();
  17722. ASSERT_GT(port, 0);
  17723. // Historically std::stoull would throw std::out_of_range here and crash
  17724. // the process, then parsing silently clamped to a bogus framing length and
  17725. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17726. // so the stream fails to open, matching the not-a-number case above. The
  17727. // process still must NOT terminate.
  17728. Client cli("127.0.0.1", port);
  17729. auto handle = cli.open_stream("GET", "/");
  17730. EXPECT_FALSE(handle.is_valid());
  17731. server_thread.join();
  17732. }
  17733. // Serves `response` to the single request `fn` makes with a fresh client.
  17734. template <typename Fn>
  17735. static void with_single_response(const std::string &response, Fn fn) {
  17736. #ifndef _WIN32
  17737. signal(SIGPIPE, SIG_IGN);
  17738. #endif
  17739. std::promise<int> port_promise;
  17740. auto port_future = port_promise.get_future();
  17741. auto server_thread = serve_single_response(port_promise, response);
  17742. auto se = detail::scope_exit([&] { server_thread.join(); });
  17743. auto port = port_future.get();
  17744. ASSERT_GT(port, 0);
  17745. Client cli("127.0.0.1", port);
  17746. fn(cli);
  17747. }
  17748. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17749. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17750. // the chunked coding and drop Content-Length, so a front-end that trusts
  17751. // Content-Length would disagree about where the body ends (response
  17752. // smuggling). The client must reject such a response.
  17753. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17754. for (const char *te : {"chunked", "gzip, chunked"}) {
  17755. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17756. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17757. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17758. "5\r\nhello\r\n0\r\n\r\n";
  17759. with_single_response(response, [&](Client &cli) {
  17760. auto res = cli.Get("/");
  17761. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17762. EXPECT_EQ(Error::Read, res.error()) << te;
  17763. });
  17764. with_single_response(response, [&](Client &cli) {
  17765. auto handle = cli.open_stream("GET", "/");
  17766. EXPECT_FALSE(handle.is_valid()) << te;
  17767. EXPECT_EQ(Error::Read, handle.error) << te;
  17768. });
  17769. }
  17770. }
  17771. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17772. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17773. // closing the connection (unlike a request, which must be rejected).
  17774. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17775. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17776. "Transfer-Encoding: chunked\r\n"
  17777. "Connection: close\r\n"
  17778. "\r\n"
  17779. "5\r\nhello\r\n0\r\n\r\n",
  17780. "HTTP/1.1 200 OK\r\n"
  17781. "Transfer-Encoding: gzip\r\n"
  17782. "Connection: close\r\n"
  17783. "\r\n"
  17784. "hello"}) {
  17785. with_single_response(response, [&](Client &cli) {
  17786. auto res = cli.Get("/");
  17787. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17788. EXPECT_EQ("hello", res->body);
  17789. });
  17790. with_single_response(response, [&](Client &cli) {
  17791. auto handle = cli.open_stream("GET", "/");
  17792. ASSERT_TRUE(handle.is_valid()) << response;
  17793. EXPECT_EQ("hello", read_all(handle));
  17794. });
  17795. }
  17796. }
  17797. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17798. // framing headers describe nothing to read and must not be rejected.
  17799. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17800. const std::string framing = "Content-Length: 5\r\n"
  17801. "Transfer-Encoding: chunked\r\n"
  17802. "Connection: close\r\n"
  17803. "\r\n";
  17804. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17805. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17806. });
  17807. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17808. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17809. });
  17810. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17811. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17812. with_single_response(response, [&](Client &cli) {
  17813. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17814. });
  17815. with_single_response(response, [&](Client &cli) {
  17816. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17817. });
  17818. }
  17819. }
  17820. // A payload max length of 0 means no limit, however the body is framed.
  17821. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  17822. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17823. "Transfer-Encoding: chunked\r\n"
  17824. "\r\n"
  17825. "5\r\nhello\r\n0\r\n\r\n",
  17826. "HTTP/1.1 200 OK\r\n"
  17827. "Connection: close\r\n"
  17828. "\r\n"
  17829. "hello"}) {
  17830. with_single_response(response, [&](Client &cli) {
  17831. cli.set_payload_max_length(0);
  17832. auto res = cli.Get("/");
  17833. ASSERT_TRUE(res) << response;
  17834. EXPECT_EQ("hello", res->body) << response;
  17835. });
  17836. }
  17837. }
  17838. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  17839. Server svr;
  17840. svr.set_payload_max_length(0);
  17841. svr.Post("/echo", [](const Request &req, Response &res) {
  17842. res.set_content(req.body, "text/plain");
  17843. });
  17844. auto port = svr.bind_to_any_port(HOST);
  17845. thread t = thread([&] { svr.listen_after_bind(); });
  17846. auto se = detail::scope_exit([&] {
  17847. svr.stop();
  17848. t.join();
  17849. ASSERT_FALSE(svr.is_running());
  17850. });
  17851. svr.wait_until_ready();
  17852. Client cli(HOST, port);
  17853. auto res = cli.Post(
  17854. "/echo",
  17855. [](size_t /*offset*/, DataSink &sink) {
  17856. sink.write("hello", 5);
  17857. sink.done();
  17858. return true;
  17859. },
  17860. "text/plain");
  17861. ASSERT_TRUE(res);
  17862. EXPECT_EQ(StatusCode::OK_200, res->status);
  17863. EXPECT_EQ("hello", res->body);
  17864. }
  17865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17866. TEST_F(OpenStreamTest, Gzip) {
  17867. Client cli("127.0.0.1", port_);
  17868. auto handle = cli.open_stream("GET", "/compressible", {},
  17869. {{"Accept-Encoding", "gzip"}});
  17870. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17871. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17872. }
  17873. #endif
  17874. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17875. TEST_F(OpenStreamTest, Brotli) {
  17876. Client cli("127.0.0.1", port_);
  17877. auto handle =
  17878. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17879. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17880. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17881. }
  17882. #endif
  17883. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17884. TEST_F(OpenStreamTest, Zstd) {
  17885. Client cli("127.0.0.1", port_);
  17886. auto handle = cli.open_stream("GET", "/compressible", {},
  17887. {{"Accept-Encoding", "zstd"}});
  17888. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17889. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17890. }
  17891. #endif
  17892. #ifdef CPPHTTPLIB_SSL_ENABLED
  17893. class SSLOpenStreamTest : public ::testing::Test {
  17894. protected:
  17895. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17896. void SetUp() override {
  17897. svr_.Get("/hello", [](const Request &, Response &res) {
  17898. res.set_content("Hello SSL World!", "text/plain");
  17899. });
  17900. svr_.Get("/chunked", [](const Request &, Response &res) {
  17901. res.set_chunked_content_provider("text/plain",
  17902. [](size_t offset, DataSink &sink) {
  17903. if (offset < 15) {
  17904. sink.write("chunk", 5);
  17905. return true;
  17906. }
  17907. sink.done();
  17908. return true;
  17909. });
  17910. });
  17911. svr_.Post("/echo", [](const Request &req, Response &res) {
  17912. res.set_content(req.body, req.get_header_value("Content-Type"));
  17913. });
  17914. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17915. std::string body = req.body;
  17916. res.set_chunked_content_provider(
  17917. "text/plain", [body](size_t offset, DataSink &sink) {
  17918. if (offset < body.size()) {
  17919. sink.write(body.data() + offset, body.size() - offset);
  17920. }
  17921. sink.done();
  17922. return true;
  17923. });
  17924. });
  17925. port_ = svr_.bind_to_any_port("127.0.0.1");
  17926. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17927. svr_.wait_until_ready();
  17928. }
  17929. void TearDown() override {
  17930. svr_.stop();
  17931. if (thread_.joinable()) thread_.join();
  17932. }
  17933. SSLServer svr_;
  17934. std::thread thread_;
  17935. int port_ = 0;
  17936. };
  17937. TEST_F(SSLOpenStreamTest, Basic) {
  17938. SSLClient cli("127.0.0.1", port_);
  17939. cli.enable_server_certificate_verification(false);
  17940. auto handle = cli.open_stream("GET", "/hello");
  17941. ASSERT_TRUE(handle.is_valid());
  17942. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17943. }
  17944. TEST_F(SSLOpenStreamTest, Chunked) {
  17945. SSLClient cli("127.0.0.1", port_);
  17946. cli.enable_server_certificate_verification(false);
  17947. auto handle = cli.open_stream("GET", "/chunked");
  17948. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17949. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17950. "Transfer-Encoding") == "chunked");
  17951. auto body = read_all(handle);
  17952. EXPECT_EQ("chunkchunkchunk", body);
  17953. }
  17954. TEST_F(SSLOpenStreamTest, Post) {
  17955. SSLClient cli("127.0.0.1", port_);
  17956. cli.enable_server_certificate_verification(false);
  17957. auto handle =
  17958. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17959. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17960. EXPECT_EQ(200, handle.response->status);
  17961. auto body = read_all(handle);
  17962. EXPECT_EQ("Hello SSL POST", body);
  17963. }
  17964. TEST_F(SSLOpenStreamTest, PostChunked) {
  17965. SSLClient cli("127.0.0.1", port_);
  17966. cli.enable_server_certificate_verification(false);
  17967. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17968. "Chunked SSL Data", "text/plain");
  17969. ASSERT_TRUE(handle.is_valid());
  17970. EXPECT_EQ(200, handle.response->status);
  17971. auto body = read_all(handle);
  17972. EXPECT_EQ("Chunked SSL Data", body);
  17973. }
  17974. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17975. // Content-Length is terminated by the server closing the connection. When the
  17976. // SSL peer sends a close_notify after the body, the client must treat it as a
  17977. // clean EOF and return a successful response rather than an error.
  17978. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17980. ASSERT_TRUE(svr.is_valid());
  17981. svr.set_keep_alive_max_count(1);
  17982. const std::string expected_body = "Hello from connection-close response!";
  17983. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17984. res.set_content_provider("text/plain",
  17985. [&](size_t offset, DataSink &sink) -> bool {
  17986. if (offset < expected_body.size()) {
  17987. sink.write(expected_body.data() + offset,
  17988. expected_body.size() - offset);
  17989. }
  17990. sink.done();
  17991. return true;
  17992. });
  17993. });
  17994. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17995. auto se = detail::scope_exit([&] {
  17996. svr.stop();
  17997. listen_thread.join();
  17998. ASSERT_FALSE(svr.is_running());
  17999. });
  18000. svr.wait_until_ready();
  18001. SSLClient cli(HOST, PORT);
  18002. cli.enable_server_certificate_verification(false);
  18003. auto res = cli.Get("/no-content-length");
  18004. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18005. EXPECT_EQ(StatusCode::OK_200, res->status);
  18006. EXPECT_EQ(expected_body, res->body);
  18007. }
  18008. #endif // CPPHTTPLIB_SSL_ENABLED
  18009. //==============================================================================
  18010. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18011. // results for various scenarios.
  18012. //==============================================================================
  18013. TEST(ParityTest, GetVsOpenStream) {
  18014. Server svr;
  18015. const std::string path = "/parity";
  18016. const std::string content = "Parity test content: hello world";
  18017. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18018. res.set_content(content, "text/plain");
  18019. });
  18020. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18021. auto se = detail::scope_exit([&] {
  18022. svr.stop();
  18023. t.join();
  18024. ASSERT_FALSE(svr.is_running());
  18025. });
  18026. svr.wait_until_ready();
  18027. Client cli(HOST, PORT);
  18028. // Non-stream path
  18029. auto r1 = cli.Get(path);
  18030. ASSERT_TRUE(r1);
  18031. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18032. // Stream path
  18033. auto h = cli.open_stream("GET", path);
  18034. ASSERT_TRUE(h.is_valid());
  18035. EXPECT_EQ(r1->body, read_all(h));
  18036. }
  18037. // Helper to compress data with provided compressor type T
  18038. template <typename Compressor>
  18039. static std::string compress_payload_for_parity(const std::string &in) {
  18040. std::string out;
  18041. Compressor compressor;
  18042. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18043. [&](const char *data, size_t n) {
  18044. out.append(data, n);
  18045. return true;
  18046. });
  18047. EXPECT_TRUE(ok);
  18048. return out;
  18049. }
  18050. // Helper function for compression parity tests
  18051. template <typename Compressor>
  18052. static void test_compression_parity(const std::string &original,
  18053. const std::string &path,
  18054. const std::string &encoding) {
  18055. const std::string compressed =
  18056. compress_payload_for_parity<Compressor>(original);
  18057. Server svr;
  18058. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18059. res.set_content(compressed, "application/octet-stream");
  18060. res.set_header("Content-Encoding", encoding);
  18061. });
  18062. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18063. auto se = detail::scope_exit([&] {
  18064. svr.stop();
  18065. t.join();
  18066. ASSERT_FALSE(svr.is_running());
  18067. });
  18068. svr.wait_until_ready();
  18069. Client cli(HOST, PORT);
  18070. // Non-streaming
  18071. {
  18072. auto res = cli.Get(path);
  18073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18074. EXPECT_EQ(StatusCode::OK_200, res->status);
  18075. EXPECT_EQ(original, res->body);
  18076. }
  18077. // Streaming
  18078. {
  18079. auto h = cli.open_stream("GET", path);
  18080. ASSERT_TRUE(h.is_valid());
  18081. EXPECT_EQ(original, read_all(h));
  18082. }
  18083. }
  18084. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18085. TEST(ParityTest, Gzip) {
  18086. test_compression_parity<detail::gzip_compressor>(
  18087. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18088. }
  18089. #endif
  18090. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18091. TEST(ParityTest, Brotli) {
  18092. test_compression_parity<detail::brotli_compressor>(
  18093. "Hello, brotli parity test payload", "/parity-br", "br");
  18094. }
  18095. #endif
  18096. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18097. TEST(ParityTest, Zstd) {
  18098. test_compression_parity<detail::zstd_compressor>(
  18099. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18100. }
  18101. #endif
  18102. //==============================================================================
  18103. // New Stream API Tests
  18104. //==============================================================================
  18105. inline std::string read_body(httplib::stream::Result &result) {
  18106. std::string body;
  18107. while (result.next()) {
  18108. body.append(result.data(), result.size());
  18109. }
  18110. return body;
  18111. }
  18112. TEST(ClientConnectionTest, Basic) {
  18113. httplib::ClientConnection conn;
  18114. EXPECT_FALSE(conn.is_open());
  18115. conn.sock = 1;
  18116. EXPECT_TRUE(conn.is_open());
  18117. httplib::ClientConnection conn2(std::move(conn));
  18118. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18119. conn2.sock = INVALID_SOCKET;
  18120. }
  18121. // Unified test server for all stream::* tests
  18122. class StreamApiTest : public ::testing::Test {
  18123. protected:
  18124. void SetUp() override {
  18125. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18126. res.set_content("Hello World!", "text/plain");
  18127. });
  18128. svr_.Get("/echo-params",
  18129. [](const httplib::Request &req, httplib::Response &res) {
  18130. std::string r;
  18131. for (const auto &p : req.params) {
  18132. if (!r.empty()) r += "&";
  18133. r += p.first + "=" + p.second;
  18134. }
  18135. res.set_content(r, "text/plain");
  18136. });
  18137. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18138. res.set_content(req.body, req.get_header_value("Content-Type"));
  18139. });
  18140. svr_.Post("/echo-headers",
  18141. [](const httplib::Request &req, httplib::Response &res) {
  18142. std::string r;
  18143. for (const auto &h : req.headers)
  18144. r += h.first + ": " + h.second + "\n";
  18145. res.set_content(r, "text/plain");
  18146. });
  18147. svr_.Post("/echo-params",
  18148. [](const httplib::Request &req, httplib::Response &res) {
  18149. std::string r = "params:";
  18150. for (const auto &p : req.params)
  18151. r += p.first + "=" + p.second + ";";
  18152. res.set_content(r + " body:" + req.body, "text/plain");
  18153. });
  18154. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18155. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18156. });
  18157. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18158. res.set_content("PUT:" + req.body, "text/plain");
  18159. });
  18160. svr_.Patch("/echo",
  18161. [](const httplib::Request &req, httplib::Response &res) {
  18162. res.set_content("PATCH:" + req.body, "text/plain");
  18163. });
  18164. svr_.Delete(
  18165. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18166. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18167. "text/plain");
  18168. });
  18169. svr_.Get("/head-test",
  18170. [](const httplib::Request &, httplib::Response &res) {
  18171. res.set_content("body for HEAD", "text/plain");
  18172. });
  18173. svr_.Options("/options",
  18174. [](const httplib::Request &, httplib::Response &res) {
  18175. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18176. });
  18177. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18178. svr_.wait_until_ready();
  18179. }
  18180. void TearDown() override {
  18181. svr_.stop();
  18182. if (thread_.joinable()) thread_.join();
  18183. }
  18184. httplib::Server svr_;
  18185. std::thread thread_;
  18186. };
  18187. // stream::Get tests
  18188. TEST_F(StreamApiTest, GetBasic) {
  18189. httplib::Client cli(HOST, PORT);
  18190. auto result = httplib::stream::Get(cli, "/hello");
  18191. ASSERT_TRUE(result.is_valid());
  18192. EXPECT_EQ(200, result.status());
  18193. EXPECT_EQ("Hello World!", read_body(result));
  18194. }
  18195. TEST_F(StreamApiTest, GetWithParams) {
  18196. httplib::Client cli(HOST, PORT);
  18197. httplib::Params params{{"foo", "bar"}};
  18198. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18199. ASSERT_TRUE(result.is_valid());
  18200. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18201. }
  18202. TEST_F(StreamApiTest, GetConnectionError) {
  18203. httplib::Client cli(HOST, 9999);
  18204. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18205. }
  18206. TEST_F(StreamApiTest, Get404) {
  18207. httplib::Client cli(HOST, PORT);
  18208. auto result = httplib::stream::Get(cli, "/nonexistent");
  18209. EXPECT_TRUE(result.is_valid());
  18210. EXPECT_EQ(404, result.status());
  18211. }
  18212. // stream::Post tests
  18213. TEST_F(StreamApiTest, PostBasic) {
  18214. httplib::Client cli(HOST, PORT);
  18215. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18216. "application/json");
  18217. ASSERT_TRUE(result.is_valid());
  18218. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18219. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18220. }
  18221. TEST_F(StreamApiTest, PostWithHeaders) {
  18222. httplib::Client cli(HOST, PORT);
  18223. httplib::Headers headers{{"X-Custom", "value"}};
  18224. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18225. "text/plain");
  18226. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18227. }
  18228. TEST_F(StreamApiTest, PostWithParams) {
  18229. httplib::Client cli(HOST, PORT);
  18230. httplib::Params params{{"k", "v"}};
  18231. auto result =
  18232. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18233. auto body = read_body(result);
  18234. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18235. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18236. }
  18237. TEST_F(StreamApiTest, PostLarge) {
  18238. httplib::Client cli(HOST, PORT);
  18239. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18240. size_t total = 0;
  18241. while (result.next()) {
  18242. total += result.size();
  18243. }
  18244. EXPECT_EQ(100u * 1024u, total);
  18245. }
  18246. // stream::Put/Patch tests
  18247. TEST_F(StreamApiTest, PutAndPatch) {
  18248. httplib::Client cli(HOST, PORT);
  18249. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18250. EXPECT_EQ("PUT:test", read_body(put));
  18251. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18252. EXPECT_EQ("PATCH:test", read_body(patch));
  18253. }
  18254. // stream::Delete tests
  18255. TEST_F(StreamApiTest, Delete) {
  18256. httplib::Client cli(HOST, PORT);
  18257. auto del1 = httplib::stream::Delete(cli, "/resource");
  18258. EXPECT_EQ("Deleted", read_body(del1));
  18259. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18260. EXPECT_EQ("Deleted:data", read_body(del2));
  18261. }
  18262. // stream::Head/Options tests
  18263. TEST_F(StreamApiTest, HeadAndOptions) {
  18264. httplib::Client cli(HOST, PORT);
  18265. auto head = httplib::stream::Head(cli, "/head-test");
  18266. EXPECT_TRUE(head.is_valid());
  18267. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18268. auto opts = httplib::stream::Options(cli, "/options");
  18269. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18270. }
  18271. // SSL stream::* tests
  18272. #ifdef CPPHTTPLIB_SSL_ENABLED
  18273. class SSLStreamApiTest : public ::testing::Test {
  18274. protected:
  18275. void SetUp() override {
  18276. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18277. res.set_content("Hello SSL!", "text/plain");
  18278. });
  18279. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18280. res.set_content(req.body, "text/plain");
  18281. });
  18282. port_ = svr_.bind_to_any_port("127.0.0.1");
  18283. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18284. svr_.wait_until_ready();
  18285. }
  18286. void TearDown() override {
  18287. svr_.stop();
  18288. if (thread_.joinable()) thread_.join();
  18289. }
  18290. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18291. std::thread thread_;
  18292. int port_ = 0;
  18293. };
  18294. TEST_F(SSLStreamApiTest, GetAndPost) {
  18295. httplib::SSLClient cli("127.0.0.1", port_);
  18296. cli.enable_server_certificate_verification(false);
  18297. auto get = httplib::stream::Get(cli, "/hello");
  18298. EXPECT_EQ("Hello SSL!", read_body(get));
  18299. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18300. EXPECT_EQ("test", read_body(post));
  18301. }
  18302. #endif
  18303. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18304. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18305. // BodyReader
  18306. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18307. // Test that read timeout during streaming is detected
  18308. // Use a large content-length response where server delays mid-stream
  18309. Server svr;
  18310. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18311. // Send a large response with delay in the middle
  18312. res.set_content_provider(
  18313. 1000, // content_length
  18314. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18315. if (offset < 100) {
  18316. // Send first 100 bytes immediately
  18317. std::string data(100, 'A');
  18318. sink.write(data.c_str(), data.size());
  18319. return true;
  18320. }
  18321. // Then delay longer than client timeout
  18322. std::this_thread::sleep_for(std::chrono::seconds(3));
  18323. std::string data(900, 'B');
  18324. sink.write(data.c_str(), data.size());
  18325. return true;
  18326. });
  18327. });
  18328. auto port = 8091;
  18329. std::thread t([&]() { svr.listen("localhost", port); });
  18330. svr.wait_until_ready();
  18331. Client cli("localhost", port);
  18332. cli.set_read_timeout(1, 0); // 1 second timeout
  18333. auto handle = cli.open_stream("GET", "/slow-stream");
  18334. ASSERT_TRUE(handle.is_valid());
  18335. char buf[256];
  18336. ssize_t total = 0;
  18337. ssize_t n;
  18338. bool got_error = false;
  18339. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18340. total += n;
  18341. }
  18342. if (n < 0) {
  18343. got_error = true;
  18344. // Should be timeout or read error
  18345. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18346. handle.get_read_error() == Error::Read)
  18347. << "Actual error: " << to_string(handle.get_read_error());
  18348. }
  18349. // Either we got an error, or we got less data than expected
  18350. EXPECT_TRUE(got_error || total < 1000)
  18351. << "Expected timeout but got all " << total << " bytes";
  18352. svr.stop();
  18353. t.join();
  18354. }
  18355. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18356. // Test connection closed detection via BodyReader
  18357. Server svr;
  18358. std::atomic<bool> close_now{false};
  18359. svr.Get("/will-close", [&](const Request &, Response &res) {
  18360. res.set_content_provider(
  18361. 10000, // Large content_length that we won't fully send
  18362. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18363. if (offset < 100) {
  18364. std::string data(100, 'X');
  18365. sink.write(data.c_str(), data.size());
  18366. return true;
  18367. }
  18368. // Wait for signal then abort
  18369. while (!close_now) {
  18370. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18371. }
  18372. return false; // Abort - server will close connection
  18373. });
  18374. });
  18375. auto port = 8092;
  18376. std::thread t([&]() { svr.listen("localhost", port); });
  18377. svr.wait_until_ready();
  18378. Client cli("localhost", port);
  18379. auto handle = cli.open_stream("GET", "/will-close");
  18380. ASSERT_TRUE(handle.is_valid());
  18381. char buf[256];
  18382. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18383. EXPECT_GT(n, 0) << "First read should succeed";
  18384. // Signal server to close
  18385. close_now = true;
  18386. // Keep reading until error or EOF
  18387. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18388. // Keep reading
  18389. }
  18390. // Should get an error since content_length wasn't satisfied
  18391. if (n < 0) {
  18392. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18393. handle.get_read_error() == Error::Read)
  18394. << "Actual error: " << to_string(handle.get_read_error());
  18395. }
  18396. svr.stop();
  18397. t.join();
  18398. }
  18399. #ifdef CPPHTTPLIB_SSL_ENABLED
  18400. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18401. // Test that read timeout during SSL streaming is detected
  18402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18403. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18404. res.set_content_provider(
  18405. 1000, "text/plain",
  18406. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18407. if (offset < 100) {
  18408. std::string data(100, 'A');
  18409. sink.write(data.c_str(), data.size());
  18410. return true;
  18411. }
  18412. std::this_thread::sleep_for(std::chrono::seconds(3));
  18413. std::string data(900, 'B');
  18414. sink.write(data.c_str(), data.size());
  18415. return true;
  18416. });
  18417. });
  18418. auto port = 8093;
  18419. std::thread t([&]() { svr.listen("localhost", port); });
  18420. svr.wait_until_ready();
  18421. SSLClient cli("localhost", port);
  18422. cli.enable_server_certificate_verification(false);
  18423. cli.set_read_timeout(1, 0); // 1 second timeout
  18424. auto handle = cli.open_stream("GET", "/slow-stream");
  18425. ASSERT_TRUE(handle.is_valid());
  18426. char buf[256];
  18427. ssize_t total = 0;
  18428. ssize_t n;
  18429. bool got_error = false;
  18430. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18431. total += n;
  18432. }
  18433. if (n < 0) {
  18434. got_error = true;
  18435. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18436. handle.get_read_error() == Error::Read)
  18437. << "Actual error: " << to_string(handle.get_read_error());
  18438. }
  18439. EXPECT_TRUE(got_error || total < 1000)
  18440. << "Expected timeout but got all " << total << " bytes";
  18441. svr.stop();
  18442. t.join();
  18443. }
  18444. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18445. // Test SSL connection closed detection
  18446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18447. std::atomic<bool> close_now{false};
  18448. svr.Get("/will-close", [&](const Request &, Response &res) {
  18449. res.set_content_provider(
  18450. 10000, "text/plain",
  18451. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18452. if (offset < 100) {
  18453. std::string data(100, 'X');
  18454. sink.write(data.c_str(), data.size());
  18455. return true;
  18456. }
  18457. while (!close_now) {
  18458. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18459. }
  18460. return false;
  18461. });
  18462. });
  18463. auto port = 8094;
  18464. std::thread t([&]() { svr.listen("localhost", port); });
  18465. svr.wait_until_ready();
  18466. SSLClient cli("localhost", port);
  18467. cli.enable_server_certificate_verification(false);
  18468. auto handle = cli.open_stream("GET", "/will-close");
  18469. ASSERT_TRUE(handle.is_valid());
  18470. char buf[256];
  18471. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18472. EXPECT_GT(n, 0);
  18473. // Signal server to close
  18474. close_now = true;
  18475. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18476. // Keep reading
  18477. }
  18478. if (n < 0) {
  18479. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18480. handle.get_read_error() == Error::Read)
  18481. << "Actual error: " << to_string(handle.get_read_error());
  18482. }
  18483. svr.stop();
  18484. t.join();
  18485. }
  18486. #endif
  18487. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18488. using namespace httplib;
  18489. // Create a test file
  18490. const char *fname = "etag_testfile.txt";
  18491. const char *content = "etag-content";
  18492. {
  18493. std::ofstream ofs(fname);
  18494. ofs << content;
  18495. ASSERT_TRUE(ofs.good());
  18496. }
  18497. Server svr;
  18498. svr.set_mount_point("/static", ".");
  18499. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18500. svr.wait_until_ready();
  18501. Client cli(HOST, PORT);
  18502. // First request: should get 200 with ETag header
  18503. auto res1 = cli.Get("/static/etag_testfile.txt");
  18504. ASSERT_TRUE(res1);
  18505. ASSERT_EQ(200, res1->status);
  18506. ASSERT_TRUE(res1->has_header("ETag"));
  18507. std::string etag = res1->get_header_value("ETag");
  18508. EXPECT_FALSE(etag.empty());
  18509. // Verify ETag format: W/"hex-hex"
  18510. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18511. EXPECT_EQ('W', etag[0]);
  18512. EXPECT_EQ('/', etag[1]);
  18513. EXPECT_EQ('"', etag[2]);
  18514. EXPECT_EQ('"', etag.back());
  18515. // Exact match: expect 304 Not Modified
  18516. Headers h2 = {{"If-None-Match", etag}};
  18517. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18518. ASSERT_TRUE(res2);
  18519. EXPECT_EQ(304, res2->status);
  18520. // Wildcard match: expect 304 Not Modified
  18521. Headers h3 = {{"If-None-Match", "*"}};
  18522. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18523. ASSERT_TRUE(res3);
  18524. EXPECT_EQ(304, res3->status);
  18525. // Non-matching ETag: expect 200
  18526. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18527. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18528. ASSERT_TRUE(res4);
  18529. EXPECT_EQ(200, res4->status);
  18530. // Multiple ETags with one matching: expect 304
  18531. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18532. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18533. ASSERT_TRUE(res5);
  18534. EXPECT_EQ(304, res5->status);
  18535. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18536. // that equivalent to the single comma-separated list above, so the match on
  18537. // the second line must still be found.
  18538. Headers h6;
  18539. h6.emplace("If-None-Match", "W/\"other\"");
  18540. h6.emplace("If-None-Match", etag);
  18541. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18542. ASSERT_TRUE(res6);
  18543. EXPECT_EQ(304, res6->status);
  18544. svr.stop();
  18545. t.join();
  18546. std::remove(fname);
  18547. }
  18548. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18549. using namespace httplib;
  18550. Server svr;
  18551. svr.set_mount_point("/static", ".");
  18552. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18553. svr.wait_until_ready();
  18554. Client cli(HOST, PORT);
  18555. // Send If-None-Match: * to a non-existent file
  18556. Headers h = {{"If-None-Match", "*"}};
  18557. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18559. EXPECT_EQ(404, res->status);
  18560. svr.stop();
  18561. t.join();
  18562. }
  18563. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18564. using namespace httplib;
  18565. // Create a test file
  18566. const char *fname = "etag_boundary_testfile.txt";
  18567. const char *content = "boundary-test";
  18568. {
  18569. std::ofstream ofs(fname);
  18570. ofs << content;
  18571. ASSERT_TRUE(ofs.good());
  18572. }
  18573. Server svr;
  18574. svr.set_mount_point("/static", ".");
  18575. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18576. svr.wait_until_ready();
  18577. Client cli(HOST, PORT);
  18578. // Get the actual ETag
  18579. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18580. ASSERT_TRUE(res1);
  18581. ASSERT_EQ(200, res1->status);
  18582. ASSERT_TRUE(res1->has_header("ETag"));
  18583. std::string etag = res1->get_header_value("ETag");
  18584. // Test 1: Very long ETag value (longer than actual ETag)
  18585. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18586. Headers h1 = {{"If-None-Match", "W/"
  18587. "\"very-long-etag-value-that-is-much-longer-"
  18588. "than-the-actual-etag-value\""}};
  18589. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18590. ASSERT_TRUE(res2);
  18591. EXPECT_EQ(200, res2->status); // Should not match
  18592. // Test 2: Long string followed by wildcard
  18593. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18594. // string)
  18595. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18596. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18597. ASSERT_TRUE(res3);
  18598. EXPECT_EQ(304, res3->status); // Should match on "*"
  18599. // Test 3: Wildcard followed by long string
  18600. // Should match on "*" immediately and return 304
  18601. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18602. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18603. ASSERT_TRUE(res4);
  18604. EXPECT_EQ(304, res4->status); // Should match on "*"
  18605. // Test 4: Multiple long non-matching values
  18606. // Should NOT match and return 200 (test that all comparisons are safe)
  18607. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18608. "W/\"second-long-non-matching-value\", "
  18609. "W/\"third-long-non-matching-value\""}};
  18610. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18611. ASSERT_TRUE(res5);
  18612. EXPECT_EQ(200, res5->status); // Should not match
  18613. // Test 5: Single character that is not "*" (edge case)
  18614. Headers h5 = {{"If-None-Match", "X"}};
  18615. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18616. ASSERT_TRUE(res6);
  18617. EXPECT_EQ(200, res6->status); // Should not match
  18618. svr.stop();
  18619. t.join();
  18620. std::remove(fname);
  18621. }
  18622. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18623. using namespace httplib;
  18624. // Create a test file
  18625. const char *fname = "ims_testfile.txt";
  18626. const char *content = "if-modified-since-test";
  18627. {
  18628. std::ofstream ofs(fname);
  18629. ofs << content;
  18630. ASSERT_TRUE(ofs.good());
  18631. }
  18632. Server svr;
  18633. svr.set_mount_point("/static", ".");
  18634. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18635. svr.wait_until_ready();
  18636. Client cli(HOST, PORT);
  18637. // First request: should get 200 with Last-Modified header
  18638. auto res1 = cli.Get("/static/ims_testfile.txt");
  18639. ASSERT_TRUE(res1);
  18640. ASSERT_EQ(200, res1->status);
  18641. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18642. std::string last_modified = res1->get_header_value("Last-Modified");
  18643. EXPECT_FALSE(last_modified.empty());
  18644. // If-Modified-Since with same time: expect 304
  18645. Headers h2 = {{"If-Modified-Since", last_modified}};
  18646. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18647. ASSERT_TRUE(res2);
  18648. EXPECT_EQ(304, res2->status);
  18649. // If-Modified-Since with future time: expect 304
  18650. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18651. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18652. ASSERT_TRUE(res3);
  18653. EXPECT_EQ(304, res3->status);
  18654. // If-Modified-Since with past time: expect 200
  18655. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18656. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18657. ASSERT_TRUE(res4);
  18658. EXPECT_EQ(200, res4->status);
  18659. // If-None-Match takes precedence over If-Modified-Since
  18660. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18661. ASSERT_TRUE(res1->has_header("ETag"));
  18662. std::string etag = res1->get_header_value("ETag");
  18663. Headers h5 = {{"If-None-Match", etag},
  18664. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18665. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18666. ASSERT_TRUE(res5);
  18667. EXPECT_EQ(304, res5->status);
  18668. svr.stop();
  18669. t.join();
  18670. std::remove(fname);
  18671. }
  18672. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18673. using namespace httplib;
  18674. Server svr;
  18675. // Endpoint that returns compressible content
  18676. svr.Get("/compressible", [](const Request &, Response &res) {
  18677. // Return a large enough body to trigger compression
  18678. std::string body(1000, 'a');
  18679. res.set_content(body, "text/plain");
  18680. });
  18681. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18682. svr.wait_until_ready();
  18683. Client cli(HOST, PORT);
  18684. // Request with gzip support: should get Vary header when compressed
  18685. cli.set_compress(true);
  18686. auto res1 = cli.Get("/compressible");
  18687. ASSERT_TRUE(res1);
  18688. EXPECT_EQ(200, res1->status);
  18689. // If Content-Encoding is set, Vary should also be set
  18690. if (res1->has_header("Content-Encoding")) {
  18691. EXPECT_TRUE(res1->has_header("Vary"));
  18692. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18693. }
  18694. // Request without Accept-Encoding header: should not have compression
  18695. Headers h_no_compress;
  18696. auto res2 = cli.Get("/compressible", h_no_compress);
  18697. ASSERT_TRUE(res2);
  18698. EXPECT_EQ(200, res2->status);
  18699. // Verify Vary header is present when compression is applied
  18700. // (the exact behavior depends on server configuration)
  18701. svr.stop();
  18702. t.join();
  18703. }
  18704. TEST(ETagTest, IfRangeWithETag) {
  18705. using namespace httplib;
  18706. // Create a test file with known content
  18707. const char *fname = "if_range_testfile.txt";
  18708. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18709. {
  18710. std::ofstream ofs(fname);
  18711. ofs << content;
  18712. ASSERT_TRUE(ofs.good());
  18713. }
  18714. Server svr;
  18715. svr.set_mount_point("/static", ".");
  18716. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18717. svr.wait_until_ready();
  18718. Client cli(HOST, PORT);
  18719. // First request: get ETag
  18720. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18721. ASSERT_TRUE(res1);
  18722. ASSERT_EQ(200, res1->status);
  18723. ASSERT_TRUE(res1->has_header("ETag"));
  18724. std::string etag = res1->get_header_value("ETag");
  18725. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18726. // Since our server generates weak ETags (W/"..."), If-Range with our
  18727. // ETag should NOT result in partial content - it should return full content.
  18728. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18729. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18730. ASSERT_TRUE(res2);
  18731. // Weak ETag in If-Range -> full content (200), not partial (206)
  18732. EXPECT_EQ(200, res2->status);
  18733. EXPECT_EQ(content, res2->body);
  18734. EXPECT_FALSE(res2->has_header("Content-Range"));
  18735. // Range request with non-matching If-Range (ETag): should get 200 (full
  18736. // content)
  18737. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18738. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18739. ASSERT_TRUE(res3);
  18740. EXPECT_EQ(200, res3->status);
  18741. EXPECT_EQ(content, res3->body);
  18742. EXPECT_FALSE(res3->has_header("Content-Range"));
  18743. // Range request with strong ETag (hypothetical - our server doesn't generate
  18744. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18745. // should return full content)
  18746. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18747. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18748. ASSERT_TRUE(res4);
  18749. EXPECT_EQ(200, res4->status);
  18750. EXPECT_EQ(content, res4->body);
  18751. EXPECT_FALSE(res4->has_header("Content-Range"));
  18752. svr.stop();
  18753. t.join();
  18754. std::remove(fname);
  18755. }
  18756. TEST(ETagTest, IfRangeWithDate) {
  18757. using namespace httplib;
  18758. // Create a test file
  18759. const char *fname = "if_range_date_testfile.txt";
  18760. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18761. {
  18762. std::ofstream ofs(fname);
  18763. ofs << content;
  18764. ASSERT_TRUE(ofs.good());
  18765. }
  18766. Server svr;
  18767. svr.set_mount_point("/static", ".");
  18768. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18769. svr.wait_until_ready();
  18770. Client cli(HOST, PORT);
  18771. // First request: get Last-Modified
  18772. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18773. ASSERT_TRUE(res1);
  18774. ASSERT_EQ(200, res1->status);
  18775. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18776. std::string last_modified = res1->get_header_value("Last-Modified");
  18777. // Range request with matching If-Range (date): should get 206
  18778. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18779. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18780. ASSERT_TRUE(res2);
  18781. EXPECT_EQ(206, res2->status);
  18782. EXPECT_EQ("FGHIJ", res2->body);
  18783. // Range request with old If-Range date: should get 200 (full content)
  18784. Headers h3 = {{"Range", "bytes=5-9"},
  18785. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18786. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18787. ASSERT_TRUE(res3);
  18788. EXPECT_EQ(200, res3->status);
  18789. EXPECT_EQ(content, res3->body);
  18790. // Range request with future If-Range date: should get 206
  18791. Headers h4 = {{"Range", "bytes=0-4"},
  18792. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18793. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18794. ASSERT_TRUE(res4);
  18795. EXPECT_EQ(206, res4->status);
  18796. EXPECT_EQ("ABCDE", res4->body);
  18797. svr.stop();
  18798. t.join();
  18799. std::remove(fname);
  18800. }
  18801. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18802. using namespace httplib;
  18803. const char *fname = "etag_malformed.txt";
  18804. const char *content = "malformed-etag";
  18805. {
  18806. std::ofstream ofs(fname);
  18807. ofs << content;
  18808. ASSERT_TRUE(ofs.good());
  18809. }
  18810. Server svr;
  18811. svr.set_mount_point("/static", ".");
  18812. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18813. svr.wait_until_ready();
  18814. Client cli(HOST, PORT);
  18815. // baseline: should get 200 and an ETag
  18816. auto res1 = cli.Get("/static/etag_malformed.txt");
  18817. ASSERT_TRUE(res1);
  18818. ASSERT_EQ(200, res1->status);
  18819. ASSERT_TRUE(res1->has_header("ETag"));
  18820. // Malformed ETag value (missing quotes) should be treated as non-matching
  18821. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18822. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18823. ASSERT_TRUE(res_bad);
  18824. EXPECT_EQ(200, res_bad->status);
  18825. // Whitespace-only header value should be considered invalid / non-matching
  18826. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18827. "Host: localhost\r\n"
  18828. "If-None-Match: \r\n"
  18829. "Connection: close\r\n"
  18830. "\r\n";
  18831. std::string out;
  18832. ASSERT_TRUE(send_request(5, raw_req, &out));
  18833. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18834. svr.stop();
  18835. t.join();
  18836. std::remove(fname);
  18837. }
  18838. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18839. using namespace httplib;
  18840. const char *fname = "ims_invalid_format.txt";
  18841. const char *content = "ims-bad-format";
  18842. {
  18843. std::ofstream ofs(fname);
  18844. ofs << content;
  18845. ASSERT_TRUE(ofs.good());
  18846. }
  18847. Server svr;
  18848. svr.set_mount_point("/static", ".");
  18849. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18850. svr.wait_until_ready();
  18851. Client cli(HOST, PORT);
  18852. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18853. ASSERT_TRUE(res1);
  18854. ASSERT_EQ(200, res1->status);
  18855. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18856. // If-Modified-Since with invalid format should not result in 304
  18857. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18858. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18859. ASSERT_TRUE(res_bad);
  18860. EXPECT_EQ(200, res_bad->status);
  18861. // If-Range with invalid date format should be treated as mismatch -> full
  18862. // content (200)
  18863. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18864. {"If-Range", "invalid-date"}};
  18865. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18866. ASSERT_TRUE(res_ifrange);
  18867. EXPECT_EQ(200, res_ifrange->status);
  18868. svr.stop();
  18869. t.join();
  18870. std::remove(fname);
  18871. }
  18872. TEST(ETagTest, IfRangeWithMalformedETag) {
  18873. using namespace httplib;
  18874. const char *fname = "ifrange_malformed.txt";
  18875. const std::string content = "0123456789";
  18876. {
  18877. std::ofstream ofs(fname);
  18878. ofs << content;
  18879. ASSERT_TRUE(ofs.good());
  18880. }
  18881. Server svr;
  18882. svr.set_mount_point("/static", ".");
  18883. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18884. svr.wait_until_ready();
  18885. Client cli(HOST, PORT);
  18886. // First request: get ETag
  18887. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18888. ASSERT_TRUE(res1);
  18889. ASSERT_EQ(200, res1->status);
  18890. ASSERT_TRUE(res1->has_header("ETag"));
  18891. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18892. // full content (200)
  18893. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18894. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18895. ASSERT_TRUE(res2);
  18896. EXPECT_EQ(200, res2->status);
  18897. EXPECT_EQ(content, res2->body);
  18898. svr.stop();
  18899. t.join();
  18900. std::remove(fname);
  18901. }
  18902. TEST(ETagTest, ExtremeLargeDateValues) {
  18903. using namespace httplib;
  18904. const char *fname = "ims_extreme_date.txt";
  18905. const char *content = "ims-extreme-date";
  18906. {
  18907. std::ofstream ofs(fname);
  18908. ofs << content;
  18909. ASSERT_TRUE(ofs.good());
  18910. }
  18911. Server svr;
  18912. svr.set_mount_point("/static", ".");
  18913. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18914. svr.wait_until_ready();
  18915. Client cli(HOST, PORT);
  18916. auto res1 = cli.Get(std::string("/static/") + fname);
  18917. ASSERT_TRUE(res1);
  18918. ASSERT_EQ(200, res1->status);
  18919. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18920. // Extremely large year that may overflow date parsing routines.
  18921. Headers h_large_date = {
  18922. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18923. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18924. ASSERT_TRUE(res_bad);
  18925. // Expect server to treat this as invalid/mismatch and return full content
  18926. EXPECT_EQ(200, res_bad->status);
  18927. // If-Range with extremely large date should be treated as mismatch -> full
  18928. // content (200)
  18929. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18930. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18931. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18932. ASSERT_TRUE(res_ifrange);
  18933. EXPECT_EQ(200, res_ifrange->status);
  18934. svr.stop();
  18935. t.join();
  18936. std::remove(fname);
  18937. }
  18938. TEST(ETagTest, NegativeFileModificationTime) {
  18939. using namespace httplib;
  18940. const char *fname = "ims_negative_mtime.txt";
  18941. const std::string content = "negative-mtime";
  18942. {
  18943. std::ofstream ofs(fname);
  18944. ofs << content;
  18945. ASSERT_TRUE(ofs.good());
  18946. }
  18947. // Try to set file mtime to a negative value. This may fail on some
  18948. // platforms/filesystems; if it fails, the test will still verify server
  18949. // behaves safely by performing a regular conditional request.
  18950. #if defined(__APPLE__) || defined(__linux__)
  18951. bool set_negative = false;
  18952. do {
  18953. struct timeval times[2];
  18954. // access time: now
  18955. times[0].tv_sec = time(nullptr);
  18956. times[0].tv_usec = 0;
  18957. // modification time: negative (e.g., -1)
  18958. times[1].tv_sec = -1;
  18959. times[1].tv_usec = 0;
  18960. if (utimes(fname, times) == 0) { set_negative = true; }
  18961. } while (0);
  18962. #else
  18963. bool set_negative = false;
  18964. #endif
  18965. Server svr;
  18966. svr.set_mount_point("/static", ".");
  18967. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18968. svr.wait_until_ready();
  18969. Client cli(HOST, PORT);
  18970. auto res1 = cli.Get(std::string("/static/") + fname);
  18971. ASSERT_TRUE(res1);
  18972. ASSERT_EQ(200, res1->status);
  18973. bool has_last_modified = res1->has_header("Last-Modified");
  18974. std::string last_modified;
  18975. if (has_last_modified) {
  18976. last_modified = res1->get_header_value("Last-Modified");
  18977. }
  18978. if (set_negative) {
  18979. // If we successfully set a negative mtime, ensure server returns a
  18980. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18981. // with an old date and ensure server handles it without crash.
  18982. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18983. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18984. ASSERT_TRUE(res2);
  18985. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18986. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18987. } else {
  18988. // Could not set negative mtime on this platform; fall back to verifying
  18989. // that normal invalid/malformed dates are treated safely (non-304).
  18990. Headers h_bad_date = {
  18991. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18992. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18993. ASSERT_TRUE(res_bad);
  18994. EXPECT_EQ(200, res_bad->status);
  18995. }
  18996. svr.stop();
  18997. t.join();
  18998. std::remove(fname);
  18999. }
  19000. //==============================================================================
  19001. // Integration Tests with Server
  19002. //==============================================================================
  19003. class SSEIntegrationTest : public ::testing::Test {
  19004. protected:
  19005. void SetUp() override {
  19006. stop_server_.store(false);
  19007. events_.clear();
  19008. server_ = httplib::detail::make_unique<Server>();
  19009. setup_server();
  19010. start_server();
  19011. }
  19012. void TearDown() override {
  19013. stop_server_.store(true);
  19014. event_cv_.notify_all();
  19015. server_->stop();
  19016. if (server_thread_.joinable()) { server_thread_.join(); }
  19017. }
  19018. void setup_server() {
  19019. // Simple SSE endpoint
  19020. server_->Get("/events", [this](const Request &req, Response &res) {
  19021. auto last_id = req.get_header_value("Last-Event-ID");
  19022. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19023. res.set_chunked_content_provider(
  19024. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19025. std::unique_lock<std::mutex> lock(event_mutex_);
  19026. if (event_cv_.wait_for(
  19027. lock, std::chrono::milliseconds(200), [this] {
  19028. return !events_.empty() || stop_server_.load();
  19029. })) {
  19030. if (stop_server_.load()) { return false; }
  19031. if (!events_.empty()) {
  19032. std::string event = events_.front();
  19033. events_.erase(events_.begin());
  19034. sink.write(event.data(), event.size());
  19035. return true;
  19036. }
  19037. }
  19038. return !stop_server_.load();
  19039. });
  19040. });
  19041. // Endpoint that returns error
  19042. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19043. res.status = 500;
  19044. res.set_content("Internal Server Error", "text/plain");
  19045. });
  19046. // Endpoint for custom event types
  19047. server_->Get("/custom-events", [](const Request &, Response &res) {
  19048. res.set_chunked_content_provider(
  19049. "text/event-stream", [](size_t offset, DataSink &sink) {
  19050. if (offset == 0) {
  19051. std::string event = "event: update\ndata: updated\n\n"
  19052. "event: delete\ndata: deleted\n\n";
  19053. sink.write(event.data(), event.size());
  19054. }
  19055. return false; // End stream after sending
  19056. });
  19057. });
  19058. }
  19059. void start_server() {
  19060. port_ = server_->bind_to_any_port(HOST);
  19061. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19062. // Wait for server to start
  19063. while (!server_->is_running()) {
  19064. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19065. }
  19066. }
  19067. int get_port() const { return port_; }
  19068. void send_event(const std::string &event) {
  19069. std::lock_guard<std::mutex> lock(event_mutex_);
  19070. events_.push_back(event);
  19071. event_cv_.notify_all();
  19072. }
  19073. std::unique_ptr<Server> server_;
  19074. std::thread server_thread_;
  19075. std::mutex event_mutex_;
  19076. std::condition_variable event_cv_;
  19077. std::vector<std::string> events_;
  19078. std::atomic<bool> stop_server_{false};
  19079. std::string last_received_event_id_;
  19080. int port_ = 0;
  19081. };
  19082. //==============================================================================
  19083. // SSE Parsing Tests
  19084. //==============================================================================
  19085. class SSEParsingTest : public SSEIntegrationTest {
  19086. protected:
  19087. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19088. // A trailing sentinel event tells when the whole stream has been parsed.
  19089. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19090. auto body = stream + "event: end\ndata: end\n\n";
  19091. server_->Get("/parse", [body](const Request &, Response &res) {
  19092. res.set_content(body, "text/event-stream");
  19093. });
  19094. return collect("/parse");
  19095. }
  19096. // Runs SSEClient against path until an "end" event arrives and returns the
  19097. // messages dispatched before it
  19098. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19099. Client client(HOST, get_port());
  19100. sse::SSEClient sse(client, path);
  19101. std::mutex mutex;
  19102. std::condition_variable cv;
  19103. std::vector<sse::SSEMessage> messages;
  19104. auto done = false;
  19105. sse.on_message([&](const sse::SSEMessage &msg) {
  19106. std::lock_guard<std::mutex> lock(mutex);
  19107. // Ignore a replay from a reconnect that races with stop()
  19108. if (!done) { messages.push_back(msg); }
  19109. });
  19110. sse.on_event("end", [&](const sse::SSEMessage &) {
  19111. std::lock_guard<std::mutex> lock(mutex);
  19112. done = true;
  19113. cv.notify_all();
  19114. });
  19115. sse.set_reconnect_interval(100);
  19116. sse.start_async();
  19117. {
  19118. std::unique_lock<std::mutex> lock(mutex);
  19119. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19120. }
  19121. sse.stop();
  19122. EXPECT_TRUE(done);
  19123. return messages;
  19124. }
  19125. };
  19126. TEST_F(SSEParsingTest, SingleLineData) {
  19127. auto msgs = parse("data: hello\n\n");
  19128. ASSERT_EQ(msgs.size(), 1u);
  19129. EXPECT_EQ(msgs[0].data, "hello");
  19130. EXPECT_EQ(msgs[0].event, "message");
  19131. }
  19132. TEST_F(SSEParsingTest, MultiLineData) {
  19133. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19134. ASSERT_EQ(msgs.size(), 1u);
  19135. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19136. }
  19137. TEST_F(SSEParsingTest, CustomEventType) {
  19138. auto msgs = parse("event: update\ndata: payload\n\n");
  19139. ASSERT_EQ(msgs.size(), 1u);
  19140. EXPECT_EQ(msgs[0].event, "update");
  19141. EXPECT_EQ(msgs[0].data, "payload");
  19142. }
  19143. TEST_F(SSEParsingTest, EventIdHandling) {
  19144. auto msgs = parse("id: 12345\ndata: test\n\n");
  19145. ASSERT_EQ(msgs.size(), 1u);
  19146. EXPECT_EQ(msgs[0].id, "12345");
  19147. }
  19148. TEST_F(SSEParsingTest, EmptyEventId) {
  19149. auto msgs = parse("id:\ndata: test\n\n");
  19150. ASSERT_EQ(msgs.size(), 1u);
  19151. EXPECT_EQ(msgs[0].id, "");
  19152. }
  19153. TEST_F(SSEParsingTest, CommentsIgnored) {
  19154. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19155. ASSERT_EQ(msgs.size(), 1u);
  19156. EXPECT_EQ(msgs[0].data, "hello");
  19157. EXPECT_EQ(msgs[0].event, "message");
  19158. }
  19159. TEST_F(SSEParsingTest, ColonInValue) {
  19160. auto msgs = parse("data: hello:world:test\n\n");
  19161. ASSERT_EQ(msgs.size(), 1u);
  19162. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19163. }
  19164. TEST_F(SSEParsingTest, FieldNameOnly) {
  19165. // A line without a colon is a field name with an empty value
  19166. auto msgs = parse("data\n\n");
  19167. ASSERT_EQ(msgs.size(), 1u);
  19168. EXPECT_EQ(msgs[0].data, "");
  19169. }
  19170. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19171. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19172. ASSERT_EQ(msgs.size(), 1u);
  19173. EXPECT_EQ(msgs[0].event, "update");
  19174. EXPECT_EQ(msgs[0].data, "hello");
  19175. }
  19176. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19177. auto msgs = parse("data\r\n\r\n");
  19178. ASSERT_EQ(msgs.size(), 1u);
  19179. EXPECT_EQ(msgs[0].data, "");
  19180. }
  19181. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19182. auto msgs = parse("event: update\rdata: hello\r\r");
  19183. ASSERT_EQ(msgs.size(), 1u);
  19184. EXPECT_EQ(msgs[0].event, "update");
  19185. EXPECT_EQ(msgs[0].data, "hello");
  19186. }
  19187. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19188. // Chunk boundaries fall inside every \r\n and right before the first one
  19189. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19190. "\n\r", "\nevent: end\ndata: end\n\n"};
  19191. server_->Get("/split", [chunks](const Request &, Response &res) {
  19192. auto i = std::make_shared<size_t>(0);
  19193. res.set_chunked_content_provider(
  19194. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19195. if (*i == chunks.size()) {
  19196. sink.done();
  19197. } else {
  19198. sink.write(chunks[*i].data(), chunks[*i].size());
  19199. (*i)++;
  19200. }
  19201. return true;
  19202. });
  19203. });
  19204. auto msgs = collect("/split");
  19205. ASSERT_EQ(msgs.size(), 1u);
  19206. EXPECT_EQ(msgs[0].event, "update");
  19207. EXPECT_EQ(msgs[0].data, "hello");
  19208. }
  19209. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19210. // Only a BOM at the start of the stream is ignored
  19211. auto msgs = parse("\xEF\xBB\xBF"
  19212. "data: first\n\n"
  19213. "\xEF\xBB\xBF"
  19214. "data: second\n\n");
  19215. ASSERT_EQ(msgs.size(), 1u);
  19216. EXPECT_EQ(msgs[0].data, "first");
  19217. }
  19218. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19219. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19220. ASSERT_EQ(msgs.size(), 1u);
  19221. EXPECT_EQ(msgs[0].data, "hello");
  19222. EXPECT_EQ(msgs[0].event, "message");
  19223. }
  19224. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19225. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19226. ASSERT_EQ(msgs.size(), 2u);
  19227. EXPECT_EQ(msgs[0].data, "hello");
  19228. EXPECT_EQ(msgs[1].data, "hello");
  19229. }
  19230. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19231. // An event without data is not dispatched, and its type must not leak
  19232. // into the next event
  19233. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19234. ASSERT_EQ(msgs.size(), 1u);
  19235. EXPECT_EQ(msgs[0].event, "message");
  19236. EXPECT_EQ(msgs[0].data, "hello");
  19237. }
  19238. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19239. // The first connection sends only an id; the second echoes back the
  19240. // Last-Event-ID it was reconnected with
  19241. std::atomic<int> connection_count{0};
  19242. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19243. if (connection_count++ == 0) {
  19244. res.set_content("id: 42\n\n", "text/event-stream");
  19245. } else {
  19246. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19247. "\n\nevent: end\ndata: end\n\n",
  19248. "text/event-stream");
  19249. }
  19250. });
  19251. auto msgs = collect("/id-only");
  19252. ASSERT_EQ(msgs.size(), 1u);
  19253. EXPECT_EQ(msgs[0].data, "42");
  19254. }
  19255. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19256. // The first connection sets an id and then clears it with an empty one; the
  19257. // second reports whether it was reconnected with a Last-Event-ID
  19258. std::atomic<int> connection_count{0};
  19259. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19260. if (connection_count++ == 0) {
  19261. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19262. "text/event-stream");
  19263. } else {
  19264. res.set_content(
  19265. std::string("data: ") +
  19266. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19267. "\n\nevent: end\ndata: end\n\n",
  19268. "text/event-stream");
  19269. }
  19270. });
  19271. auto msgs = collect("/id-clear");
  19272. ASSERT_EQ(msgs.size(), 3u);
  19273. EXPECT_EQ(msgs[0].id, "1");
  19274. EXPECT_EQ(msgs[1].id, "");
  19275. EXPECT_EQ(msgs[2].data, "not sent");
  19276. }
  19277. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19278. // The first connection sets an id and then sends ids that cannot be carried
  19279. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19280. // with
  19281. std::atomic<int> connection_count{0};
  19282. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19283. if (connection_count++ == 0) {
  19284. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19285. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19286. "text/event-stream");
  19287. } else {
  19288. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19289. "\n\nevent: end\ndata: end\n\n",
  19290. "text/event-stream");
  19291. }
  19292. });
  19293. auto msgs = collect("/id-unsendable");
  19294. ASSERT_EQ(msgs.size(), 1u);
  19295. EXPECT_EQ(msgs[0].data, "42");
  19296. }
  19297. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19298. auto msgs = parse("event: notification\nid: evt-42\n"
  19299. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19300. ASSERT_EQ(msgs.size(), 1u);
  19301. EXPECT_EQ(msgs[0].event, "notification");
  19302. EXPECT_EQ(msgs[0].id, "evt-42");
  19303. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19304. }
  19305. TEST(SSEMessageTest, Clear) {
  19306. sse::SSEMessage msg;
  19307. msg.event = "custom";
  19308. msg.data = "some data";
  19309. msg.id = "123";
  19310. msg.clear();
  19311. EXPECT_EQ(msg.event, "message");
  19312. EXPECT_EQ(msg.data, "");
  19313. EXPECT_EQ(msg.id, "");
  19314. }
  19315. //==============================================================================
  19316. // SSE Integration Tests
  19317. //==============================================================================
  19318. // Test: Successful connection and on_open callback
  19319. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19320. // Add a simple endpoint that sends one event and closes
  19321. server_->Get("/simple-event", [](const Request &, Response &res) {
  19322. res.set_chunked_content_provider(
  19323. "text/event-stream", [](size_t offset, DataSink &sink) {
  19324. if (offset == 0) {
  19325. std::string event = "data: hello\n\n";
  19326. sink.write(event.data(), event.size());
  19327. }
  19328. return false; // Close stream after sending
  19329. });
  19330. });
  19331. Client client("localhost", get_port());
  19332. sse::SSEClient sse(client, "/simple-event");
  19333. std::atomic<bool> open_called{false};
  19334. std::atomic<bool> message_received{false};
  19335. sse.on_open([&open_called]() { open_called.store(true); });
  19336. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19337. if (msg.data == "hello") { message_received.store(true); }
  19338. });
  19339. sse.set_reconnect_interval(100);
  19340. sse.set_max_reconnect_attempts(1);
  19341. // Start async
  19342. sse.start_async();
  19343. // Wait for message to be processed
  19344. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19345. sse.stop();
  19346. EXPECT_TRUE(open_called.load());
  19347. EXPECT_TRUE(message_received.load());
  19348. }
  19349. // Test: on_message callback
  19350. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19351. // Endpoint that sends multiple events then closes
  19352. server_->Get("/multi-event", [](const Request &, Response &res) {
  19353. res.set_chunked_content_provider(
  19354. "text/event-stream", [](size_t offset, DataSink &sink) {
  19355. if (offset == 0) {
  19356. std::string events = "data: message1\n\ndata: message2\n\n";
  19357. sink.write(events.data(), events.size());
  19358. }
  19359. return false;
  19360. });
  19361. });
  19362. Client client("localhost", get_port());
  19363. sse::SSEClient sse(client, "/multi-event");
  19364. std::vector<std::string> received_messages;
  19365. std::mutex messages_mutex;
  19366. sse.on_message([&](const sse::SSEMessage &msg) {
  19367. std::lock_guard<std::mutex> lock(messages_mutex);
  19368. received_messages.push_back(msg.data);
  19369. });
  19370. sse.set_reconnect_interval(100);
  19371. sse.set_max_reconnect_attempts(1);
  19372. sse.start_async();
  19373. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19374. sse.stop();
  19375. std::lock_guard<std::mutex> lock(messages_mutex);
  19376. EXPECT_GE(received_messages.size(), 2u);
  19377. if (received_messages.size() >= 2) {
  19378. EXPECT_EQ(received_messages[0], "message1");
  19379. EXPECT_EQ(received_messages[1], "message2");
  19380. }
  19381. }
  19382. // Test: on_event for specific types
  19383. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19384. Client client("localhost", get_port());
  19385. sse::SSEClient sse(client, "/custom-events");
  19386. std::atomic<bool> update_received{false};
  19387. std::atomic<bool> delete_received{false};
  19388. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19389. if (msg.data == "updated") { update_received.store(true); }
  19390. });
  19391. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19392. if (msg.data == "deleted") { delete_received.store(true); }
  19393. });
  19394. sse.set_max_reconnect_attempts(1);
  19395. sse.start_async();
  19396. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19397. sse.stop();
  19398. EXPECT_TRUE(update_received.load());
  19399. EXPECT_TRUE(delete_received.load());
  19400. }
  19401. // Test: on_error callback on connection failure
  19402. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19403. // Connect to a non-existent port
  19404. Client client("localhost", 59999);
  19405. sse::SSEClient sse(client, "/events");
  19406. std::atomic<bool> error_called{false};
  19407. Error received_error = Error::Success;
  19408. sse.on_error([&](Error err) {
  19409. error_called.store(true);
  19410. received_error = err;
  19411. });
  19412. sse.set_reconnect_interval(50);
  19413. sse.set_max_reconnect_attempts(1);
  19414. sse.start_async();
  19415. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19416. sse.stop();
  19417. EXPECT_TRUE(error_called.load());
  19418. EXPECT_NE(received_error, Error::Success);
  19419. }
  19420. // Test: Last-Event-ID header sent on reconnect
  19421. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19422. // Endpoint that sends event with ID
  19423. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19424. res.set_chunked_content_provider(
  19425. "text/event-stream", [](size_t offset, DataSink &sink) {
  19426. if (offset == 0) {
  19427. std::string event = "id: evt-123\ndata: test\n\n";
  19428. sink.write(event.data(), event.size());
  19429. }
  19430. return false;
  19431. });
  19432. });
  19433. Client client("localhost", get_port());
  19434. sse::SSEClient sse(client, "/event-with-id");
  19435. std::atomic<bool> id_received{false};
  19436. sse.on_message([&](const sse::SSEMessage &msg) {
  19437. if (!msg.id.empty()) { id_received.store(true); }
  19438. });
  19439. sse.set_reconnect_interval(100);
  19440. sse.set_max_reconnect_attempts(1);
  19441. sse.start_async();
  19442. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19443. sse.stop();
  19444. EXPECT_TRUE(id_received.load());
  19445. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19446. }
  19447. // Test: Manual stop
  19448. TEST_F(SSEIntegrationTest, ManualStop) {
  19449. // Endpoint that sends one event and stays open briefly
  19450. std::atomic<bool> handler_running{true};
  19451. server_->Get("/stay-open", [&handler_running](const Request &,
  19452. Response &res) {
  19453. res.set_chunked_content_provider(
  19454. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19455. if (offset == 0) {
  19456. std::string event = "data: connected\n\n";
  19457. sink.write(event.data(), event.size());
  19458. }
  19459. // Keep connection open while handler_running is true
  19460. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19461. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19462. }
  19463. return false;
  19464. });
  19465. });
  19466. Client client("localhost", get_port());
  19467. sse::SSEClient sse(client, "/stay-open");
  19468. std::atomic<bool> connected{false};
  19469. sse.on_open([&connected]() { connected.store(true); });
  19470. sse.set_reconnect_interval(100);
  19471. sse.set_max_reconnect_attempts(1);
  19472. sse.start_async();
  19473. // Wait for connection to establish
  19474. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19475. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19476. }
  19477. EXPECT_TRUE(connected.load());
  19478. EXPECT_TRUE(sse.is_connected());
  19479. // Signal handler to stop
  19480. handler_running.store(false);
  19481. // Stop SSE client
  19482. sse.stop();
  19483. EXPECT_FALSE(sse.is_connected());
  19484. }
  19485. // Test: SSEClient with custom headers
  19486. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19487. // Setup a server endpoint that checks for custom header
  19488. std::atomic<bool> header_received{false};
  19489. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19490. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19491. header_received.store(true);
  19492. }
  19493. res.set_chunked_content_provider("text/event-stream",
  19494. [](size_t, DataSink &) { return false; });
  19495. });
  19496. Client client("localhost", get_port());
  19497. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19498. sse::SSEClient sse(client, "/header-check", headers);
  19499. sse.set_max_reconnect_attempts(1);
  19500. sse.start_async();
  19501. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19502. sse.stop();
  19503. EXPECT_TRUE(header_received.load());
  19504. }
  19505. // Test: Reconnect interval configuration
  19506. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19507. Client client("localhost", get_port());
  19508. sse::SSEClient sse(client, "/events");
  19509. auto &result = sse.set_reconnect_interval(500);
  19510. // Builder pattern should return reference to self
  19511. EXPECT_EQ(&result, &sse);
  19512. }
  19513. // Test: Max reconnect attempts
  19514. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19515. // Connect to non-existent port to force reconnects
  19516. Client client("localhost", 59998);
  19517. sse::SSEClient sse(client, "/events");
  19518. std::atomic<int> error_count{0};
  19519. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19520. sse.set_reconnect_interval(50);
  19521. sse.set_max_reconnect_attempts(2);
  19522. auto start = std::chrono::steady_clock::now();
  19523. sse.start(); // Blocking call
  19524. auto end = std::chrono::steady_clock::now();
  19525. // Should have stopped after 2 failed attempts
  19526. EXPECT_GE(error_count.load(), 2);
  19527. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19528. auto duration =
  19529. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19530. #ifdef _WIN32
  19531. // Windows is much slower for socket connection failures
  19532. EXPECT_LT(duration.count(), 7000);
  19533. #else
  19534. EXPECT_LT(duration.count(), 1000);
  19535. #endif
  19536. }
  19537. // Test: Multi-line data in integration
  19538. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19539. // Endpoint with multi-line data
  19540. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19541. res.set_chunked_content_provider(
  19542. "text/event-stream", [](size_t offset, DataSink &sink) {
  19543. if (offset == 0) {
  19544. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19545. sink.write(event.data(), event.size());
  19546. }
  19547. return false;
  19548. });
  19549. });
  19550. Client client("localhost", get_port());
  19551. sse::SSEClient sse(client, "/multiline-data");
  19552. std::string received_data;
  19553. std::mutex data_mutex;
  19554. sse.on_message([&](const sse::SSEMessage &msg) {
  19555. std::lock_guard<std::mutex> lock(data_mutex);
  19556. received_data = msg.data;
  19557. });
  19558. sse.set_reconnect_interval(100);
  19559. sse.set_max_reconnect_attempts(1);
  19560. sse.start_async();
  19561. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19562. sse.stop();
  19563. std::lock_guard<std::mutex> lock(data_mutex);
  19564. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19565. }
  19566. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19567. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19568. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19569. DataSink &sink) {
  19570. if (offset == 0) {
  19571. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19572. sink.write(events.data(), events.size());
  19573. }
  19574. return false;
  19575. });
  19576. });
  19577. Client client("localhost", get_port());
  19578. sse::SSEClient sse(client, "/empty-data-lines");
  19579. std::mutex mutex;
  19580. std::condition_variable cv;
  19581. std::vector<std::string> received;
  19582. sse.on_message([&](const sse::SSEMessage &msg) {
  19583. std::lock_guard<std::mutex> lock(mutex);
  19584. received.push_back(msg.data);
  19585. cv.notify_all();
  19586. });
  19587. sse.set_max_reconnect_attempts(1);
  19588. sse.start_async();
  19589. {
  19590. std::unique_lock<std::mutex> lock(mutex);
  19591. cv.wait_for(lock, std::chrono::seconds(2),
  19592. [&] { return received.size() >= 3; });
  19593. }
  19594. sse.stop();
  19595. ASSERT_GE(received.size(), 3u);
  19596. EXPECT_EQ(received[0], "");
  19597. EXPECT_EQ(received[1], "\nhello");
  19598. EXPECT_EQ(received[2], "");
  19599. }
  19600. // Test: Auto-reconnect after server disconnection
  19601. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19602. std::atomic<int> connection_count{0};
  19603. std::atomic<int> message_count{0};
  19604. // Endpoint that sends one event and closes, forcing reconnect
  19605. server_->Get("/reconnect-test",
  19606. [&connection_count](const Request &, Response &res) {
  19607. connection_count.fetch_add(1);
  19608. res.set_chunked_content_provider(
  19609. "text/event-stream", [](size_t offset, DataSink &sink) {
  19610. if (offset == 0) {
  19611. std::string event = "data: hello\n\n";
  19612. sink.write(event.data(), event.size());
  19613. }
  19614. return false; // Close connection after sending
  19615. });
  19616. });
  19617. Client client("localhost", get_port());
  19618. sse::SSEClient sse(client, "/reconnect-test");
  19619. sse.on_message([&message_count](const sse::SSEMessage &) {
  19620. message_count.fetch_add(1);
  19621. });
  19622. sse.set_reconnect_interval(100);
  19623. sse.set_max_reconnect_attempts(3);
  19624. sse.start_async();
  19625. // Wait long enough for multiple reconnects
  19626. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19627. sse.stop();
  19628. // Should have connected multiple times (initial + reconnects)
  19629. EXPECT_GE(connection_count.load(), 2);
  19630. // Should have received messages from multiple connections
  19631. EXPECT_GE(message_count.load(), 2);
  19632. }
  19633. // Test: A retry field that is not all ASCII digits is ignored
  19634. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19635. std::atomic<int> connection_count{0};
  19636. server_->Get("/bad-retry",
  19637. [&connection_count](const Request &, Response &res) {
  19638. connection_count.fetch_add(1);
  19639. res.set_chunked_content_provider(
  19640. "text/event-stream", [](size_t offset, DataSink &sink) {
  19641. if (offset == 0) {
  19642. std::string event = "retry: -1\ndata: hello\n\n";
  19643. sink.write(event.data(), event.size());
  19644. }
  19645. return false;
  19646. });
  19647. });
  19648. Client client("localhost", get_port());
  19649. sse::SSEClient sse(client, "/bad-retry");
  19650. sse.set_reconnect_interval(10000);
  19651. sse.start_async();
  19652. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19653. sse.stop();
  19654. EXPECT_EQ(connection_count.load(), 1);
  19655. }
  19656. // Test: A retry field of all ASCII digits sets the reconnection time
  19657. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19658. std::atomic<int> connection_count{0};
  19659. server_->Get("/zero-retry",
  19660. [&connection_count](const Request &, Response &res) {
  19661. connection_count.fetch_add(1);
  19662. res.set_chunked_content_provider(
  19663. "text/event-stream", [](size_t offset, DataSink &sink) {
  19664. if (offset == 0) {
  19665. std::string event = "retry: 0\ndata: hello\n\n";
  19666. sink.write(event.data(), event.size());
  19667. }
  19668. return false;
  19669. });
  19670. });
  19671. Client client("localhost", get_port());
  19672. sse::SSEClient sse(client, "/zero-retry");
  19673. sse.set_reconnect_interval(10000);
  19674. sse.start_async();
  19675. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19676. sse.stop();
  19677. // The server-supplied interval is applied, but never below 100ms, so
  19678. // "retry: 0" does not cause a busy reconnect loop
  19679. EXPECT_GE(connection_count.load(), 2);
  19680. EXPECT_LE(connection_count.load(), 10);
  19681. }
  19682. // Test: Last-Event-ID sent on reconnect
  19683. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19684. std::atomic<int> connection_count{0};
  19685. std::vector<std::string> received_last_event_ids;
  19686. std::mutex id_mutex;
  19687. // Endpoint that checks Last-Event-ID header and sends event with ID
  19688. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19689. int conn = connection_count.fetch_add(1);
  19690. // Capture the Last-Event-ID header from each connection
  19691. {
  19692. std::lock_guard<std::mutex> lock(id_mutex);
  19693. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19694. }
  19695. res.set_chunked_content_provider(
  19696. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19697. if (offset == 0) {
  19698. std::string event =
  19699. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19700. sink.write(event.data(), event.size());
  19701. }
  19702. return false;
  19703. });
  19704. });
  19705. Client client("localhost", get_port());
  19706. sse::SSEClient sse(client, "/reconnect-with-id");
  19707. sse.set_reconnect_interval(100);
  19708. sse.set_max_reconnect_attempts(3);
  19709. sse.start_async();
  19710. // Wait for at least 2 connections
  19711. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19712. sse.stop();
  19713. // Verify behavior
  19714. std::lock_guard<std::mutex> lock(id_mutex);
  19715. EXPECT_GE(received_last_event_ids.size(), 2u);
  19716. // First connection should have no Last-Event-ID
  19717. if (!received_last_event_ids.empty()) {
  19718. EXPECT_EQ(received_last_event_ids[0], "");
  19719. }
  19720. // Second connection should have Last-Event-ID from first connection
  19721. if (received_last_event_ids.size() >= 2) {
  19722. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19723. }
  19724. }
  19725. // Test: set_headers updates headers used on reconnect
  19726. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19727. std::vector<std::string> received_tokens;
  19728. std::mutex token_mutex;
  19729. // Endpoint that captures Authorization header
  19730. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19731. {
  19732. std::lock_guard<std::mutex> lock(token_mutex);
  19733. received_tokens.push_back(req.get_header_value("Authorization"));
  19734. }
  19735. res.set_chunked_content_provider(
  19736. "text/event-stream", [](size_t offset, DataSink &sink) {
  19737. if (offset == 0) {
  19738. std::string event = "data: hello\n\n";
  19739. sink.write(event.data(), event.size());
  19740. }
  19741. return false; // Close connection to trigger reconnect
  19742. });
  19743. });
  19744. Client client("localhost", get_port());
  19745. Headers headers = {{"Authorization", "Bearer old-token"}};
  19746. sse::SSEClient sse(client, "/auth-check", headers);
  19747. // Update headers on each successful connection
  19748. sse.on_open(
  19749. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19750. sse.set_reconnect_interval(100);
  19751. sse.set_max_reconnect_attempts(3);
  19752. sse.start_async();
  19753. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19754. sse.stop();
  19755. std::lock_guard<std::mutex> lock(token_mutex);
  19756. ASSERT_GE(received_tokens.size(), 2u);
  19757. // First connection uses original header
  19758. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19759. // Second connection uses updated header from set_headers
  19760. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19761. }
  19762. // Test: 401 allows reconnection (so on_error can refresh headers)
  19763. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19764. std::atomic<int> connection_count{0};
  19765. // Endpoint: returns 401 on first attempt, 200 on second
  19766. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19767. int conn = connection_count.fetch_add(1);
  19768. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19769. res.status = StatusCode::Unauthorized_401;
  19770. res.set_content("Unauthorized", "text/plain");
  19771. return;
  19772. }
  19773. res.set_chunked_content_provider(
  19774. "text/event-stream", [](size_t offset, DataSink &sink) {
  19775. if (offset == 0) {
  19776. std::string event = "data: authenticated\n\n";
  19777. sink.write(event.data(), event.size());
  19778. }
  19779. return false;
  19780. });
  19781. });
  19782. Client client("localhost", get_port());
  19783. Headers headers = {{"Authorization", "Bearer expired"}};
  19784. sse::SSEClient sse(client, "/auth-retry", headers);
  19785. std::atomic<bool> message_received{false};
  19786. // Refresh token on error
  19787. sse.on_error(
  19788. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19789. sse.on_message([&](const sse::SSEMessage &msg) {
  19790. if (msg.data == "authenticated") { message_received.store(true); }
  19791. });
  19792. sse.set_reconnect_interval(100);
  19793. sse.set_max_reconnect_attempts(3);
  19794. sse.start_async();
  19795. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19796. sse.stop();
  19797. // Should have reconnected after 401 and succeeded with new token
  19798. EXPECT_GE(connection_count.load(), 2);
  19799. EXPECT_TRUE(message_received.load());
  19800. }
  19801. TEST(Issue2318Test, EmptyHostString) {
  19802. {
  19803. httplib::Client cli_empty("", PORT);
  19804. auto res = cli_empty.Get("/");
  19805. ASSERT_FALSE(res);
  19806. EXPECT_EQ(httplib::Error::Connection, res.error());
  19807. }
  19808. {
  19809. httplib::Client cli(" ", PORT);
  19810. auto res = cli.Get("/");
  19811. ASSERT_FALSE(res);
  19812. EXPECT_EQ(httplib::Error::Connection, res.error());
  19813. }
  19814. }
  19815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19816. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19817. Server svr;
  19818. // Set a small payload limit (1KB)
  19819. svr.set_payload_max_length(1024);
  19820. svr.Post("/test", [&](const Request &req, Response &res) {
  19821. res.set_content("Body size: " + std::to_string(req.body.size()),
  19822. "text/plain");
  19823. });
  19824. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19825. auto se = detail::scope_exit([&] {
  19826. svr.stop();
  19827. listen_thread.join();
  19828. });
  19829. svr.wait_until_ready();
  19830. // Create data that compresses well but exceeds limit when decompressed
  19831. // 8KB of repeated null bytes compresses to a very small size
  19832. std::string original_data(8 * 1024, '\0');
  19833. // Compress the data using gzip
  19834. std::string compressed_data;
  19835. detail::gzip_compressor compressor;
  19836. compressor.compress(original_data.data(), original_data.size(), true,
  19837. [&](const char *data, size_t size) {
  19838. compressed_data.append(data, size);
  19839. return true;
  19840. });
  19841. // Verify compression worked (compressed should be much smaller)
  19842. ASSERT_LT(compressed_data.size(), original_data.size());
  19843. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19844. // Send compressed data with Content-Encoding: gzip
  19845. Client cli(HOST, PORT);
  19846. Headers headers = {{"Content-Encoding", "gzip"}};
  19847. auto res =
  19848. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19849. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19851. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19852. }
  19853. #endif
  19854. // ============================================================================
  19855. // OpenSSL-Specific Tests
  19856. // ============================================================================
  19857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19858. X509 *readCertificate(const std::string &strFileName) {
  19859. std::ifstream inStream(strFileName);
  19860. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19861. std::istreambuf_iterator<char>());
  19862. if (strCertPEM.empty()) return (nullptr);
  19863. BIO *pbCert = BIO_new(BIO_s_mem());
  19864. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19865. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19866. BIO_free(pbCert);
  19867. return (pCert);
  19868. }
  19869. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19870. std::ifstream inStream(strFileName);
  19871. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19872. std::istreambuf_iterator<char>());
  19873. if (strPrivateKeyPEM.empty()) return (nullptr);
  19874. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19875. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19876. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19877. BIO_free(pbPrivKey);
  19878. return (pPrivateKey);
  19879. }
  19880. TEST(BindServerTest, UpdateCerts) {
  19881. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19882. int port = svr.bind_to_any_port("0.0.0.0");
  19883. ASSERT_TRUE(svr.is_valid());
  19884. ASSERT_TRUE(port > 0);
  19885. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19886. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19887. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19888. ASSERT_TRUE(cert != nullptr);
  19889. ASSERT_TRUE(ca_cert != nullptr);
  19890. ASSERT_TRUE(key != nullptr);
  19891. X509_STORE *cert_store = X509_STORE_new();
  19892. X509_STORE_add_cert(cert_store, ca_cert);
  19893. // svr.update_certs(cert, key, cert_store); // deprecated
  19894. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19895. CLIENT_CA_CERT_FILE);
  19896. ASSERT_TRUE(svr.is_valid());
  19897. svr.stop();
  19898. X509_STORE_free(cert_store);
  19899. X509_free(cert);
  19900. X509_free(ca_cert);
  19901. EVP_PKEY_free(key);
  19902. }
  19903. // Test that update_certs() updates client CA list correctly
  19904. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19905. // Start with file-based constructor
  19906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19907. ASSERT_TRUE(svr.is_valid());
  19908. // Initially no client CA list should be set
  19909. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19910. ASSERT_TRUE(ssl_ctx != nullptr);
  19911. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19912. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19913. EXPECT_EQ(0, count_before);
  19914. // Now update with client CA (PEM string)
  19915. std::string cert_pem, key_pem, ca_pem;
  19916. read_file(SERVER_CERT_FILE, cert_pem);
  19917. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19918. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19919. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19920. ASSERT_TRUE(svr.is_valid());
  19921. // Now client CA list should be set
  19922. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19923. ASSERT_TRUE(ca_list_after != nullptr);
  19924. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19925. }
  19926. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19927. // Test that the file-path SSLServer constructor properly sets the client CA
  19928. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19930. ASSERT_TRUE(svr.is_valid());
  19931. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19932. ASSERT_TRUE(ssl_ctx != nullptr);
  19933. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19934. ASSERT_TRUE(ca_list != nullptr);
  19935. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19936. }
  19937. #endif
  19938. // ============================================================================
  19939. // MbedTLS-Specific Tests
  19940. // ============================================================================
  19941. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19942. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19943. using namespace httplib::tls;
  19944. // Track if callback was invoked
  19945. bool callback_invoked = false;
  19946. // The callback receives void* ctx which is actually MbedTlsContext*
  19947. // We can access the mbedtls_ssl_config via the context
  19948. auto setup_callback = [&callback_invoked](void *ctx) {
  19949. callback_invoked = true;
  19950. // Cast to MbedTlsContext* to access the ssl config
  19951. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19952. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19953. // Use static variables to hold certificate data (simplified for test)
  19954. static mbedtls_x509_crt own_cert;
  19955. static mbedtls_pk_context own_key;
  19956. static mbedtls_x509_crt ca_chain;
  19957. static bool initialized = false;
  19958. if (!initialized) {
  19959. mbedtls_x509_crt_init(&own_cert);
  19960. mbedtls_pk_init(&own_key);
  19961. mbedtls_x509_crt_init(&ca_chain);
  19962. // Load server certificate
  19963. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19964. return false;
  19965. }
  19966. // Load server private key.
  19967. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19968. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19969. #if MBEDTLS_VERSION_MAJOR == 3
  19970. ,
  19971. mbedtls_ctr_drbg_random, nullptr
  19972. #endif
  19973. ) != 0) {
  19974. return false;
  19975. }
  19976. // Load CA chain for client verification
  19977. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19978. return false;
  19979. }
  19980. initialized = true;
  19981. }
  19982. // Configure the SSL config
  19983. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19984. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19985. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19986. // Set minimum TLS version using mbedTLS native API
  19987. #if MBEDTLS_VERSION_MAJOR >= 3
  19988. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19989. #else
  19990. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19991. MBEDTLS_SSL_MINOR_VERSION_3);
  19992. #endif
  19993. return true;
  19994. };
  19995. SSLServer svr(setup_callback);
  19996. ASSERT_TRUE(svr.is_valid());
  19997. ASSERT_TRUE(callback_invoked);
  19998. svr.Get("/test", [&](const Request &req, Response &res) {
  19999. res.set_content("test", "text/plain");
  20000. auto cert = req.peer_cert();
  20001. ASSERT_TRUE(static_cast<bool>(cert));
  20002. auto common_name = cert.subject_cn();
  20003. EXPECT_EQ("Common Name", common_name);
  20004. });
  20005. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20006. auto se = detail::scope_exit([&] {
  20007. svr.stop();
  20008. t.join();
  20009. ASSERT_FALSE(svr.is_running());
  20010. });
  20011. svr.wait_until_ready();
  20012. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20013. cli.enable_server_certificate_verification(false);
  20014. cli.set_connection_timeout(30);
  20015. auto res = cli.Get("/test");
  20016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20017. ASSERT_EQ(StatusCode::OK_200, res->status);
  20018. }
  20019. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20020. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20021. // keep-alive SSL session, which reads through that config in
  20022. // mbedtls_ssl_close_notify.
  20023. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20025. ASSERT_TRUE(svr.is_valid());
  20026. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20027. res.set_content("test", "text/plain");
  20028. });
  20029. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20030. auto se = detail::scope_exit([&] {
  20031. svr.stop();
  20032. t.join();
  20033. ASSERT_FALSE(svr.is_running());
  20034. });
  20035. svr.wait_until_ready();
  20036. {
  20037. SSLClient cli(HOST, PORT);
  20038. cli.enable_server_certificate_verification(false);
  20039. cli.set_keep_alive(true);
  20040. auto res = cli.Get("/test");
  20041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20042. ASSERT_EQ(StatusCode::OK_200, res->status);
  20043. // cli is destructed here with the keep-alive SSL session still open.
  20044. }
  20045. }
  20046. #endif
  20047. // WebSocket Tests
  20048. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20049. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20050. // defining the meaning of these bits has been negotiated.
  20051. auto make_frame = [](uint8_t first_byte) {
  20052. std::string frame;
  20053. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20054. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20055. frame += "Hello";
  20056. return frame;
  20057. };
  20058. // RSV1 set (0x40)
  20059. {
  20060. detail::BufferStream strm;
  20061. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20062. ws::Opcode opcode;
  20063. std::string payload;
  20064. bool fin;
  20065. EXPECT_EQ(
  20066. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20067. ws::impl::FrameRead::Fail);
  20068. }
  20069. // RSV2 set (0x20)
  20070. {
  20071. detail::BufferStream strm;
  20072. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20073. ws::Opcode opcode;
  20074. std::string payload;
  20075. bool fin;
  20076. EXPECT_EQ(
  20077. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20078. ws::impl::FrameRead::Fail);
  20079. }
  20080. // RSV3 set (0x10)
  20081. {
  20082. detail::BufferStream strm;
  20083. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20084. ws::Opcode opcode;
  20085. std::string payload;
  20086. bool fin;
  20087. EXPECT_EQ(
  20088. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20089. ws::impl::FrameRead::Fail);
  20090. }
  20091. // No RSV bits set - should succeed
  20092. {
  20093. detail::BufferStream strm;
  20094. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20095. ws::Opcode opcode;
  20096. std::string payload;
  20097. bool fin;
  20098. EXPECT_EQ(
  20099. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20100. ws::impl::FrameRead::Ok);
  20101. EXPECT_EQ(ws::Opcode::Text, opcode);
  20102. EXPECT_EQ("Hello", payload);
  20103. EXPECT_TRUE(fin);
  20104. }
  20105. }
  20106. TEST(WebSocketTest, ControlFrameValidation) {
  20107. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20108. // payload length <= 125.
  20109. // Ping with FIN=0 - must be rejected
  20110. {
  20111. detail::BufferStream strm;
  20112. std::string frame;
  20113. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20114. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20115. strm.write(frame.data(), frame.size());
  20116. ws::Opcode opcode;
  20117. std::string payload;
  20118. bool fin;
  20119. EXPECT_EQ(
  20120. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20121. ws::impl::FrameRead::Fail);
  20122. }
  20123. // Close with FIN=0 - must be rejected
  20124. {
  20125. detail::BufferStream strm;
  20126. std::string frame;
  20127. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20128. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20129. strm.write(frame.data(), frame.size());
  20130. ws::Opcode opcode;
  20131. std::string payload;
  20132. bool fin;
  20133. EXPECT_EQ(
  20134. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20135. ws::impl::FrameRead::Fail);
  20136. }
  20137. // Ping with payload_len=126 (extended length) - must be rejected
  20138. {
  20139. detail::BufferStream strm;
  20140. std::string frame;
  20141. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20142. frame += static_cast<char>(126); // payload_len=126 (>125)
  20143. frame += static_cast<char>(0x00); // extended length high byte
  20144. frame += static_cast<char>(126); // extended length low byte
  20145. frame += std::string(126, 'x');
  20146. strm.write(frame.data(), frame.size());
  20147. ws::Opcode opcode;
  20148. std::string payload;
  20149. bool fin;
  20150. EXPECT_EQ(
  20151. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20152. ws::impl::FrameRead::Fail);
  20153. }
  20154. // Ping with FIN=1 and payload_len=125 - should succeed
  20155. {
  20156. detail::BufferStream strm;
  20157. std::string frame;
  20158. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20159. frame += static_cast<char>(125); // payload_len=125
  20160. frame += std::string(125, 'x');
  20161. strm.write(frame.data(), frame.size());
  20162. ws::Opcode opcode;
  20163. std::string payload;
  20164. bool fin;
  20165. EXPECT_EQ(
  20166. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20167. ws::impl::FrameRead::Ok);
  20168. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20169. EXPECT_EQ(125u, payload.size());
  20170. EXPECT_TRUE(fin);
  20171. }
  20172. }
  20173. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20174. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20175. // length MUST be 0.
  20176. // MSB set - must be rejected
  20177. {
  20178. detail::BufferStream strm;
  20179. std::string frame;
  20180. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20181. frame += static_cast<char>(127); // 64-bit extended length
  20182. frame += static_cast<char>(0x80); // MSB set (invalid)
  20183. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20184. strm.write(frame.data(), frame.size());
  20185. ws::Opcode opcode;
  20186. std::string payload;
  20187. bool fin;
  20188. EXPECT_EQ(
  20189. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20190. ws::impl::FrameRead::Fail);
  20191. }
  20192. // MSB clear - should pass length parsing (will be rejected by max_len,
  20193. // but that's a different check; use a small length to verify)
  20194. {
  20195. detail::BufferStream strm;
  20196. std::string frame;
  20197. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20198. frame += static_cast<char>(127); // 64-bit extended length
  20199. frame += std::string(7, '\0'); // high bytes = 0
  20200. frame += static_cast<char>(0x03); // length = 3
  20201. frame += "abc";
  20202. strm.write(frame.data(), frame.size());
  20203. ws::Opcode opcode;
  20204. std::string payload;
  20205. bool fin;
  20206. EXPECT_EQ(
  20207. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20208. ws::impl::FrameRead::Ok);
  20209. EXPECT_EQ(ws::Opcode::Text, opcode);
  20210. EXPECT_EQ("abc", payload);
  20211. }
  20212. }
  20213. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20214. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20215. // Valid UTF-8
  20216. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20217. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20218. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20219. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20220. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20221. // Invalid UTF-8
  20222. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20223. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20224. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20225. EXPECT_FALSE(
  20226. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20227. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20228. }
  20229. TEST(WebSocketTest, ConnectAndDisconnect) {
  20230. Server svr;
  20231. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20232. std::string msg;
  20233. while (ws.read(msg)) {}
  20234. });
  20235. auto port = svr.bind_to_any_port(HOST);
  20236. std::thread t([&]() { svr.listen_after_bind(); });
  20237. svr.wait_until_ready();
  20238. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20239. auto res = client.connect();
  20240. ASSERT_TRUE(res);
  20241. EXPECT_EQ(Error::Success, res.error());
  20242. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20243. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20244. EXPECT_TRUE(client.is_open());
  20245. client.close();
  20246. EXPECT_FALSE(client.is_open());
  20247. svr.stop();
  20248. t.join();
  20249. }
  20250. TEST(WebSocketTest, ValidURL) {
  20251. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20252. EXPECT_TRUE(ws1.is_valid());
  20253. ws::WebSocketClient ws2("ws://example.com/path");
  20254. EXPECT_TRUE(ws2.is_valid());
  20255. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20256. EXPECT_TRUE(ws3.is_valid());
  20257. #ifdef CPPHTTPLIB_SSL_ENABLED
  20258. ws::WebSocketClient wss1("wss://example.com/path");
  20259. EXPECT_TRUE(wss1.is_valid());
  20260. ws::WebSocketClient wss2("wss://example.com:443/path");
  20261. EXPECT_TRUE(wss2.is_valid());
  20262. #endif
  20263. }
  20264. TEST(WebSocketTest, InvalidURL) {
  20265. // No scheme
  20266. ws::WebSocketClient ws1("localhost:8080/path");
  20267. EXPECT_FALSE(ws1.is_valid());
  20268. // No path
  20269. ws::WebSocketClient ws2("ws://localhost:8080");
  20270. EXPECT_FALSE(ws2.is_valid());
  20271. // Empty string
  20272. ws::WebSocketClient ws3("");
  20273. EXPECT_FALSE(ws3.is_valid());
  20274. // Missing host
  20275. ws::WebSocketClient ws4("ws://:8080/path");
  20276. EXPECT_FALSE(ws4.is_valid());
  20277. // Port number overflow — should not crash
  20278. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20279. EXPECT_FALSE(ws5.is_valid());
  20280. // Port out of range
  20281. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20282. EXPECT_FALSE(ws6.is_valid());
  20283. }
  20284. TEST(WebSocketTest, UnsupportedScheme) {
  20285. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20286. ws::WebSocketClient ws1("http://localhost:8080/path");
  20287. EXPECT_FALSE(ws1.is_valid());
  20288. ws::WebSocketClient ws2("https://localhost:8080/path");
  20289. EXPECT_FALSE(ws2.is_valid());
  20290. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20291. EXPECT_FALSE(ws3.is_valid());
  20292. #else
  20293. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20294. std::invalid_argument);
  20295. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20296. std::invalid_argument);
  20297. #endif
  20298. }
  20299. TEST(WebSocketTest, ConnectWhenInvalid) {
  20300. ws::WebSocketClient ws("not a valid url");
  20301. EXPECT_FALSE(ws.is_valid());
  20302. auto res = ws.connect();
  20303. EXPECT_FALSE(res);
  20304. EXPECT_EQ(Error::Connection, res.error());
  20305. EXPECT_EQ(-1, res.status());
  20306. }
  20307. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20308. // Grab a port that is free, then close it again so nothing listens there
  20309. Server svr;
  20310. auto port = svr.bind_to_any_port(HOST);
  20311. svr.stop();
  20312. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20313. auto res = client.connect();
  20314. ASSERT_FALSE(res);
  20315. EXPECT_EQ(Error::Connection, res.error());
  20316. EXPECT_EQ(-1, res.status());
  20317. }
  20318. TEST(WebSocketTest, DefaultPort) {
  20319. ws::WebSocketClient ws1("ws://example.com/path");
  20320. EXPECT_TRUE(ws1.is_valid());
  20321. // ws:// defaults to port 80 (verified by successful parse)
  20322. #ifdef CPPHTTPLIB_SSL_ENABLED
  20323. ws::WebSocketClient ws2("wss://example.com/path");
  20324. EXPECT_TRUE(ws2.is_valid());
  20325. // wss:// defaults to port 443 (verified by successful parse)
  20326. #endif
  20327. }
  20328. TEST(WebSocketTest, IPv6LiteralAddress) {
  20329. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20330. EXPECT_TRUE(ws1.is_valid());
  20331. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20332. EXPECT_TRUE(ws2.is_valid());
  20333. }
  20334. TEST(WebSocketTest, ComplexPath) {
  20335. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20336. EXPECT_TRUE(ws1.is_valid());
  20337. ws::WebSocketClient ws2("ws://localhost:8080/");
  20338. EXPECT_TRUE(ws2.is_valid());
  20339. }
  20340. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20341. Server svr;
  20342. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20343. std::string msg;
  20344. while (ws.read(msg)) {}
  20345. });
  20346. auto port = svr.bind_to_any_port(HOST);
  20347. std::thread t([&]() { svr.listen_after_bind(); });
  20348. svr.wait_until_ready();
  20349. auto another_host = "example.com";
  20350. auto wrong_ip = "192.0.2.1";
  20351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20352. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20353. ASSERT_TRUE(client.connect());
  20354. EXPECT_TRUE(client.is_open());
  20355. client.close();
  20356. svr.stop();
  20357. t.join();
  20358. }
  20359. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20360. Server svr;
  20361. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20362. std::string msg;
  20363. while (ws.read(msg)) {}
  20364. });
  20365. auto port = svr.bind_to_any_port(HOST);
  20366. std::thread t([&]() { svr.listen_after_bind(); });
  20367. svr.wait_until_ready();
  20368. auto wrong_ip = "192.0.2.1";
  20369. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20370. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20371. client.set_connection_timeout(1);
  20372. client.set_read_timeout(1);
  20373. client.set_write_timeout(1);
  20374. EXPECT_FALSE(client.connect());
  20375. EXPECT_FALSE(client.is_open());
  20376. svr.stop();
  20377. t.join();
  20378. }
  20379. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20380. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20381. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20382. // (RFC 6761) is only a map key and the Host header value.
  20383. auto host = "target.invalid";
  20384. Server svr;
  20385. std::string received_host;
  20386. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20387. received_host = req.get_header_value("Host");
  20388. std::string msg;
  20389. while (ws.read(msg)) {}
  20390. });
  20391. auto port = svr.bind_to_any_port(HOST);
  20392. std::thread t([&]() { svr.listen_after_bind(); });
  20393. // ASSERT_* below returns from the test body, which would leave t joinable
  20394. // and make ~thread call std::terminate.
  20395. auto se = detail::scope_exit([&] {
  20396. svr.stop();
  20397. if (t.joinable()) { t.join(); }
  20398. });
  20399. svr.wait_until_ready();
  20400. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20401. std::to_string(port) + "/ws");
  20402. client.set_hostname_addr_map({{host, HOST}});
  20403. ASSERT_TRUE(client.connect());
  20404. EXPECT_TRUE(client.is_open());
  20405. client.close();
  20406. svr.stop();
  20407. t.join();
  20408. // The mapping only redirects the connection; the identity stays host_.
  20409. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20410. }
  20411. class WebSocketIntegrationTest : public ::testing::Test {
  20412. protected:
  20413. void SetUp() override {
  20414. server_ = httplib::detail::make_unique<Server>();
  20415. setup_server();
  20416. start_server();
  20417. }
  20418. void TearDown() override {
  20419. server_->stop();
  20420. if (server_thread_.joinable()) { server_thread_.join(); }
  20421. }
  20422. void setup_server() {
  20423. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20424. std::string msg;
  20425. ws::ReadResult ret;
  20426. while ((ret = ws.read(msg))) {
  20427. if (ret == ws::Binary) {
  20428. ws.send(msg.data(), msg.size());
  20429. } else {
  20430. ws.send(msg);
  20431. }
  20432. }
  20433. });
  20434. server_->WebSocket("/ws-echo-string",
  20435. [](const Request &, ws::WebSocket &ws) {
  20436. std::string msg;
  20437. while (ws.read(msg)) {
  20438. ws.send("echo: " + msg);
  20439. }
  20440. });
  20441. server_->WebSocket(
  20442. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20443. // Echo back request metadata
  20444. ws.send("path:" + req.path);
  20445. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20446. std::string msg;
  20447. while (ws.read(msg)) {}
  20448. });
  20449. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20450. std::string msg;
  20451. ws.read(msg); // wait for a message
  20452. ws.close();
  20453. });
  20454. server_->WebSocket("/ws-close-status",
  20455. [](const Request &, ws::WebSocket &ws) {
  20456. std::string msg;
  20457. ws.read(msg); // wait for a message
  20458. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20459. });
  20460. server_->WebSocket(
  20461. "/ws-subprotocol",
  20462. [](const Request &, ws::WebSocket &ws) {
  20463. std::string msg;
  20464. while (ws.read(msg)) {
  20465. ws.send(msg);
  20466. }
  20467. },
  20468. [](const std::vector<std::string> &protocols) -> std::string {
  20469. for (const auto &p : protocols) {
  20470. if (p == "graphql-ws") { return p; }
  20471. }
  20472. return "";
  20473. });
  20474. server_->WebSocket(
  20475. "/ws-subprotocol-unoffered",
  20476. [](const Request &, ws::WebSocket &ws) {
  20477. std::string msg;
  20478. while (ws.read(msg)) {
  20479. ws.send(msg);
  20480. }
  20481. },
  20482. [](const std::vector<std::string> &) -> std::string {
  20483. return "admin";
  20484. });
  20485. }
  20486. void start_server() {
  20487. port_ = server_->bind_to_any_port(HOST);
  20488. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20489. server_->wait_until_ready();
  20490. }
  20491. std::unique_ptr<Server> server_;
  20492. std::thread server_thread_;
  20493. int port_ = 0;
  20494. };
  20495. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20496. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20497. "/ws-echo");
  20498. ASSERT_TRUE(client.connect());
  20499. ASSERT_TRUE(client.is_open());
  20500. ASSERT_TRUE(client.send("Hello WebSocket"));
  20501. std::string msg;
  20502. EXPECT_EQ(ws::Text, client.read(msg));
  20503. EXPECT_EQ("Hello WebSocket", msg);
  20504. client.close();
  20505. }
  20506. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20507. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20508. "/ws-echo");
  20509. ASSERT_TRUE(client.connect());
  20510. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20511. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20512. std::string msg;
  20513. EXPECT_EQ(ws::Binary, client.read(msg));
  20514. EXPECT_EQ(binary_data, msg);
  20515. client.close();
  20516. }
  20517. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20518. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20519. "/ws-echo");
  20520. ASSERT_TRUE(client.connect());
  20521. for (int i = 0; i < 10; i++) {
  20522. auto text = "message " + std::to_string(i);
  20523. ASSERT_TRUE(client.send(text));
  20524. std::string msg;
  20525. ASSERT_TRUE(client.read(msg));
  20526. EXPECT_EQ(text, msg);
  20527. }
  20528. client.close();
  20529. }
  20530. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20531. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20532. "/ws-close");
  20533. ASSERT_TRUE(client.connect());
  20534. // Send a message to trigger the server to close
  20535. ASSERT_TRUE(client.send("trigger close"));
  20536. // The server will close, so read should return false
  20537. std::string msg;
  20538. EXPECT_FALSE(client.read(msg));
  20539. EXPECT_FALSE(client.is_open());
  20540. }
  20541. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20542. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20543. "/ws-echo");
  20544. ASSERT_TRUE(client.connect());
  20545. // 128KB message
  20546. std::string large_data(128 * 1024, 'X');
  20547. ASSERT_TRUE(client.send(large_data));
  20548. std::string msg;
  20549. ASSERT_TRUE(client.read(msg));
  20550. EXPECT_EQ(large_data, msg);
  20551. client.close();
  20552. }
  20553. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20554. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20555. "/ws-echo");
  20556. ASSERT_TRUE(client.connect());
  20557. const int num_threads = 4;
  20558. std::vector<std::thread> threads;
  20559. std::atomic<int> send_count{0};
  20560. for (int t = 0; t < num_threads; t++) {
  20561. threads.emplace_back([&client, &send_count, t]() {
  20562. for (int i = 0; i < 5; i++) {
  20563. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20564. if (client.send(text)) { send_count++; }
  20565. }
  20566. });
  20567. }
  20568. for (auto &th : threads) {
  20569. th.join();
  20570. }
  20571. int received = 0;
  20572. std::string msg;
  20573. while (received < send_count.load()) {
  20574. if (!client.read(msg)) { break; }
  20575. received++;
  20576. }
  20577. EXPECT_EQ(send_count.load(), received);
  20578. client.close();
  20579. }
  20580. TEST_F(WebSocketIntegrationTest, ReadString) {
  20581. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20582. "/ws-echo-string");
  20583. ASSERT_TRUE(client.connect());
  20584. ASSERT_TRUE(client.send("hello"));
  20585. std::string msg;
  20586. ASSERT_TRUE(client.read(msg));
  20587. EXPECT_EQ("echo: hello", msg);
  20588. ASSERT_TRUE(client.send("world"));
  20589. ASSERT_TRUE(client.read(msg));
  20590. EXPECT_EQ("echo: world", msg);
  20591. client.close();
  20592. }
  20593. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20594. Headers headers = {{"X-Test-Header", "test-value"}};
  20595. ws::WebSocketClient client(
  20596. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20597. ASSERT_TRUE(client.connect());
  20598. std::string msg;
  20599. ASSERT_TRUE(client.read(msg));
  20600. EXPECT_EQ("path:/ws-request-info", msg);
  20601. ASSERT_TRUE(client.read(msg));
  20602. EXPECT_EQ("header:test-value", msg);
  20603. client.close();
  20604. }
  20605. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20606. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20607. "/ws-echo");
  20608. client.set_read_timeout(1, 0); // 1 second
  20609. ASSERT_TRUE(client.connect());
  20610. // Don't send anything — server echo handler waits for a message, so read()
  20611. // should time out. The connection survives it: nothing was consumed.
  20612. std::string msg;
  20613. EXPECT_EQ(client.read(msg), ws::Timeout);
  20614. EXPECT_TRUE(client.is_open());
  20615. // And it is still usable afterwards.
  20616. EXPECT_TRUE(client.send("after timeout"));
  20617. EXPECT_EQ(client.read(msg), ws::Text);
  20618. EXPECT_EQ(msg, "after timeout");
  20619. }
  20620. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20621. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20622. "/ws-echo");
  20623. client.set_read_timeout(1, 0);
  20624. ASSERT_TRUE(client.connect());
  20625. ASSERT_TRUE(client.send("first"));
  20626. std::string msg;
  20627. ASSERT_EQ(client.read(msg), ws::Text);
  20628. ASSERT_EQ(msg, "first");
  20629. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20630. // not be used with a read timeout: it would reprocess the previous message.
  20631. EXPECT_EQ(client.read(msg), ws::Timeout);
  20632. EXPECT_EQ(msg, "first");
  20633. }
  20634. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20635. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20636. "/ws-echo");
  20637. ASSERT_TRUE(client.connect());
  20638. // Setting it once the connection is open reaches the live stream, not just
  20639. // the seed for the next connect().
  20640. client.set_read_timeout(1, 0);
  20641. std::string msg;
  20642. EXPECT_EQ(client.read(msg), ws::Timeout);
  20643. EXPECT_TRUE(client.is_open());
  20644. }
  20645. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20646. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20647. "/ws-echo");
  20648. client.set_read_timeout(5, 0);
  20649. ASSERT_TRUE(client.connect());
  20650. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20651. // The server should reject it and close the connection.
  20652. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20653. client.send(oversized);
  20654. // The server's read() should have failed due to payload limit,
  20655. // so our read() should return false (connection closed).
  20656. std::string msg;
  20657. EXPECT_FALSE(client.read(msg));
  20658. }
  20659. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20660. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20661. "/ws-echo");
  20662. client.set_read_timeout(10, 0);
  20663. ASSERT_TRUE(client.connect());
  20664. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20665. // This should succeed.
  20666. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20667. ASSERT_TRUE(client.send(at_limit));
  20668. std::string msg;
  20669. ASSERT_TRUE(client.read(msg));
  20670. EXPECT_EQ(at_limit.size(), msg.size());
  20671. client.close();
  20672. }
  20673. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20675. "/nonexistent");
  20676. auto res = client.connect();
  20677. EXPECT_FALSE(res);
  20678. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20679. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20680. EXPECT_FALSE(client.is_open());
  20681. }
  20682. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20683. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20684. "/ws-echo");
  20685. ASSERT_TRUE(client.connect());
  20686. ASSERT_TRUE(client.send(""));
  20687. std::string msg;
  20688. EXPECT_EQ(ws::Text, client.read(msg));
  20689. EXPECT_EQ("", msg);
  20690. client.close();
  20691. }
  20692. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20694. "/ws-echo");
  20695. // First connection
  20696. ASSERT_TRUE(client.connect());
  20697. ASSERT_TRUE(client.send("first"));
  20698. std::string msg;
  20699. ASSERT_TRUE(client.read(msg));
  20700. EXPECT_EQ("first", msg);
  20701. client.close();
  20702. EXPECT_FALSE(client.is_open());
  20703. // Reconnect using the same client object
  20704. ASSERT_TRUE(client.connect());
  20705. ASSERT_TRUE(client.is_open());
  20706. ASSERT_TRUE(client.send("second"));
  20707. ASSERT_TRUE(client.read(msg));
  20708. EXPECT_EQ("second", msg);
  20709. client.close();
  20710. }
  20711. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20712. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20713. "/ws-close-status");
  20714. ASSERT_TRUE(client.connect());
  20715. // Trigger the server to close with GoingAway status
  20716. ASSERT_TRUE(client.send("trigger"));
  20717. // read() should return false after receiving the close frame
  20718. std::string msg;
  20719. EXPECT_FALSE(client.read(msg));
  20720. EXPECT_FALSE(client.is_open());
  20721. }
  20722. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20723. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20724. "/ws-echo");
  20725. ASSERT_TRUE(client.connect());
  20726. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20727. EXPECT_FALSE(client.is_open());
  20728. }
  20729. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20730. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20731. ws::WebSocketClient client(
  20732. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20733. ASSERT_TRUE(client.connect());
  20734. // Server should have selected graphql-ws
  20735. EXPECT_EQ("graphql-ws", client.subprotocol());
  20736. client.close();
  20737. }
  20738. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20739. Headers headers;
  20740. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20741. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20742. ws::WebSocketClient client(
  20743. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20744. ASSERT_TRUE(client.connect());
  20745. // The offer on the second field line counts too, so graphql-ws is selected
  20746. EXPECT_EQ("graphql-ws", client.subprotocol());
  20747. client.close();
  20748. }
  20749. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20750. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20751. ws::WebSocketClient client(
  20752. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20753. ASSERT_TRUE(client.connect());
  20754. // Server should not have selected any subprotocol
  20755. EXPECT_TRUE(client.subprotocol().empty());
  20756. client.close();
  20757. }
  20758. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  20759. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20760. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20761. "/ws-subprotocol-unoffered",
  20762. headers);
  20763. ASSERT_TRUE(client.connect());
  20764. EXPECT_TRUE(client.subprotocol().empty());
  20765. client.close();
  20766. }
  20767. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20768. // Connect without requesting any subprotocol
  20769. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20770. "/ws-subprotocol");
  20771. ASSERT_TRUE(client.connect());
  20772. EXPECT_TRUE(client.subprotocol().empty());
  20773. client.close();
  20774. }
  20775. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20776. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20777. "/ws-echo");
  20778. client.set_tcp_nodelay(true);
  20779. client.set_connection_timeout(3, 0);
  20780. bool socket_options_called = false;
  20781. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20782. ASSERT_TRUE(client.connect());
  20783. ASSERT_TRUE(client.is_open());
  20784. EXPECT_TRUE(socket_options_called);
  20785. ASSERT_TRUE(client.send("hello"));
  20786. std::string msg;
  20787. auto result = client.read(msg);
  20788. EXPECT_EQ(result, ws::ReadResult::Text);
  20789. EXPECT_EQ(msg, "hello");
  20790. client.close();
  20791. }
  20792. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20793. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20794. "/ws-echo");
  20795. client.set_connection_timeout(std::chrono::seconds(3));
  20796. client.set_write_timeout(std::chrono::seconds(3));
  20797. // A sub-second remainder exercises the seconds/microseconds split.
  20798. client.set_read_timeout(std::chrono::milliseconds(1500));
  20799. ASSERT_TRUE(client.connect());
  20800. auto start = std::chrono::steady_clock::now();
  20801. std::string msg;
  20802. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20803. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20804. std::chrono::steady_clock::now() - start)
  20805. .count();
  20806. // Above 1s so that dropping the microseconds half of the split fails here.
  20807. // Ignoring the setter altogether would not reach this line at all: a client
  20808. // waits forever by default.
  20809. EXPECT_GE(elapsed, 1400);
  20810. EXPECT_LT(elapsed, 30000);
  20811. }
  20812. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20813. Server svr;
  20814. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20815. if (!req.has_header("Authorization")) {
  20816. res.status = StatusCode::Unauthorized_401;
  20817. res.set_content("Unauthorized", "text/plain");
  20818. return Server::HandlerResponse::Handled;
  20819. }
  20820. return Server::HandlerResponse::Unhandled;
  20821. });
  20822. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20823. std::string msg;
  20824. while (ws.read(msg)) {
  20825. ws.send(msg);
  20826. }
  20827. });
  20828. auto port = svr.bind_to_any_port("localhost");
  20829. std::thread t([&]() { svr.listen_after_bind(); });
  20830. svr.wait_until_ready();
  20831. // Without Authorization header - should be rejected before upgrade
  20832. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20833. EXPECT_FALSE(client1.connect());
  20834. // The rejection is framed like any other HTTP response
  20835. {
  20836. Client cli("localhost", port);
  20837. Headers headers = {{"Upgrade", "websocket"},
  20838. {"Connection", "Upgrade"},
  20839. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20840. {"Sec-WebSocket-Version", "13"}};
  20841. auto res = cli.Get("/ws", headers);
  20842. ASSERT_TRUE(res);
  20843. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20844. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20845. EXPECT_EQ("Unauthorized", res->body);
  20846. }
  20847. // With Authorization header - should succeed
  20848. Headers headers = {{"Authorization", "Bearer token123"}};
  20849. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20850. headers);
  20851. ASSERT_TRUE(client2.connect());
  20852. ASSERT_TRUE(client2.send("hello"));
  20853. std::string msg;
  20854. ASSERT_TRUE(client2.read(msg));
  20855. EXPECT_EQ("hello", msg);
  20856. client2.close();
  20857. svr.stop();
  20858. t.join();
  20859. }
  20860. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20861. Server svr;
  20862. std::atomic<int> pre_request_calls{0};
  20863. std::atomic<bool> route_matched{false};
  20864. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20865. pre_request_calls++;
  20866. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20867. if (req.get_header_value("Authorization") != "Bearer token123") {
  20868. res.status = StatusCode::Unauthorized_401;
  20869. res.set_content("Unauthorized", "text/plain");
  20870. return Server::HandlerResponse::Handled;
  20871. }
  20872. return Server::HandlerResponse::Unhandled;
  20873. });
  20874. std::atomic<bool> handler_called{false};
  20875. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20876. handler_called = true;
  20877. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20878. });
  20879. auto port = svr.bind_to_any_port("localhost");
  20880. std::thread t([&]() { svr.listen_after_bind(); });
  20881. svr.wait_until_ready();
  20882. // Without Authorization header - should be rejected before upgrade
  20883. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20884. "/ws/1");
  20885. EXPECT_FALSE(client1.connect());
  20886. EXPECT_FALSE(handler_called);
  20887. EXPECT_EQ(1, pre_request_calls);
  20888. EXPECT_TRUE(route_matched);
  20889. // The rejection is an ordinary HTTP response, not a protocol switch
  20890. {
  20891. Client cli("localhost", port);
  20892. Headers headers = {{"Upgrade", "websocket"},
  20893. {"Connection", "Upgrade"},
  20894. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20895. {"Sec-WebSocket-Version", "13"}};
  20896. auto res = cli.Get("/ws/1", headers);
  20897. ASSERT_TRUE(res);
  20898. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20899. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20900. EXPECT_EQ("Unauthorized", res->body);
  20901. }
  20902. EXPECT_FALSE(handler_called);
  20903. // With Authorization header - should succeed
  20904. Headers headers = {{"Authorization", "Bearer token123"}};
  20905. ws::WebSocketClient client2(
  20906. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20907. ASSERT_TRUE(client2.connect());
  20908. std::string msg;
  20909. ASSERT_TRUE(client2.read(msg));
  20910. EXPECT_EQ("/ws/:id 2", msg);
  20911. EXPECT_TRUE(handler_called);
  20912. client2.close();
  20913. svr.stop();
  20914. t.join();
  20915. }
  20916. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20917. Server svr;
  20918. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20919. // A read timeout is how a handler gets control back. Without it, a handler
  20920. // parked in read() can never write on the connection it is reading.
  20921. ws.set_read_timeout(std::chrono::milliseconds(100));
  20922. std::string msg;
  20923. while (ws.is_open()) {
  20924. auto r = ws.read(msg);
  20925. if (r == httplib::ws::Timeout) {
  20926. ws.send("tick");
  20927. continue;
  20928. }
  20929. if (r == httplib::ws::Fail) { break; }
  20930. ws.send(msg);
  20931. }
  20932. });
  20933. auto port = svr.bind_to_any_port("localhost");
  20934. std::thread t([&]() { svr.listen_after_bind(); });
  20935. svr.wait_until_ready();
  20936. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20937. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20938. ASSERT_TRUE(client.connect());
  20939. // The client sends nothing, so anything it receives came out of the
  20940. // handler's timeout path.
  20941. std::string msg;
  20942. ASSERT_EQ(client.read(msg), ws::Text);
  20943. EXPECT_EQ("tick", msg);
  20944. client.close();
  20945. svr.stop();
  20946. t.join();
  20947. }
  20948. // Stream::read may return fewer bytes than asked for. This is that contract at
  20949. // its worst -- one byte per call -- which is what a frame header straddling a
  20950. // read buffer's boundary looks like to the frame parser.
  20951. class WsByteAtATimeStream : public Stream {
  20952. public:
  20953. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20954. bool is_readable() const override { return true; }
  20955. bool wait_readable() const override { return true; }
  20956. bool wait_writable() const override { return true; }
  20957. ssize_t read(char *ptr, size_t size) override {
  20958. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20959. *ptr = data_[pos_++];
  20960. return 1;
  20961. }
  20962. ssize_t write(const char *, size_t size) override {
  20963. return static_cast<ssize_t>(size);
  20964. }
  20965. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20966. ip = "127.0.0.1";
  20967. port = 0;
  20968. }
  20969. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20970. ip = "127.0.0.1";
  20971. port = 0;
  20972. }
  20973. socket_t socket() const override { return INVALID_SOCKET; }
  20974. time_t duration() const override { return 0; }
  20975. private:
  20976. std::string data_;
  20977. size_t pos_ = 0;
  20978. };
  20979. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20980. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20981. // length and the mask key are all multi-byte fields here. Each used to be
  20982. // read with a single read() call, which fails as soon as one is split.
  20983. std::string body(200, 'x');
  20984. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20985. std::string frame;
  20986. frame += static_cast<char>(0x81); // FIN + Text
  20987. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20988. frame += static_cast<char>(body.size() >> 8);
  20989. frame += static_cast<char>(body.size() & 0xff);
  20990. for (size_t i = 0; i < 4; i++) {
  20991. frame += static_cast<char>(mask[i]);
  20992. }
  20993. for (size_t i = 0; i < body.size(); i++) {
  20994. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20995. }
  20996. WsByteAtATimeStream strm(frame);
  20997. ws::Opcode opcode;
  20998. std::string payload;
  20999. bool fin = false;
  21000. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21001. /*expect_masked=*/true, 1024),
  21002. ws::impl::FrameRead::Ok);
  21003. EXPECT_TRUE(fin);
  21004. EXPECT_EQ(opcode, ws::Opcode::Text);
  21005. EXPECT_EQ(payload, body);
  21006. }
  21007. TEST(WebSocketTest, QueryStringInHandshake) {
  21008. Server svr;
  21009. std::mutex mtx;
  21010. std::string received_target;
  21011. std::string received_token;
  21012. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21013. {
  21014. std::lock_guard<std::mutex> lock(mtx);
  21015. received_target = req.target;
  21016. if (req.has_param("token")) {
  21017. received_token = req.get_param_value("token");
  21018. }
  21019. }
  21020. std::string msg;
  21021. while (ws.read(msg)) {
  21022. ws.send(msg);
  21023. }
  21024. });
  21025. auto port = svr.bind_to_any_port("localhost");
  21026. std::thread t([&]() { svr.listen_after_bind(); });
  21027. svr.wait_until_ready();
  21028. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21029. "/ws?token=ABC&session=123");
  21030. ASSERT_TRUE(client.connect());
  21031. // Round-trip ensures the handler has run and captured the request.
  21032. ASSERT_TRUE(client.send("hello"));
  21033. std::string msg;
  21034. ASSERT_TRUE(client.read(msg));
  21035. EXPECT_EQ("hello", msg);
  21036. client.close();
  21037. {
  21038. std::lock_guard<std::mutex> lock(mtx);
  21039. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21040. EXPECT_EQ("ABC", received_token);
  21041. }
  21042. svr.stop();
  21043. t.join();
  21044. }
  21045. // Run a handshake against a throwaway server and hand the request the server
  21046. // received back to the caller, so tests can assert on the headers the client
  21047. // actually put on the wire.
  21048. static void capture_websocket_handshake_request(
  21049. const Headers &client_headers,
  21050. std::function<void(const Request &, int port)> verify) {
  21051. Server svr;
  21052. std::mutex mtx;
  21053. Request received;
  21054. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21055. {
  21056. std::lock_guard<std::mutex> lock(mtx);
  21057. received = req;
  21058. }
  21059. std::string msg;
  21060. while (ws.read(msg)) {
  21061. ws.send(msg);
  21062. }
  21063. });
  21064. auto port = svr.bind_to_any_port("localhost");
  21065. std::thread t([&]() { svr.listen_after_bind(); });
  21066. auto se = detail::scope_exit([&] {
  21067. svr.stop();
  21068. t.join();
  21069. });
  21070. svr.wait_until_ready();
  21071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21072. client_headers);
  21073. ASSERT_TRUE(client.connect());
  21074. ASSERT_TRUE(client.send("hello"));
  21075. std::string msg;
  21076. ASSERT_TRUE(client.read(msg));
  21077. client.close();
  21078. {
  21079. std::lock_guard<std::mutex> lock(mtx);
  21080. verify(received, port);
  21081. }
  21082. }
  21083. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21084. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21085. // Non-default port must be present in the Host header. Default ports
  21086. // (80/443) are omitted; that logic is covered by
  21087. // MakeHostAndPortStringTest.
  21088. EXPECT_EQ("localhost:" + std::to_string(port),
  21089. req.get_header_value("Host"));
  21090. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21091. req.get_header_value("User-Agent"));
  21092. EXPECT_FALSE(req.has_header("Accept"));
  21093. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21094. EXPECT_FALSE(req.has_header("Content-Length"));
  21095. });
  21096. }
  21097. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21098. capture_websocket_handshake_request(
  21099. {{"Host", "example.com"},
  21100. {"User-Agent", "custom-agent"},
  21101. {"X-Custom", "value"}},
  21102. [](const Request &req, int) {
  21103. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21104. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21105. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21106. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21107. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21108. });
  21109. }
  21110. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21111. capture_websocket_handshake_request(
  21112. {{"Upgrade", "bogus"},
  21113. {"Connection", "close"},
  21114. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21115. {"Sec-WebSocket-Version", "8"}},
  21116. [](const Request &req, int) {
  21117. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21118. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21119. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21120. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21121. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21122. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21123. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21124. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21125. req.get_header_value("Sec-WebSocket-Key"));
  21126. });
  21127. }
  21128. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21129. // A header the client refuses to send must abort the handshake before any
  21130. // part of it reaches the wire; a lone request line would otherwise sit in
  21131. // the peer's buffer as a truncated request.
  21132. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21133. ASSERT_NE(INVALID_SOCKET, srv);
  21134. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21135. sockaddr_in addr{};
  21136. addr.sin_family = AF_INET;
  21137. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21138. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21139. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21140. ASSERT_EQ(0, ::listen(srv, 1));
  21141. sockaddr_in bound{};
  21142. socklen_t bound_len = sizeof(bound);
  21143. ASSERT_EQ(
  21144. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21145. auto port = ntohs(bound.sin_port);
  21146. ssize_t received = -1;
  21147. std::thread t([&] {
  21148. // Bound every blocking call so a regression fails the test with a bad
  21149. // value instead of hanging the suite.
  21150. fd_set rfds;
  21151. FD_ZERO(&rfds);
  21152. FD_SET(srv, &rfds);
  21153. timeval tv{5, 0};
  21154. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21155. 0) {
  21156. return;
  21157. }
  21158. sockaddr_in cli_addr{};
  21159. socklen_t cli_len = sizeof(cli_addr);
  21160. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21161. if (cli == INVALID_SOCKET) { return; }
  21162. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21163. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21164. char buf[4096];
  21165. received = ::recv(cli, buf, sizeof(buf), 0);
  21166. });
  21167. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21168. // connect() has already shut the socket down by the time it returns false,
  21169. // so the peer sees EOF without waiting for the client to be destroyed.
  21170. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21171. {{"X-Bad", "a\r\nInjected: 1"}});
  21172. EXPECT_FALSE(client.connect());
  21173. t.join();
  21174. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21175. EXPECT_EQ(0, received);
  21176. }
  21177. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21178. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21179. // contains "upgrade" as a substring is a different token and must not
  21180. // start a WebSocket handshake.
  21181. auto make_request = [](const std::vector<std::string> &connection_values) {
  21182. Request req;
  21183. req.method = "GET";
  21184. req.headers.emplace("Upgrade", "websocket");
  21185. for (const auto &value : connection_values) {
  21186. req.headers.emplace("Connection", value);
  21187. }
  21188. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21189. req.headers.emplace("Sec-WebSocket-Version", "13");
  21190. return req;
  21191. };
  21192. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21193. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21194. EXPECT_TRUE(
  21195. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21196. EXPECT_TRUE(
  21197. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21198. EXPECT_TRUE(
  21199. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21200. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21201. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21202. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21203. EXPECT_FALSE(
  21204. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21205. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21206. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21207. }
  21208. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21209. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21210. // asks recipients to match each protocol-name case-insensitively, and RFC
  21211. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21212. // client naming websocket alongside another protocol, or on a second field
  21213. // line, is offering websocket; a value that merely contains "websocket" as a
  21214. // substring is a different protocol name and is not.
  21215. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21216. Request req;
  21217. req.method = "GET";
  21218. for (const auto &value : upgrade_values) {
  21219. req.headers.emplace("Upgrade", value);
  21220. }
  21221. req.headers.emplace("Connection", "Upgrade");
  21222. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21223. req.headers.emplace("Sec-WebSocket-Version", "13");
  21224. return req;
  21225. };
  21226. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21227. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21228. EXPECT_TRUE(
  21229. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21230. EXPECT_TRUE(
  21231. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21232. EXPECT_TRUE(
  21233. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21234. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21235. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21236. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21237. EXPECT_FALSE(
  21238. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21239. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21240. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21241. }
  21242. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21243. Server svr;
  21244. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21245. auto port = svr.bind_to_any_port("localhost");
  21246. std::thread t([&]() { svr.listen_after_bind(); });
  21247. auto se = detail::scope_exit([&] {
  21248. svr.stop();
  21249. t.join();
  21250. });
  21251. svr.wait_until_ready();
  21252. Headers headers = {{"Upgrade", "websocket"},
  21253. {"Connection", "notupgrade"},
  21254. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21255. {"Sec-WebSocket-Version", "13"}};
  21256. Client cli("localhost", port);
  21257. auto res = cli.Get("/ws", headers);
  21258. // The route exists only as a WebSocket route, so a request that fails the
  21259. // handshake check falls through to ordinary routing.
  21260. ASSERT_TRUE(res);
  21261. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21262. }
  21263. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21264. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21265. // Connection value is the only thing left for the client to reject.
  21266. Server svr;
  21267. svr.Get("/ws", [](const Request &req, Response &res) {
  21268. res.status = StatusCode::SwitchingProtocol_101;
  21269. res.set_header("Upgrade", "websocket");
  21270. res.set_header("Connection", "notupgrade");
  21271. res.set_header("Sec-WebSocket-Accept",
  21272. detail::websocket_accept_key(
  21273. req.get_header_value("Sec-WebSocket-Key")));
  21274. });
  21275. auto port = svr.bind_to_any_port("localhost");
  21276. std::thread t([&]() { svr.listen_after_bind(); });
  21277. auto se = detail::scope_exit([&] {
  21278. svr.stop();
  21279. t.join();
  21280. });
  21281. svr.wait_until_ready();
  21282. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21283. auto res = client.connect();
  21284. EXPECT_FALSE(res);
  21285. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21286. EXPECT_FALSE(client.is_open());
  21287. }
  21288. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21289. Server svr;
  21290. svr.Get("/ws", [](const Request &req, Response &res) {
  21291. res.status = StatusCode::SwitchingProtocol_101;
  21292. res.set_header("Upgrade", "websocket");
  21293. res.set_header("Connection", "Upgrade");
  21294. res.set_header("Sec-WebSocket-Accept",
  21295. detail::websocket_accept_key(
  21296. req.get_header_value("Sec-WebSocket-Key")));
  21297. res.set_header("Sec-WebSocket-Protocol", "admin");
  21298. });
  21299. auto port = svr.bind_to_any_port("localhost");
  21300. std::thread t([&]() { svr.listen_after_bind(); });
  21301. auto se = detail::scope_exit([&] {
  21302. svr.stop();
  21303. t.join();
  21304. });
  21305. svr.wait_until_ready();
  21306. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21307. // Server selects a subprotocol the client never offered
  21308. {
  21309. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21310. ws::WebSocketClient client(url, headers);
  21311. auto res = client.connect();
  21312. EXPECT_FALSE(res);
  21313. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21314. EXPECT_FALSE(client.is_open());
  21315. EXPECT_TRUE(client.subprotocol().empty());
  21316. }
  21317. // Client offered none but the server named one anyway
  21318. {
  21319. ws::WebSocketClient client(url);
  21320. auto res = client.connect();
  21321. EXPECT_FALSE(res);
  21322. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21323. EXPECT_FALSE(client.is_open());
  21324. EXPECT_TRUE(client.subprotocol().empty());
  21325. }
  21326. }
  21327. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21328. // The socket path doubles as the URL host, so it must not contain '/'.
  21329. const char *shard = getenv("GTEST_SHARD_INDEX");
  21330. const std::string sock_path =
  21331. shard ? std::string("httplib-ws-") + shard + ".sock"
  21332. : std::string("httplib-ws.sock");
  21333. std::remove(sock_path.c_str());
  21334. Server svr;
  21335. std::mutex mtx;
  21336. std::string received_host;
  21337. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21338. {
  21339. std::lock_guard<std::mutex> lock(mtx);
  21340. received_host = req.get_header_value("Host");
  21341. }
  21342. std::string msg;
  21343. while (ws.read(msg)) {
  21344. ws.send(msg);
  21345. }
  21346. });
  21347. svr.set_address_family(AF_UNIX);
  21348. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21349. auto se = detail::scope_exit([&] {
  21350. svr.stop();
  21351. t.join();
  21352. std::remove(sock_path.c_str());
  21353. });
  21354. svr.wait_until_ready();
  21355. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21356. client.set_address_family(AF_UNIX);
  21357. ASSERT_TRUE(client.connect());
  21358. ASSERT_TRUE(client.send("hello"));
  21359. std::string msg;
  21360. ASSERT_TRUE(client.read(msg));
  21361. client.close();
  21362. {
  21363. std::lock_guard<std::mutex> lock(mtx);
  21364. // There is no host:port for a Unix socket, so the same "localhost"
  21365. // placeholder the HTTP client uses is expected.
  21366. EXPECT_EQ("localhost", received_host);
  21367. }
  21368. }
  21369. // Two threads must never parse WebSocket frames from the same stream.
  21370. // close() used to read the peer's Close reply with its own frame read, so it
  21371. // raced a reader thread that was in the middle of a payload: the payload loop
  21372. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21373. // so bytes taken by close() were replaced with bytes from further along the
  21374. // stream. The message kept its length and silently changed content.
  21375. //
  21376. // The raw peer below sends a frame header plus part of the payload, waits for
  21377. // the handler to call close(), and only then sends the rest. Whichever thread
  21378. // would win the race for those bytes, the message must arrive intact, because
  21379. // close() must not touch the stream while read() owns it.
  21380. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21381. #ifndef _WIN32
  21382. signal(SIGPIPE, SIG_IGN);
  21383. #endif
  21384. const size_t payload_len = 120; // fits the 7-bit length field
  21385. const size_t prefix_len = 8;
  21386. const int attempts = 8;
  21387. std::string expected(payload_len, '\0');
  21388. for (size_t i = 0; i < payload_len; i++) {
  21389. expected[i] = static_cast<char>('a' + i % 26);
  21390. }
  21391. std::atomic<bool> peer_stalled{false};
  21392. std::atomic<bool> handler_done{false};
  21393. std::mutex received_mutex;
  21394. std::vector<std::string> received;
  21395. // Bound every wait, so a regression fails the test instead of hanging the
  21396. // suite.
  21397. auto wait_for = [](const std::atomic<bool> &flag) {
  21398. for (int i = 0; i < 500 && !flag; i++) {
  21399. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21400. }
  21401. };
  21402. Server svr;
  21403. svr.set_websocket_ping_interval(0);
  21404. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21405. std::thread reader([&]() {
  21406. std::string msg;
  21407. while (ws.read(msg)) {
  21408. std::lock_guard<std::mutex> guard(received_mutex);
  21409. received.push_back(msg);
  21410. }
  21411. });
  21412. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21413. // inside read_websocket_frame() when close() runs.
  21414. wait_for(peer_stalled);
  21415. ws.close();
  21416. reader.join();
  21417. handler_done = true;
  21418. });
  21419. auto port = svr.bind_to_any_port("127.0.0.1");
  21420. std::thread t([&]() { svr.listen_after_bind(); });
  21421. auto se = detail::scope_exit([&] {
  21422. svr.stop();
  21423. t.join();
  21424. });
  21425. svr.wait_until_ready();
  21426. auto send_bytes = [](socket_t s, const std::string &data) {
  21427. #ifdef _WIN32
  21428. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21429. #else
  21430. auto n = ::send(s, data.data(), data.size(), 0);
  21431. #endif
  21432. return n == static_cast<decltype(n)>(data.size());
  21433. };
  21434. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21435. // Every length used here fits the 7-bit length field.
  21436. auto masked_header = [](uint8_t first_byte, size_t len) {
  21437. std::string h;
  21438. h += static_cast<char>(first_byte);
  21439. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21440. h.append(4, '\0'); // mask key
  21441. return h;
  21442. };
  21443. for (int attempt = 0; attempt < attempts; attempt++) {
  21444. peer_stalled = false;
  21445. handler_done = false;
  21446. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21447. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21448. auto se_sock = detail::scope_exit([&] {
  21449. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21450. });
  21451. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21452. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21453. sockaddr_in addr{};
  21454. addr.sin_family = AF_INET;
  21455. addr.sin_port = htons(static_cast<uint16_t>(port));
  21456. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21457. ASSERT_EQ(
  21458. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21459. << "attempt " << attempt;
  21460. ASSERT_TRUE(send_bytes(sock,
  21461. "GET /ws HTTP/1.1\r\n"
  21462. "Host: 127.0.0.1\r\n"
  21463. "Upgrade: websocket\r\n"
  21464. "Connection: Upgrade\r\n"
  21465. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21466. "Sec-WebSocket-Version: 13\r\n"
  21467. "\r\n"))
  21468. << "attempt " << attempt;
  21469. std::string response;
  21470. while (response.find("\r\n\r\n") == std::string::npos) {
  21471. char buf[512];
  21472. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21473. if (n <= 0) { break; }
  21474. response.append(buf, static_cast<size_t>(n));
  21475. }
  21476. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21477. << "attempt " << attempt;
  21478. // Send the header of a Binary message but only the first prefix_len bytes
  21479. // of its payload, leaving the reader thread stalled inside the payload.
  21480. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21481. expected.substr(0, prefix_len)))
  21482. << "attempt " << attempt;
  21483. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21484. peer_stalled = true;
  21485. // Let close() send its Close frame and park in its own read before the
  21486. // rest of the payload arrives, so both threads are waiting for it.
  21487. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21488. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21489. close_frame += static_cast<char>(0x03); // status 1000
  21490. close_frame += static_cast<char>(0xE8);
  21491. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21492. << "attempt " << attempt;
  21493. // Closing the peer releases the reader thread even on the buggy path,
  21494. // where it waits for bytes another thread already consumed.
  21495. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21496. detail::close_socket(sock);
  21497. sock = INVALID_SOCKET;
  21498. wait_for(handler_done);
  21499. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21500. }
  21501. std::lock_guard<std::mutex> guard(received_mutex);
  21502. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21503. << "a message in flight when close() ran was dropped";
  21504. for (size_t i = 0; i < received.size(); i++) {
  21505. EXPECT_EQ(expected, received[i]) << "message " << i;
  21506. }
  21507. }
  21508. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21509. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21510. protected:
  21511. void SetUp() override {
  21512. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21513. SERVER_PRIVATE_KEY_FILE);
  21514. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21515. std::string msg;
  21516. ws::ReadResult ret;
  21517. while ((ret = ws.read(msg))) {
  21518. if (ret == ws::Binary) {
  21519. ws.send(msg.data(), msg.size());
  21520. } else {
  21521. ws.send(msg);
  21522. }
  21523. }
  21524. });
  21525. port_ = server_->bind_to_any_port(HOST);
  21526. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21527. server_->wait_until_ready();
  21528. }
  21529. void TearDown() override {
  21530. server_->stop();
  21531. if (server_thread_.joinable()) { server_thread_.join(); }
  21532. }
  21533. std::unique_ptr<SSLServer> server_;
  21534. std::thread server_thread_;
  21535. int port_ = 0;
  21536. };
  21537. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21538. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21539. "/ws-echo");
  21540. client.enable_server_certificate_verification(false);
  21541. ASSERT_TRUE(client.connect());
  21542. ASSERT_TRUE(client.is_open());
  21543. ASSERT_TRUE(client.send("Hello WSS"));
  21544. std::string msg;
  21545. EXPECT_EQ(ws::Text, client.read(msg));
  21546. EXPECT_EQ("Hello WSS", msg);
  21547. client.close();
  21548. }
  21549. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21550. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21551. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21552. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21553. // client (without calling close() first) is the only path that runs
  21554. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21555. // bug exactly.
  21556. //
  21557. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21558. // when linked against an instrumented libssl; run under Valgrind to catch it
  21559. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21560. // suite (the freed session otherwise stalls on the close handshake) — this test
  21561. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21562. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21563. {
  21564. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21565. "/ws-echo");
  21566. client.enable_server_certificate_verification(false);
  21567. client.set_read_timeout(2, 0);
  21568. client.set_write_timeout(2, 0);
  21569. ASSERT_TRUE(client.connect());
  21570. ASSERT_TRUE(client.is_open());
  21571. ASSERT_TRUE(client.send("still open"));
  21572. // Intentionally do NOT call client.close(): leaving scope runs
  21573. // shutdown_and_close() with the WebSocket still open, which must send the
  21574. // close frame while the TLS session is still alive.
  21575. }
  21576. }
  21577. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21578. // shutdown_and_close() at the start of connect(), reproducing the same
  21579. // use-after-free within the test body rather than at scope exit. The second
  21580. // connect must succeed and echo, proving the close handshake ran over a live
  21581. // session. See the note above about memory-tool requirements.
  21582. TEST_F(WebSocketSSLIntegrationTest,
  21583. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21584. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21585. "/ws-echo");
  21586. client.enable_server_certificate_verification(false);
  21587. client.set_read_timeout(2, 0);
  21588. client.set_write_timeout(2, 0);
  21589. ASSERT_TRUE(client.connect());
  21590. ASSERT_TRUE(client.is_open());
  21591. ASSERT_TRUE(client.send("still open"));
  21592. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21593. // the still-open connection, which must not touch a freed TLS session.
  21594. ASSERT_TRUE(client.connect());
  21595. ASSERT_TRUE(client.is_open());
  21596. ASSERT_TRUE(client.send("after reconnect"));
  21597. std::string msg;
  21598. EXPECT_EQ(ws::Text, client.read(msg));
  21599. EXPECT_EQ("after reconnect", msg);
  21600. client.close();
  21601. }
  21602. #endif
  21603. #ifdef CPPHTTPLIB_SSL_ENABLED
  21604. class WebSocketSSLCATest : public ::testing::Test {
  21605. protected:
  21606. void SetUp() override {
  21607. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21608. SERVER_PRIVATE_KEY_FILE);
  21609. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21610. std::string msg;
  21611. while (ws.read(msg)) {
  21612. ws.send(msg);
  21613. }
  21614. });
  21615. port_ = server_->bind_to_any_port("127.0.0.1");
  21616. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21617. server_->wait_until_ready();
  21618. }
  21619. void TearDown() override {
  21620. server_->stop();
  21621. if (server_thread_.joinable()) { server_thread_.join(); }
  21622. }
  21623. std::string url() const {
  21624. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21625. }
  21626. std::unique_ptr<SSLServer> server_;
  21627. std::thread server_thread_;
  21628. int port_ = 0;
  21629. };
  21630. // A custom CA loaded as PEM verifies the server with full certificate
  21631. // verification enabled
  21632. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21633. ws::WebSocketClient client(url());
  21634. std::string cert;
  21635. read_file(SERVER_CERT2_FILE, cert);
  21636. client.load_ca_cert_store(cert.c_str(), cert.size());
  21637. ASSERT_TRUE(client.connect());
  21638. ASSERT_TRUE(client.send("hello"));
  21639. std::string msg;
  21640. EXPECT_EQ(ws::Text, client.read(msg));
  21641. EXPECT_EQ("hello", msg);
  21642. client.close();
  21643. }
  21644. // A custom CA that does not cover the server must fail verification (the
  21645. // custom CA is exclusive; system certs are not loaded alongside it)
  21646. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21647. ws::WebSocketClient client(url());
  21648. std::string cert;
  21649. read_file(CLIENT_CA_CERT_FILE, cert);
  21650. client.load_ca_cert_store(cert.c_str(), cert.size());
  21651. auto res = client.connect();
  21652. ASSERT_FALSE(res);
  21653. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21654. EXPECT_EQ(-1, res.status());
  21655. EXPECT_NE(0u, res.ssl_backend_error());
  21656. }
  21657. // The same CA as a file path rather than PEM in memory
  21658. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21659. ws::WebSocketClient client(url());
  21660. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21661. ASSERT_TRUE(client.connect());
  21662. ASSERT_TRUE(client.send("hello"));
  21663. std::string msg;
  21664. EXPECT_EQ(ws::Text, client.read(msg));
  21665. EXPECT_EQ("hello", msg);
  21666. client.close();
  21667. }
  21668. // ...and a CA file that does not cover the server still fails, so it is the
  21669. // path above that decides the outcome
  21670. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21671. ws::WebSocketClient client(url());
  21672. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21673. ASSERT_FALSE(client.connect());
  21674. }
  21675. // Regression test: reconnecting with a native custom CA store used to reuse
  21676. // a store handle the previous TLS context had already freed (use-after-free
  21677. // under the OpenSSL backend). The context now lives as long as the client.
  21678. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21679. ws::WebSocketClient client(url());
  21680. std::string cert;
  21681. read_file(SERVER_CERT2_FILE, cert);
  21682. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21683. ASSERT_TRUE(client.connect());
  21684. client.close();
  21685. ASSERT_TRUE(client.connect());
  21686. ASSERT_TRUE(client.send("again"));
  21687. std::string msg;
  21688. EXPECT_EQ(ws::Text, client.read(msg));
  21689. EXPECT_EQ("again", msg);
  21690. client.close();
  21691. }
  21692. // Regression test: a certificate with a trusted chain but no identity match
  21693. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21694. // verification entirely for IP hosts, so this connection succeeded there.
  21695. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21696. // chain verification while the identity check must still fail.
  21697. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21698. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21699. ASSERT_TRUE(svr.is_valid());
  21700. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21701. std::string msg;
  21702. while (ws.read(msg)) {
  21703. ws.send(msg);
  21704. }
  21705. });
  21706. auto port = svr.bind_to_any_port("127.0.0.1");
  21707. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21708. auto se = detail::scope_exit([&] {
  21709. svr.stop();
  21710. t.join();
  21711. });
  21712. svr.wait_until_ready();
  21713. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21714. "/echo");
  21715. std::string cert;
  21716. read_file(SERVER_CERT_FILE, cert);
  21717. client.load_ca_cert_store(cert.c_str(), cert.size());
  21718. ASSERT_FALSE(client.connect());
  21719. }
  21720. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21721. // SNI, so nothing binds the host name to the TLS session. These bind the
  21722. // server to "localhost" instead, the only shape that exercises the SNI and
  21723. // hostname-verification path with certificate verification left enabled.
  21724. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21725. protected:
  21726. void Start(const char *cert_file) {
  21727. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21728. SERVER_PRIVATE_KEY_FILE);
  21729. ASSERT_TRUE(server_->is_valid());
  21730. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21731. std::string msg;
  21732. while (ws.read(msg)) {
  21733. ws.send(msg);
  21734. }
  21735. });
  21736. port_ = server_->bind_to_any_port("localhost");
  21737. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21738. server_->wait_until_ready();
  21739. }
  21740. void TearDown() override {
  21741. if (server_) { server_->stop(); }
  21742. if (server_thread_.joinable()) { server_thread_.join(); }
  21743. }
  21744. std::string url() const {
  21745. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21746. }
  21747. std::unique_ptr<SSLServer> server_;
  21748. std::thread server_thread_;
  21749. int port_ = 0;
  21750. };
  21751. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21752. // out and the connection is usable
  21753. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21754. Start(SERVER_CERT2_FILE);
  21755. ws::WebSocketClient client(url());
  21756. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21757. ASSERT_TRUE(client.connect());
  21758. ASSERT_TRUE(client.send("hello"));
  21759. std::string msg;
  21760. EXPECT_EQ(ws::Text, client.read(msg));
  21761. EXPECT_EQ("hello", msg);
  21762. client.close();
  21763. }
  21764. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21765. // while the identity check must still reject "localhost"
  21766. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21767. Start(SERVER_CERT_FILE);
  21768. ws::WebSocketClient client(url());
  21769. client.set_ca_cert_path(SERVER_CERT_FILE);
  21770. auto res = client.connect();
  21771. ASSERT_FALSE(res);
  21772. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21773. EXPECT_EQ(-1, res.status());
  21774. }
  21775. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21776. // disabled: the chain is still checked, only the identity check is skipped
  21777. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21778. Start(SERVER_CERT_FILE);
  21779. ws::WebSocketClient client(url());
  21780. client.set_ca_cert_path(SERVER_CERT_FILE);
  21781. client.enable_server_hostname_verification(false);
  21782. ASSERT_TRUE(client.connect());
  21783. ASSERT_TRUE(client.send("hello"));
  21784. std::string msg;
  21785. EXPECT_EQ(ws::Text, client.read(msg));
  21786. EXPECT_EQ("hello", msg);
  21787. client.close();
  21788. }
  21789. // A CA that did not sign the server certificate fails the chain, even though
  21790. // the name would match
  21791. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21792. Start(SERVER_CERT2_FILE);
  21793. ws::WebSocketClient client(url());
  21794. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21795. ASSERT_FALSE(client.connect());
  21796. }
  21797. // With verification disabled, neither the chain nor the name is checked
  21798. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21799. Start(SERVER_CERT_FILE);
  21800. ws::WebSocketClient client(url());
  21801. client.enable_server_certificate_verification(false);
  21802. ASSERT_TRUE(client.connect());
  21803. ASSERT_TRUE(client.send("hello"));
  21804. std::string msg;
  21805. EXPECT_EQ(ws::Text, client.read(msg));
  21806. EXPECT_EQ("hello", msg);
  21807. client.close();
  21808. }
  21809. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21810. protected:
  21811. void SetUp() override {
  21812. server_ = httplib::detail::make_unique<SSLServer>(
  21813. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21814. ASSERT_TRUE(server_->is_valid());
  21815. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21816. std::string msg;
  21817. while (ws.read(msg)) {
  21818. ws.send(msg);
  21819. }
  21820. });
  21821. port_ = server_->bind_to_any_port("localhost");
  21822. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21823. server_->wait_until_ready();
  21824. }
  21825. void TearDown() override {
  21826. server_->stop();
  21827. if (server_thread_.joinable()) { server_thread_.join(); }
  21828. }
  21829. std::string url() const {
  21830. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21831. }
  21832. void ConnectWithClientCert(const std::string &client_cert_file,
  21833. const std::string &client_private_key_file,
  21834. const char *private_key_password) {
  21835. std::string cert_pem, key_pem;
  21836. read_file(client_cert_file, cert_pem);
  21837. read_file(client_private_key_file, key_pem);
  21838. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21839. key_pem.c_str(), key_pem.size(),
  21840. private_key_password};
  21841. ws::WebSocketClient client(url(), pem);
  21842. ASSERT_TRUE(client.is_valid());
  21843. client.enable_server_certificate_verification(false);
  21844. ASSERT_TRUE(client.connect());
  21845. ASSERT_TRUE(client.send("hello"));
  21846. std::string msg;
  21847. EXPECT_EQ(ws::Text, client.read(msg));
  21848. EXPECT_EQ("hello", msg);
  21849. client.close();
  21850. }
  21851. std::unique_ptr<SSLServer> server_;
  21852. std::thread server_thread_;
  21853. int port_ = 0;
  21854. };
  21855. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21856. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21857. }
  21858. // Control for the tests above: the fixture's server really does require a
  21859. // client certificate, so it is the PEM the constructor installed that decides
  21860. // the outcome.
  21861. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21862. ws::WebSocketClient client(url());
  21863. ASSERT_TRUE(client.is_valid());
  21864. client.enable_server_certificate_verification(false);
  21865. EXPECT_FALSE(client.connect());
  21866. }
  21867. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21868. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21869. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21870. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21871. }
  21872. #endif
  21873. #if !defined(_WIN32)
  21874. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21875. auto secret_dir = std::string("./symlink_test_secret");
  21876. auto served_dir = std::string("./symlink_test_served");
  21877. auto secret_file = secret_dir + "/secret.txt";
  21878. auto symlink_path = served_dir + "/escape";
  21879. // Setup: create directories and files
  21880. mkdir(secret_dir.c_str(), 0755);
  21881. mkdir(served_dir.c_str(), 0755);
  21882. {
  21883. std::ofstream ofs(secret_file);
  21884. ofs << "SECRET_DATA";
  21885. }
  21886. // Create symlink using absolute path so it resolves correctly
  21887. #ifdef PATH_MAX
  21888. char abs_secret[PATH_MAX];
  21889. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21890. #else
  21891. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21892. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21893. ASSERT_NE(nullptr, abs_secret);
  21894. #endif
  21895. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21896. auto se = detail::scope_exit([&] {
  21897. unlink(symlink_path.c_str());
  21898. unlink(secret_file.c_str());
  21899. rmdir(served_dir.c_str());
  21900. rmdir(secret_dir.c_str());
  21901. });
  21902. Server svr;
  21903. svr.set_mount_point("/", served_dir);
  21904. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21905. auto se2 = detail::scope_exit([&] {
  21906. svr.stop();
  21907. listen_thread.join();
  21908. });
  21909. svr.wait_until_ready();
  21910. Client cli("localhost", PORT);
  21911. // Symlink pointing outside base dir should be blocked
  21912. auto res = cli.Get("/escape/secret.txt");
  21913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21914. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21915. }
  21916. #endif
  21917. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21918. // "GET /smuggled" request), reads the first response, and only then sends the
  21919. // embedded request as the body. Returns how many times /smuggled ran.
  21920. //
  21921. // The body is sent AFTER receiving the first response (as in the original
  21922. // PoC) so that the stream_line_reader cannot buffer it together with the
  21923. // headers of the first request.
  21924. static int count_smuggled_requests(const std::string &outer_head,
  21925. std::string &first_response) {
  21926. Server svr;
  21927. svr.set_mount_point("/", "./www");
  21928. std::atomic<int> smuggled_count(0);
  21929. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21930. smuggled_count++;
  21931. res.set_content("oops", "text/plain");
  21932. });
  21933. svr.Post("/post", [&](const Request &req, Response &res) {
  21934. res.set_content(req.body, "text/plain");
  21935. });
  21936. auto port = svr.bind_to_any_port("localhost");
  21937. thread t = thread([&] { svr.listen_after_bind(); });
  21938. auto se = detail::scope_exit([&] {
  21939. svr.stop();
  21940. t.join();
  21941. });
  21942. svr.wait_until_ready();
  21943. auto error = Error::Success;
  21944. auto sock = detail::create_client_socket(
  21945. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21946. /*connection_timeout_sec=*/2, 0,
  21947. /*read_timeout_sec=*/2, 0,
  21948. /*write_timeout_sec=*/2, 0, std::string(), error);
  21949. EXPECT_NE(INVALID_SOCKET, sock);
  21950. if (sock == INVALID_SOCKET) { return -1; }
  21951. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21952. // The "smuggled" request will be sent as the body of the outer request
  21953. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21954. "Host: localhost\r\n"
  21955. "Connection: close\r\n"
  21956. "\r\n";
  21957. auto head = outer_head;
  21958. auto len = std::to_string(smuggled.size());
  21959. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21960. pos = head.find("{len}", pos + len.size())) {
  21961. head.replace(pos, 5, len);
  21962. }
  21963. // Step 1: Send only the outer request headers (no body yet)
  21964. auto sent = send(sock, head.data(), head.size(), 0);
  21965. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21966. // Step 2: Read the first response
  21967. char buf[4096];
  21968. for (;;) {
  21969. auto n = recv(sock, buf, sizeof(buf), 0);
  21970. if (n <= 0) break;
  21971. first_response.append(buf, static_cast<size_t>(n));
  21972. // Stop once we have a complete response (headers + body)
  21973. auto hdr_end = first_response.find("\r\n\r\n");
  21974. if (hdr_end != std::string::npos) {
  21975. // Check for Content-Length to know when the body is complete
  21976. auto cl_pos = first_response.find("Content-Length:");
  21977. if (cl_pos != std::string::npos) {
  21978. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21979. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21980. auto cl = std::stoul(
  21981. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21982. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21983. } else {
  21984. break; // No Content-Length, assume headers-only response
  21985. }
  21986. }
  21987. }
  21988. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21989. // vulnerable server the keep-alive loop reads this as a second request. The
  21990. // server may already have closed the connection, so the result is ignored.
  21991. send(sock, smuggled.data(), smuggled.size(), 0);
  21992. // Half-close so that a server which drained the body sees EOF and closes,
  21993. // instead of the read below waiting for the read timeout.
  21994. #ifdef _WIN32
  21995. ::shutdown(sock, SD_SEND);
  21996. #else
  21997. ::shutdown(sock, SHUT_WR);
  21998. #endif
  21999. // Step 4: Read until the server closes the connection
  22000. for (;;) {
  22001. auto n = recv(sock, buf, sizeof(buf), 0);
  22002. if (n <= 0) break;
  22003. }
  22004. return smuggled_count.load();
  22005. }
  22006. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22007. // A GET request with Content-Length to a static file handler must have its
  22008. // body drained before the keep-alive connection is reused. Otherwise the
  22009. // unread body bytes are interpreted as the next HTTP request.
  22010. std::string first_response;
  22011. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22012. "Host: localhost\r\n"
  22013. "Content-Length: {len}\r\n"
  22014. "\r\n",
  22015. first_response));
  22016. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22017. }
  22018. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22019. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22020. // be answered with 400 and the connection closed. Treating it as "no body"
  22021. // leaves the body to be parsed as the next request.
  22022. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22023. const char *targets[] = {
  22024. "GET /file", // handler that never reads the body
  22025. "GET /not-found", // no handler matches (404)
  22026. "POST /post", // handler that reads the body
  22027. };
  22028. for (auto target : targets) {
  22029. for (auto value : values) {
  22030. std::string first_response;
  22031. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22032. " HTTP/1.1\r\n"
  22033. "Host: localhost\r\n"
  22034. "Content-Length: " +
  22035. value + "\r\n\r\n",
  22036. first_response))
  22037. << target << " with Content-Length: " << value;
  22038. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22039. << target << " with Content-Length: " << value;
  22040. }
  22041. }
  22042. }
  22043. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22044. // A 400 for an unparseable request line leaves the rest of the message
  22045. // unread, so the connection must be closed rather than reused.
  22046. std::string first_response;
  22047. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22048. "Host: localhost\r\n"
  22049. "Content-Length: {len}\r\n"
  22050. "\r\n",
  22051. first_response));
  22052. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22053. }
  22054. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22055. // Same as above for a header block that fails to parse.
  22056. std::string first_response;
  22057. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22058. "Host: localhost\r\n"
  22059. "Bad Header\r\n"
  22060. "Content-Length: {len}\r\n"
  22061. "\r\n",
  22062. first_response));
  22063. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22064. }
  22065. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22066. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22067. // server must not read another request on that connection, even when the
  22068. // request had no body to drain.
  22069. std::string first_response;
  22070. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22071. "Host: localhost\r\n"
  22072. "\r\n",
  22073. first_response));
  22074. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22075. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22076. }
  22077. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22078. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22079. // must be rejected with 400 Bad Request.
  22080. Server svr;
  22081. svr.Post("/test", [&](const Request &, Response &res) {
  22082. res.set_content("ok", "text/plain");
  22083. });
  22084. thread t = thread([&] { svr.listen(HOST, PORT); });
  22085. auto se = detail::scope_exit([&] {
  22086. svr.stop();
  22087. t.join();
  22088. ASSERT_FALSE(svr.is_running());
  22089. });
  22090. svr.wait_until_ready();
  22091. // Exact "chunked"
  22092. {
  22093. auto req = "POST /test HTTP/1.1\r\n"
  22094. "Host: localhost\r\n"
  22095. "Content-Length: 5\r\n"
  22096. "Transfer-Encoding: chunked\r\n"
  22097. "Connection: close\r\n"
  22098. "\r\n"
  22099. "hello";
  22100. std::string response;
  22101. ASSERT_TRUE(send_request(1, req, &response));
  22102. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22103. response.substr(0, response.find("\r\n")));
  22104. }
  22105. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22106. {
  22107. auto req = "POST /test HTTP/1.1\r\n"
  22108. "Host: localhost\r\n"
  22109. "Content-Length: 5\r\n"
  22110. "Transfer-Encoding: gzip, chunked\r\n"
  22111. "Connection: close\r\n"
  22112. "\r\n"
  22113. "hello";
  22114. std::string response;
  22115. ASSERT_TRUE(send_request(1, req, &response));
  22116. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22117. response.substr(0, response.find("\r\n")));
  22118. }
  22119. }
  22120. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22121. Server svr;
  22122. svr.Post("/test", [&](const Request &, Response &res) {
  22123. res.set_content("ok", "text/plain");
  22124. });
  22125. thread t = thread([&] { svr.listen(HOST, PORT); });
  22126. auto se = detail::scope_exit([&] {
  22127. svr.stop();
  22128. t.join();
  22129. ASSERT_FALSE(svr.is_running());
  22130. });
  22131. svr.wait_until_ready();
  22132. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22133. // length cannot be determined, so the server must answer 400 and close
  22134. // rather than treat the request as bodyless and leave the body in the
  22135. // socket for the next request to pick up.
  22136. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22137. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22138. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22139. std::string response;
  22140. ASSERT_TRUE(send_request(1, req, &response));
  22141. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22142. response.substr(0, response.find("\r\n")))
  22143. << transfer_encoding;
  22144. }
  22145. // RFC 9110 5.3: the codings may also be split across several
  22146. // Transfer-Encoding lines, which combine in the order they were received.
  22147. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22148. // just like the single-line "chunked, gzip" above.
  22149. {
  22150. auto req = "POST /test HTTP/1.1\r\n"
  22151. "Host: localhost\r\n"
  22152. "Transfer-Encoding: chunked\r\n"
  22153. "Transfer-Encoding: gzip\r\n"
  22154. "\r\n"
  22155. "0\r\n\r\n";
  22156. std::string response;
  22157. ASSERT_TRUE(send_request(1, req, &response));
  22158. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22159. response.substr(0, response.find("\r\n")));
  22160. }
  22161. // A sequence ending in chunked stays valid.
  22162. auto req = "POST /test HTTP/1.1\r\n"
  22163. "Host: localhost\r\n"
  22164. "Transfer-Encoding: gzip, chunked\r\n"
  22165. "Connection: close\r\n"
  22166. "\r\n"
  22167. "0\r\n\r\n";
  22168. std::string response;
  22169. ASSERT_TRUE(send_request(1, req, &response));
  22170. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22171. // ...including when it is spread over several lines.
  22172. auto split_req = "POST /test HTTP/1.1\r\n"
  22173. "Host: localhost\r\n"
  22174. "Transfer-Encoding: gzip\r\n"
  22175. "Transfer-Encoding: chunked\r\n"
  22176. "Connection: close\r\n"
  22177. "\r\n"
  22178. "0\r\n\r\n";
  22179. std::string split_response;
  22180. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22181. EXPECT_EQ("HTTP/1.1 200 OK",
  22182. split_response.substr(0, split_response.find("\r\n")));
  22183. }
  22184. // Regression for issue #2450: a DELETE without Content-Length on a
  22185. // keep-alive connection must not let the post-response drain consume the
  22186. // next request's bytes.
  22187. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22188. Server svr;
  22189. std::atomic<int> delete_count(0);
  22190. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22191. delete_count++;
  22192. res.status = StatusCode::NoContent_204;
  22193. });
  22194. auto port = svr.bind_to_any_port(HOST);
  22195. thread t = thread([&] { svr.listen_after_bind(); });
  22196. auto se = detail::scope_exit([&] {
  22197. svr.stop();
  22198. t.join();
  22199. });
  22200. svr.wait_until_ready();
  22201. auto error = Error::Success;
  22202. auto sock = detail::create_client_socket(
  22203. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22204. /*connection_timeout_sec=*/2, 0,
  22205. /*read_timeout_sec=*/2, 0,
  22206. /*write_timeout_sec=*/2, 0, std::string(), error);
  22207. ASSERT_NE(INVALID_SOCKET, sock);
  22208. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22209. auto send_request_and_read_response = [&](const std::string &req,
  22210. std::string &out) -> bool {
  22211. auto sent = send(sock, req.data(), req.size(), 0);
  22212. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22213. char buf[4096];
  22214. for (;;) {
  22215. auto n = recv(sock, buf, sizeof(buf), 0);
  22216. if (n <= 0) { return !out.empty(); }
  22217. out.append(buf, static_cast<size_t>(n));
  22218. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22219. }
  22220. };
  22221. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22222. "Host: localhost\r\n"
  22223. "\r\n";
  22224. std::string resp1;
  22225. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22226. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22227. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22228. "Host: localhost\r\n"
  22229. "Connection: close\r\n"
  22230. "\r\n";
  22231. std::string resp2;
  22232. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22233. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22234. EXPECT_EQ(2, delete_count.load());
  22235. }
  22236. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22237. Server svr;
  22238. svr.Post("/ingest", [&](const Request &, Response &res,
  22239. const ContentReader &content_reader) {
  22240. auto consumed = content_reader([](const char *, size_t) { return false; });
  22241. EXPECT_FALSE(consumed);
  22242. res.status = StatusCode::Conflict_409;
  22243. res.set_header("Connection", "close");
  22244. });
  22245. auto port = svr.bind_to_any_port(HOST);
  22246. thread t = thread([&] { svr.listen_after_bind(); });
  22247. auto se = detail::scope_exit([&] {
  22248. svr.stop();
  22249. t.join();
  22250. });
  22251. svr.wait_until_ready();
  22252. auto error = Error::Success;
  22253. auto sock = detail::create_client_socket(
  22254. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22255. /*connection_timeout_sec=*/2, 0,
  22256. /*read_timeout_sec=*/1, 0,
  22257. /*write_timeout_sec=*/2, 0, std::string(), error);
  22258. ASSERT_NE(INVALID_SOCKET, sock);
  22259. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22260. std::string request = "POST /ingest HTTP/1.1\r\n"
  22261. "Host: localhost\r\n"
  22262. "Transfer-Encoding: chunked\r\n"
  22263. "\r\n"
  22264. "4\r\n"
  22265. "data\r\n";
  22266. auto sent = send(sock, request.data(), request.size(), 0);
  22267. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22268. std::string response;
  22269. ssize_t received = 0;
  22270. do {
  22271. char buf[4096];
  22272. received = recv(sock, buf, sizeof(buf), 0);
  22273. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22274. } while (received > 0);
  22275. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22276. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22277. EXPECT_EQ(0, received);
  22278. }
  22279. namespace no_proxy_test {
  22280. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22281. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22282. // calling listen().
  22283. class ScopedServer {
  22284. public:
  22285. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22286. ~ScopedServer() {
  22287. svr_.stop();
  22288. if (th_.joinable()) { th_.join(); }
  22289. }
  22290. Server &svr() { return svr_; }
  22291. int port() const { return port_; }
  22292. void listen() {
  22293. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22294. svr_.wait_until_ready();
  22295. }
  22296. private:
  22297. Server svr_;
  22298. std::thread th_;
  22299. int port_ = 0;
  22300. };
  22301. class ProxyAndTargetServers {
  22302. public:
  22303. ProxyAndTargetServers() {
  22304. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22305. proxy_hits_++;
  22306. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22307. res.set_content("via-proxy", "text/plain");
  22308. });
  22309. target_.Get(".*", [this](const Request &req, Response &res) {
  22310. target_hits_++;
  22311. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22312. res.set_content("direct", "text/plain");
  22313. });
  22314. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22315. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22316. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22317. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22318. proxy_mock_.wait_until_ready();
  22319. target_.wait_until_ready();
  22320. }
  22321. ~ProxyAndTargetServers() {
  22322. proxy_mock_.stop();
  22323. target_.stop();
  22324. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22325. if (target_thread_.joinable()) { target_thread_.join(); }
  22326. }
  22327. Server &proxy_mock() { return proxy_mock_; }
  22328. Server &target() { return target_; }
  22329. int proxy_port() const { return proxy_port_; }
  22330. int target_port() const { return target_port_; }
  22331. int proxy_hits() const { return proxy_hits_.load(); }
  22332. int target_hits() const { return target_hits_.load(); }
  22333. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22334. void reset_counters() {
  22335. proxy_hits_ = 0;
  22336. target_hits_ = 0;
  22337. last_had_proxy_authz_ = false;
  22338. }
  22339. private:
  22340. Server proxy_mock_;
  22341. Server target_;
  22342. std::thread proxy_thread_;
  22343. std::thread target_thread_;
  22344. int proxy_port_ = 0;
  22345. int target_port_ = 0;
  22346. std::atomic<int> proxy_hits_{0};
  22347. std::atomic<int> target_hits_{0};
  22348. std::atomic<bool> last_had_proxy_authz_{false};
  22349. };
  22350. inline std::unique_ptr<Client> make_client(const std::string &host,
  22351. ProxyAndTargetServers &s) {
  22352. auto cli = detail::make_unique<Client>(host, s.target_port());
  22353. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22354. cli->set_proxy("127.0.0.1", s.proxy_port());
  22355. return cli;
  22356. }
  22357. } // namespace no_proxy_test
  22358. using no_proxy_test::make_client;
  22359. using no_proxy_test::ProxyAndTargetServers;
  22360. TEST(NoProxyTest, ExactHostnameBypasses) {
  22361. ProxyAndTargetServers s;
  22362. auto cli = make_client("example.com", s);
  22363. cli->set_no_proxy({"example.com"});
  22364. auto res = cli->Get("/");
  22365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22366. EXPECT_EQ(0, s.proxy_hits());
  22367. EXPECT_EQ(1, s.target_hits());
  22368. }
  22369. TEST(NoProxyTest, SubdomainBypasses) {
  22370. ProxyAndTargetServers s;
  22371. auto cli = make_client("foo.example.com", s);
  22372. cli->set_no_proxy({"example.com"});
  22373. auto res = cli->Get("/");
  22374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22375. EXPECT_EQ(0, s.proxy_hits());
  22376. EXPECT_EQ(1, s.target_hits());
  22377. }
  22378. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22379. // Regression guard: "evilexample.com" must not be considered a subdomain
  22380. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22381. // check would let traffic bypass the proxy and leak credentials direct
  22382. // to the attacker host.
  22383. ProxyAndTargetServers s;
  22384. auto cli = make_client("evilexample.com", s);
  22385. cli->set_no_proxy({"example.com"});
  22386. auto res = cli->Get("/");
  22387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22388. EXPECT_GE(s.proxy_hits(), 1);
  22389. EXPECT_EQ(0, s.target_hits());
  22390. }
  22391. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22392. ProxyAndTargetServers s;
  22393. auto cli = make_client("example.com.evil.com", s);
  22394. cli->set_no_proxy({"example.com"});
  22395. auto res = cli->Get("/");
  22396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22397. EXPECT_GE(s.proxy_hits(), 1);
  22398. EXPECT_EQ(0, s.target_hits());
  22399. }
  22400. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22401. ProxyAndTargetServers s;
  22402. auto cli = make_client("example.com", s);
  22403. cli->set_no_proxy({".example.com"});
  22404. auto res = cli->Get("/");
  22405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22406. EXPECT_EQ(0, s.proxy_hits());
  22407. EXPECT_EQ(1, s.target_hits());
  22408. }
  22409. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22410. ProxyAndTargetServers s;
  22411. auto cli = make_client("Example.COM", s);
  22412. cli->set_no_proxy({"EXAMPLE.com"});
  22413. auto res = cli->Get("/");
  22414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22415. EXPECT_EQ(0, s.proxy_hits());
  22416. EXPECT_EQ(1, s.target_hits());
  22417. }
  22418. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22419. ProxyAndTargetServers s;
  22420. auto cli = make_client("example.com.", s);
  22421. cli->set_no_proxy({"example.com"});
  22422. auto res = cli->Get("/");
  22423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22424. EXPECT_EQ(0, s.proxy_hits());
  22425. EXPECT_EQ(1, s.target_hits());
  22426. }
  22427. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22428. // Trailing dots must be normalized on BOTH sides — host and entry.
  22429. // An implementation that only strips the host-side trailing dot would
  22430. // fail to match host "example.com" against entry "example.com." because
  22431. // a literal substring search would compare 11 chars against 12.
  22432. ProxyAndTargetServers s;
  22433. auto cli = make_client("example.com", s);
  22434. cli->set_no_proxy({"example.com."});
  22435. auto res = cli->Get("/");
  22436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22437. EXPECT_EQ(0, s.proxy_hits());
  22438. EXPECT_EQ(1, s.target_hits());
  22439. }
  22440. TEST(NoProxyTest, WildcardBypassesEverything) {
  22441. ProxyAndTargetServers s;
  22442. auto cli = make_client("anything.invalid.test", s);
  22443. cli->set_no_proxy({"*"});
  22444. auto res = cli->Get("/");
  22445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22446. EXPECT_EQ(0, s.proxy_hits());
  22447. EXPECT_EQ(1, s.target_hits());
  22448. }
  22449. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22450. ProxyAndTargetServers s;
  22451. Client cli("127.0.0.1", s.target_port());
  22452. cli.set_proxy("127.0.0.1", s.proxy_port());
  22453. cli.set_no_proxy({"127.0.0.1"});
  22454. auto res = cli.Get("/");
  22455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22456. EXPECT_EQ(0, s.proxy_hits());
  22457. EXPECT_EQ(1, s.target_hits());
  22458. }
  22459. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22460. ProxyAndTargetServers s;
  22461. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22462. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22463. cli.set_proxy("127.0.0.1", s.proxy_port());
  22464. cli.set_no_proxy({"::1"});
  22465. auto res = cli.Get("/");
  22466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22467. EXPECT_EQ(0, s.proxy_hits());
  22468. EXPECT_EQ(1, s.target_hits());
  22469. }
  22470. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22471. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22472. // must still be recognized as IPv6 for CIDR matching. Implementations
  22473. // that detect IPv6 only when the host begins with '[' would parse the
  22474. // host as a hostname and miss the match.
  22475. ProxyAndTargetServers s;
  22476. Client cli("fe80::1", s.target_port());
  22477. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22478. cli.set_proxy("127.0.0.1", s.proxy_port());
  22479. cli.set_no_proxy({"fe80::/10"});
  22480. auto res = cli.Get("/");
  22481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22482. EXPECT_EQ(0, s.proxy_hits());
  22483. EXPECT_EQ(1, s.target_hits());
  22484. }
  22485. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22486. ProxyAndTargetServers s;
  22487. Client cli("::1", s.target_port());
  22488. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22489. cli.set_proxy("127.0.0.1", s.proxy_port());
  22490. cli.set_no_proxy({"[::1]"});
  22491. auto res = cli.Get("/");
  22492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22493. EXPECT_EQ(0, s.proxy_hits());
  22494. EXPECT_EQ(1, s.target_hits());
  22495. }
  22496. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22497. ProxyAndTargetServers s;
  22498. Client cli("fe80::1", s.target_port());
  22499. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22500. cli.set_proxy("127.0.0.1", s.proxy_port());
  22501. cli.set_no_proxy({"[fe80::]/10"});
  22502. auto res = cli.Get("/");
  22503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22504. EXPECT_EQ(0, s.proxy_hits());
  22505. EXPECT_EQ(1, s.target_hits());
  22506. }
  22507. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22508. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22509. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22510. // tricks via address-family conversion.
  22511. ProxyAndTargetServers s;
  22512. Client cli("::ffff:127.0.0.1", s.target_port());
  22513. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22514. cli.set_proxy("127.0.0.1", s.proxy_port());
  22515. cli.set_no_proxy({"127.0.0.1"});
  22516. auto res = cli.Get("/");
  22517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22518. EXPECT_GE(s.proxy_hits(), 1);
  22519. EXPECT_EQ(0, s.target_hits());
  22520. }
  22521. TEST(NoProxyTest, IPv4CidrMatch) {
  22522. ProxyAndTargetServers s;
  22523. Client cli("127.0.0.1", s.target_port());
  22524. cli.set_proxy("127.0.0.1", s.proxy_port());
  22525. cli.set_no_proxy({"127.0.0.0/8"});
  22526. auto res = cli.Get("/");
  22527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22528. EXPECT_EQ(0, s.proxy_hits());
  22529. EXPECT_EQ(1, s.target_hits());
  22530. }
  22531. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22532. ProxyAndTargetServers s;
  22533. Client cli("127.0.0.1", s.target_port());
  22534. cli.set_proxy("127.0.0.1", s.proxy_port());
  22535. cli.set_no_proxy({"10.0.0.0/8"});
  22536. auto res = cli.Get("/");
  22537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22538. EXPECT_GE(s.proxy_hits(), 1);
  22539. EXPECT_EQ(0, s.target_hits());
  22540. }
  22541. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22542. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22543. // IPv4 target matches.
  22544. ProxyAndTargetServers s;
  22545. Client cli("127.0.0.1", s.target_port());
  22546. cli.set_proxy("127.0.0.1", s.proxy_port());
  22547. cli.set_no_proxy({"0.0.0.0/0"});
  22548. auto res = cli.Get("/");
  22549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22550. EXPECT_EQ(0, s.proxy_hits());
  22551. EXPECT_EQ(1, s.target_hits());
  22552. }
  22553. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22554. ProxyAndTargetServers s;
  22555. Client cli("127.0.0.1", s.target_port());
  22556. cli.set_proxy("127.0.0.1", s.proxy_port());
  22557. cli.set_no_proxy({"127.0.0.1"});
  22558. auto res = cli.Get("/");
  22559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22560. EXPECT_EQ(0, s.proxy_hits());
  22561. EXPECT_EQ(1, s.target_hits());
  22562. }
  22563. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22564. ProxyAndTargetServers s;
  22565. Client cli("127.0.0.1", s.target_port());
  22566. cli.set_proxy("127.0.0.1", s.proxy_port());
  22567. cli.set_no_proxy({"127.0.0.0/33"});
  22568. auto res = cli.Get("/");
  22569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22570. EXPECT_GE(s.proxy_hits(), 1);
  22571. EXPECT_EQ(0, s.target_hits());
  22572. }
  22573. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22574. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22575. ProxyAndTargetServers s;
  22576. Client cli("127.0.0.1", s.target_port());
  22577. cli.set_proxy("127.0.0.1", s.proxy_port());
  22578. cli.set_no_proxy({"127.0.0.1/"});
  22579. auto res = cli.Get("/");
  22580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22581. EXPECT_GE(s.proxy_hits(), 1);
  22582. EXPECT_EQ(0, s.target_hits());
  22583. }
  22584. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22585. ProxyAndTargetServers s;
  22586. auto cli = make_client("internal.corp", s);
  22587. cli->set_proxy_basic_auth("u", "p");
  22588. cli->set_no_proxy({"internal.corp"});
  22589. auto res = cli->Get("/");
  22590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22591. EXPECT_EQ(1, s.target_hits());
  22592. EXPECT_EQ(0, s.proxy_hits());
  22593. EXPECT_FALSE(s.last_had_proxy_authz())
  22594. << "Proxy-Authorization must not be sent direct to the target";
  22595. }
  22596. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22597. ProxyAndTargetServers s;
  22598. auto cli = make_client("public.example", s);
  22599. cli->set_proxy_basic_auth("u", "p");
  22600. cli->set_no_proxy({"internal.corp"}); // does not match
  22601. auto res = cli->Get("/");
  22602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22603. EXPECT_GE(s.proxy_hits(), 1);
  22604. EXPECT_TRUE(s.last_had_proxy_authz());
  22605. }
  22606. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22607. ProxyAndTargetServers s;
  22608. auto cli = make_client("anything.test", s);
  22609. auto res = cli->Get("/");
  22610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22611. EXPECT_GE(s.proxy_hits(), 1);
  22612. EXPECT_EQ(0, s.target_hits());
  22613. }
  22614. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22615. ProxyAndTargetServers s;
  22616. auto cli = make_client("example.com", s);
  22617. cli->set_no_proxy({"example.com:8080"});
  22618. auto res = cli->Get("/");
  22619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22620. EXPECT_GE(s.proxy_hits(), 1);
  22621. EXPECT_EQ(0, s.target_hits());
  22622. }
  22623. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22624. ProxyAndTargetServers s;
  22625. auto cli = make_client("anything.test", s);
  22626. cli->set_no_proxy({"", " ", "\t"});
  22627. auto res = cli->Get("/");
  22628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22629. EXPECT_GE(s.proxy_hits(), 1);
  22630. EXPECT_EQ(0, s.target_hits());
  22631. }
  22632. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22633. // An entry with leading/trailing whitespace must still match — env-style
  22634. // values are commonly pasted with stray spaces and an implementation
  22635. // that feeds the raw token directly to inet_pton would fail to match
  22636. // valid CIDRs because of the spaces.
  22637. ProxyAndTargetServers s;
  22638. Client cli("127.0.0.1", s.target_port());
  22639. cli.set_proxy("127.0.0.1", s.proxy_port());
  22640. cli.set_no_proxy({" 127.0.0.0/8 "});
  22641. auto res = cli.Get("/");
  22642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22643. EXPECT_EQ(0, s.proxy_hits());
  22644. EXPECT_EQ(1, s.target_hits());
  22645. }
  22646. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22647. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22648. // go direct and must NOT carry Proxy-Authorization.
  22649. std::atomic<int> proxy_hits{0};
  22650. std::atomic<int> target_hits{0};
  22651. std::atomic<bool> target_saw_authz{false};
  22652. no_proxy_test::ScopedServer proxy_mock, target;
  22653. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22654. proxy_hits++;
  22655. res.status = 302;
  22656. res.set_header("Location", "http://127.0.0.1:" +
  22657. std::to_string(target.port()) + "/landed");
  22658. });
  22659. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22660. target_hits++;
  22661. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22662. res.set_content("direct", "text/plain");
  22663. });
  22664. proxy_mock.listen();
  22665. target.listen();
  22666. Client cli("public.example", target.port());
  22667. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22668. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22669. cli.set_proxy_basic_auth("u", "p");
  22670. cli.set_no_proxy({"127.0.0.1"});
  22671. cli.set_follow_location(true);
  22672. auto res = cli.Get("/redir");
  22673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22674. EXPECT_GE(proxy_hits.load(), 1);
  22675. EXPECT_GE(target_hits.load(), 1);
  22676. EXPECT_FALSE(target_saw_authz.load());
  22677. }
  22678. #ifdef CPPHTTPLIB_SSL_ENABLED
  22679. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22680. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22681. // proxy creds would be sent to the (possibly hostile) origin.
  22682. std::atomic<int> target_hits{0};
  22683. std::atomic<bool> target_saw_proxy_authz{false};
  22684. no_proxy_test::ScopedServer target;
  22685. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22686. target_hits++;
  22687. if (req.has_header("Proxy-Authorization")) {
  22688. target_saw_proxy_authz = true;
  22689. }
  22690. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22691. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22692. "nonce=\"abc\", algorithm=MD5");
  22693. });
  22694. target.listen();
  22695. // The proxy address is set to the target's port: the bypass MUST kick in;
  22696. // if it doesn't, the test still routes "via proxy" to the same server and
  22697. // the Proxy-Authorization assertion below catches the leak.
  22698. Client cli("evil.example", target.port());
  22699. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22700. cli.set_proxy("127.0.0.1", target.port());
  22701. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22702. cli.set_no_proxy({"evil.example"});
  22703. auto res = cli.Get("/x");
  22704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22705. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22706. EXPECT_EQ(1, target_hits.load());
  22707. EXPECT_FALSE(target_saw_proxy_authz.load());
  22708. }
  22709. #endif
  22710. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22711. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22712. std::atomic<int> proxy_hits{0};
  22713. std::atomic<int> bypass_hits{0};
  22714. std::atomic<bool> proxy_saw_c_url{false};
  22715. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22716. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22717. proxy_hits++;
  22718. if (req.path.find("/start") != std::string::npos) {
  22719. res.status = 302;
  22720. res.set_header("Location", "http://127.0.0.1:" +
  22721. std::to_string(bypass_server.port()) +
  22722. "/middle");
  22723. return;
  22724. }
  22725. if (req.path.find("/end") != std::string::npos) {
  22726. proxy_saw_c_url = true;
  22727. res.set_content("c-via-proxy", "text/plain");
  22728. return;
  22729. }
  22730. res.set_content("unexpected", "text/plain");
  22731. });
  22732. // public.example's "advertised" port is arbitrary (the request never lands
  22733. // there — it goes through the proxy), but use a dynamic value to stay
  22734. // friendly with sharded parallel runs.
  22735. int public_port = bypass_server.port();
  22736. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22737. bypass_hits++;
  22738. res.status = 302;
  22739. res.set_header("Location", "http://public.example:" +
  22740. std::to_string(public_port) + "/end");
  22741. });
  22742. proxy_mock.listen();
  22743. bypass_server.listen();
  22744. Client cli("public.example", public_port);
  22745. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22746. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22747. cli.set_no_proxy({"127.0.0.1"});
  22748. cli.set_follow_location(true);
  22749. auto res = cli.Get("/start");
  22750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22751. EXPECT_EQ(StatusCode::OK_200, res->status);
  22752. EXPECT_EQ("c-via-proxy", res->body);
  22753. EXPECT_GE(proxy_hits.load(), 2);
  22754. EXPECT_GE(bypass_hits.load(), 1);
  22755. EXPECT_TRUE(proxy_saw_c_url.load());
  22756. }
  22757. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22758. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22759. // request reconnects to the correct endpoint.
  22760. std::atomic<int> proxy_hits{0};
  22761. std::atomic<int> target_hits{0};
  22762. no_proxy_test::ScopedServer proxy_mock, target;
  22763. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22764. proxy_hits++;
  22765. res.set_content("via-proxy", "text/plain");
  22766. });
  22767. target.svr().Get(".*", [&](const Request &, Response &res) {
  22768. target_hits++;
  22769. res.set_content("direct", "text/plain");
  22770. });
  22771. proxy_mock.listen();
  22772. target.listen();
  22773. Client cli("public.example", target.port());
  22774. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22775. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22776. cli.set_keep_alive(true);
  22777. auto res1 = cli.Get("/a");
  22778. ASSERT_TRUE(res1);
  22779. EXPECT_EQ("via-proxy", res1->body);
  22780. EXPECT_EQ(1, proxy_hits.load());
  22781. EXPECT_EQ(0, target_hits.load());
  22782. cli.set_no_proxy({"public.example"});
  22783. auto res2 = cli.Get("/b");
  22784. ASSERT_TRUE(res2);
  22785. EXPECT_EQ("direct", res2->body);
  22786. EXPECT_EQ(1, proxy_hits.load());
  22787. EXPECT_EQ(1, target_hits.load());
  22788. }
  22789. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22790. namespace proxy_tunnel_test {
  22791. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22792. class ScopedSSLServer {
  22793. public:
  22794. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22795. port_ = svr_.bind_to_any_port("127.0.0.1");
  22796. }
  22797. ~ScopedSSLServer() {
  22798. svr_.stop();
  22799. if (th_.joinable()) { th_.join(); }
  22800. }
  22801. SSLServer &svr() { return svr_; }
  22802. int port() const { return port_; }
  22803. void listen() {
  22804. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22805. svr_.wait_until_ready();
  22806. }
  22807. private:
  22808. SSLServer svr_;
  22809. std::thread th_;
  22810. int port_ = 0;
  22811. };
  22812. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22813. class ScopedConnectProxy {
  22814. public:
  22815. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22816. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22817. if (listen_fd_ < 0) { return; }
  22818. int yes = 1;
  22819. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22820. sockaddr_in a{};
  22821. a.sin_family = AF_INET;
  22822. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22823. a.sin_port = 0;
  22824. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22825. return;
  22826. }
  22827. socklen_t alen = sizeof(a);
  22828. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22829. 0) {
  22830. return;
  22831. }
  22832. port_ = ntohs(a.sin_port);
  22833. if (::listen(listen_fd_, 1) != 0) { return; }
  22834. th_ = std::thread([this] { run(); });
  22835. }
  22836. ~ScopedConnectProxy() {
  22837. stop_ = true;
  22838. if (listen_fd_ >= 0) {
  22839. ::shutdown(listen_fd_, SHUT_RDWR);
  22840. ::close(listen_fd_);
  22841. }
  22842. if (th_.joinable()) { th_.join(); }
  22843. }
  22844. int port() const { return port_; }
  22845. int connect_hits() const { return connect_hits_.load(); }
  22846. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22847. std::string connect_request() const {
  22848. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22849. return connect_request_;
  22850. }
  22851. private:
  22852. void run() {
  22853. while (!stop_.load()) {
  22854. fd_set rfds;
  22855. FD_ZERO(&rfds);
  22856. FD_SET(listen_fd_, &rfds);
  22857. timeval tv{0, 100 * 1000};
  22858. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22859. if (sel <= 0) { continue; }
  22860. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22861. if (client_fd < 0) { continue; }
  22862. std::string req;
  22863. char buf[2048];
  22864. while (req.find("\r\n\r\n") == std::string::npos) {
  22865. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22866. if (n <= 0) { break; }
  22867. req.append(buf, static_cast<size_t>(n));
  22868. }
  22869. if (req.compare(0, 7, "CONNECT") != 0) {
  22870. ::close(client_fd);
  22871. continue;
  22872. }
  22873. connect_hits_++;
  22874. {
  22875. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22876. connect_request_ = req;
  22877. }
  22878. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22879. ::send(client_fd, ok, std::strlen(ok), 0);
  22880. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22881. sockaddr_in o{};
  22882. o.sin_family = AF_INET;
  22883. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22884. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22885. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22886. 0) {
  22887. ::close(client_fd);
  22888. ::close(origin_fd);
  22889. continue;
  22890. }
  22891. auto forward = [](int from, int to) {
  22892. char b[8192];
  22893. for (;;) {
  22894. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22895. if (n <= 0) { break; }
  22896. ssize_t off = 0;
  22897. while (off < n) {
  22898. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22899. if (s <= 0) {
  22900. off = n;
  22901. break;
  22902. }
  22903. off += s;
  22904. }
  22905. }
  22906. ::shutdown(to, SHUT_WR);
  22907. };
  22908. std::thread t1([&] { forward(client_fd, origin_fd); });
  22909. std::thread t2([&] { forward(origin_fd, client_fd); });
  22910. t1.join();
  22911. t2.join();
  22912. ::close(client_fd);
  22913. ::close(origin_fd);
  22914. }
  22915. }
  22916. int forward_port_ = -1;
  22917. int listen_fd_ = -1;
  22918. int port_ = 0;
  22919. std::thread th_;
  22920. std::atomic<bool> stop_{false};
  22921. std::atomic<int> connect_hits_{0};
  22922. mutable std::mutex connect_request_mutex_;
  22923. std::string connect_request_;
  22924. };
  22925. // Sends one request through the CONNECT proxy to the TLS origin with a
  22926. // credential configured for each hop, and checks that each credential reaches
  22927. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22928. // origin's (every header in origin_headers) on the tunnelled request.
  22929. void CredentialsStayWithTheirHop(
  22930. const std::function<void(SSLClient &)> &set_credentials,
  22931. const std::string &scheme,
  22932. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22933. std::atomic<int> origin_hits{0};
  22934. std::atomic<bool> origin_saw_proxy_authz{false};
  22935. std::atomic<bool> origin_saw_headers{false};
  22936. ScopedSSLServer origin;
  22937. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22938. origin_hits++;
  22939. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22940. origin_saw_headers =
  22941. std::all_of(origin_headers.begin(), origin_headers.end(),
  22942. [&](const std::string &h) { return req.has_header(h); });
  22943. res.set_content("ok", "text/plain");
  22944. });
  22945. origin.listen();
  22946. ScopedConnectProxy proxy(origin.port());
  22947. ASSERT_NE(0, proxy.port());
  22948. // Pinned to 127.0.0.1 for the same reason as the test below.
  22949. SSLClient cli("127.0.0.1", origin.port());
  22950. cli.enable_server_certificate_verification(false);
  22951. cli.set_proxy("127.0.0.1", proxy.port());
  22952. set_credentials(cli);
  22953. auto res = cli.Get("/x");
  22954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22955. EXPECT_EQ(StatusCode::OK_200, res->status);
  22956. EXPECT_EQ(1, origin_hits.load());
  22957. EXPECT_EQ(1, proxy.connect_hits());
  22958. EXPECT_TRUE(origin_saw_headers.load());
  22959. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22960. << "Proxy-Authorization must not be sent inside the tunnel";
  22961. auto connect_req = proxy.connect_request();
  22962. EXPECT_NE(std::string::npos,
  22963. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22964. for (const auto &h : origin_headers) {
  22965. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22966. << h << " must not be sent to the proxy on CONNECT";
  22967. }
  22968. }
  22969. } // namespace proxy_tunnel_test
  22970. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22971. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22972. [](SSLClient &cli) {
  22973. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22974. cli.set_basic_auth("origin-user", "origin-pass");
  22975. },
  22976. "Basic");
  22977. }
  22978. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22979. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22980. [](SSLClient &cli) {
  22981. cli.set_proxy_bearer_token_auth("proxy-token");
  22982. cli.set_bearer_token_auth("origin-token");
  22983. },
  22984. "Bearer");
  22985. }
  22986. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22987. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22988. [](SSLClient &cli) {
  22989. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22990. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22991. {"Cookie", "sid=origin-session"},
  22992. {"X-Api-Key", "origin-key"}});
  22993. },
  22994. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22995. }
  22996. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22997. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22998. // retry; otherwise proxy creds would be sent to the origin.
  22999. std::atomic<int> origin_hits{0};
  23000. std::atomic<bool> origin_saw_proxy_authz{false};
  23001. proxy_tunnel_test::ScopedSSLServer origin;
  23002. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23003. origin_hits++;
  23004. if (req.has_header("Proxy-Authorization")) {
  23005. origin_saw_proxy_authz = true;
  23006. }
  23007. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23008. res.set_header("Proxy-Authenticate",
  23009. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23010. "algorithm=MD5");
  23011. });
  23012. origin.listen();
  23013. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23014. ASSERT_NE(0, proxy.port());
  23015. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23016. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23017. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23018. // and answer with its own status, making this test flaky.
  23019. SSLClient cli("127.0.0.1", origin.port());
  23020. cli.enable_server_certificate_verification(false);
  23021. cli.set_proxy("127.0.0.1", proxy.port());
  23022. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23023. auto res = cli.Get("/x");
  23024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23025. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23026. EXPECT_EQ(1, origin_hits.load());
  23027. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23028. EXPECT_EQ(1, proxy.connect_hits());
  23029. }
  23030. #endif