test.cc 940 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969
  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, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  1058. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*");
  1061. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1470. // Server::read_content() keeps a FormFields::iterator alive across the
  1471. // content callbacks that fill the part it points at. The container is
  1472. // vector-backed, so a later emplace can reallocate and invalidate an older
  1473. // iterator; 64 parts grow the vector through seven reallocations, which
  1474. // checks that every part's content still lands in its own entry.
  1475. const size_t part_count = 64;
  1476. // One formula for both the parts sent and the values expected back, so the
  1477. // two cannot drift apart.
  1478. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1479. auto content_of = [](size_t i) {
  1480. return std::string(64, static_cast<char>('a' + (i % 26)));
  1481. };
  1482. Server svr;
  1483. std::vector<std::pair<std::string, std::string>> received;
  1484. svr.Post("/many", [&](const Request &req, Response &res) {
  1485. for (const auto &field : req.form.fields) {
  1486. received.emplace_back(field.first, field.second.content);
  1487. }
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. UploadFormDataItems items;
  1499. for (size_t i = 0; i < part_count; i++) {
  1500. items.push_back({name_of(i), content_of(i), "", ""});
  1501. }
  1502. Client cli(HOST, port);
  1503. auto res = cli.Post("/many", items);
  1504. ASSERT_TRUE(res);
  1505. ASSERT_EQ(part_count, received.size());
  1506. for (size_t i = 0; i < part_count; i++) {
  1507. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1508. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1509. }
  1510. }
  1511. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1512. string content_type = "multipart/form-data; boundary=something";
  1513. string boundary;
  1514. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1515. EXPECT_TRUE(ret);
  1516. EXPECT_EQ(boundary, "something");
  1517. }
  1518. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1519. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1520. string boundary;
  1521. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1522. EXPECT_TRUE(ret);
  1523. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1524. }
  1525. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1526. string content_type =
  1527. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1528. string boundary;
  1529. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1530. EXPECT_TRUE(ret);
  1531. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1534. string content_type =
  1535. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1536. string boundary;
  1537. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1538. EXPECT_TRUE(ret);
  1539. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1542. const string boundary(70, 'a');
  1543. string content_type = "multipart/form-data; boundary=" + boundary;
  1544. string parsed;
  1545. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(parsed, boundary);
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1550. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1551. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1552. string parsed;
  1553. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1554. EXPECT_FALSE(ret);
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1557. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1558. // is 72 characters on the wire and still valid.
  1559. const string boundary(70, 'a');
  1560. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1561. string parsed;
  1562. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1563. EXPECT_EQ(parsed, boundary);
  1564. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1565. parsed.clear();
  1566. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1569. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1570. // The parameter parser must not treat that '=' as the key/value separator.
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1573. "charset=UTF-8";
  1574. string parsed;
  1575. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1576. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1579. // A ';' inside the quoted-string is part of the value, not a parameter
  1580. // separator, so it must not truncate the boundary.
  1581. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1582. string parsed;
  1583. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1584. EXPECT_EQ(parsed, "a;b");
  1585. }
  1586. TEST(ParseDispositionParamsTest, QuotedValues) {
  1587. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1588. // ';' and '=' are ordinary characters inside one.
  1589. struct {
  1590. const char *value;
  1591. std::vector<std::pair<const char *, const char *>> expected;
  1592. } cases[] = {
  1593. {"name=\"file1\"; filename=\"a.txt\"",
  1594. {{"name", "file1"}, {"filename", "a.txt"}}},
  1595. // Whitespace around '=' and ';' is still trimmed
  1596. {"name=\"file2\" ;filename = \"a.html\"",
  1597. {{"name", "file2"}, {"filename", "a.html"}}},
  1598. // '=' inside the value used to leave only the text after the last one
  1599. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1600. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1601. {"name=\"x=y\"", {{"name", "x=y"}}},
  1602. // ';' inside the value used to truncate the pair and leave a bogus one
  1603. {"name=\"file3\"; filename=\"a;b.txt\"",
  1604. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1605. // An unquoted value keeps working, and so does filename*
  1606. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1607. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1608. // A parameter with no key is dropped rather than turned into one whose
  1609. // key is the value
  1610. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1611. // An escaped quote does not end the value
  1612. {"name=\"a\\\"; filename=evil.php\"",
  1613. {{"name", "a\"; filename=evil.php"}}},
  1614. // Other backslashes, as in a Windows path, are kept
  1615. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1616. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1617. };
  1618. for (const auto &c : cases) {
  1619. Params params;
  1620. detail::parse_disposition_params(c.value, params);
  1621. for (const auto &kv : c.expected) {
  1622. auto it = params.find(kv.first);
  1623. ASSERT_NE(it, params.end())
  1624. << "value: " << c.value << ", key: " << kv.first;
  1625. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1626. }
  1627. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1628. }
  1629. }
  1630. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1631. Server svr;
  1632. std::string filename;
  1633. std::string content;
  1634. svr.Post("/upload", [&](const Request &req, Response &) {
  1635. const auto &file = req.form.get_file("file");
  1636. filename = file.filename;
  1637. content = file.content;
  1638. });
  1639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. thread.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. std::string body = "--B\r\n"
  1647. "Content-Disposition: form-data; name=\"file\"; "
  1648. "filename=\"a.txt\"\r\n"
  1649. "Content-Type: text/plain\r\n"
  1650. "\r\n"
  1651. "hello\r\n"
  1652. "--B--\r\n";
  1653. Client cli(HOST, PORT);
  1654. auto res = cli.Post(
  1655. "/upload",
  1656. [&](size_t offset, DataSink &sink) {
  1657. if (offset < body.size()) {
  1658. sink.write(&body[offset], 1);
  1659. } else {
  1660. sink.done();
  1661. }
  1662. return true;
  1663. },
  1664. "multipart/form-data; boundary=B");
  1665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1666. EXPECT_EQ(StatusCode::OK_200, res->status);
  1667. EXPECT_EQ("a.txt", filename);
  1668. EXPECT_EQ("hello", content);
  1669. }
  1670. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1671. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1672. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1673. Server svr;
  1674. std::string field_value, file_name, file_filename;
  1675. bool has_field = false, has_file = false;
  1676. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1677. has_field = req.form.has_field("x=y");
  1678. field_value = req.form.get_field("x=y");
  1679. has_file = req.form.has_file("file1");
  1680. const auto &file = req.form.get_file("file1");
  1681. file_name = file.name;
  1682. file_filename = file.filename;
  1683. res.set_content("ok", "text/plain");
  1684. });
  1685. auto port = svr.bind_to_any_port(HOST);
  1686. thread t = thread([&] { svr.listen_after_bind(); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. t.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. UploadFormDataItems items = {
  1694. {"x=y", "field-value", "", ""},
  1695. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1696. };
  1697. Client cli(HOST, port);
  1698. auto res = cli.Post("/quoted", items);
  1699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1700. ASSERT_EQ(StatusCode::OK_200, res->status);
  1701. EXPECT_TRUE(has_field);
  1702. EXPECT_EQ("field-value", field_value);
  1703. EXPECT_TRUE(has_file);
  1704. EXPECT_EQ("file1", file_name);
  1705. EXPECT_EQ("a;b=report.pdf", file_filename);
  1706. }
  1707. TEST(GetHeaderValueTest, DefaultValue) {
  1708. Headers headers = {{"Dummy", "Dummy"}};
  1709. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1710. EXPECT_STREQ("text/plain", val);
  1711. }
  1712. TEST(GetHeaderValueTest, DefaultValueInt) {
  1713. Headers headers = {{"Dummy", "Dummy"}};
  1714. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1715. EXPECT_EQ(100ull, val);
  1716. }
  1717. TEST(GetHeaderValueTest, RegularValue) {
  1718. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1719. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1720. EXPECT_STREQ("text/html", val);
  1721. }
  1722. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1723. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1724. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1725. EXPECT_STREQ("text/html", val);
  1726. }
  1727. TEST(GetHeaderValueTest, SetContent) {
  1728. Response res;
  1729. res.set_content("html", "text/html");
  1730. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1731. res.set_content("text", "text/plain");
  1732. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1733. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1734. }
  1735. TEST(GetHeaderValueTest, RegularValueInt) {
  1736. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1737. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1738. EXPECT_EQ(100ull, val);
  1739. }
  1740. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1741. Headers headers = {{"Content-Length", "x"}};
  1742. auto is_invalid_value = false;
  1743. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1744. is_invalid_value);
  1745. EXPECT_EQ(0ull, val);
  1746. EXPECT_TRUE(is_invalid_value);
  1747. }
  1748. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1749. // An all-digit value that overflows size_t must be reported as invalid, not
  1750. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1751. // a large length to a small one on 32-bit builds, leaving the framing length
  1752. // wrong while is_invalid_value stayed false.
  1753. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1754. auto is_invalid_value = false;
  1755. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1756. is_invalid_value);
  1757. EXPECT_TRUE(is_invalid_value);
  1758. // A well-formed length is unaffected.
  1759. Headers ok = {{"Content-Length", "1234"}};
  1760. is_invalid_value = false;
  1761. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1762. is_invalid_value);
  1763. EXPECT_EQ(1234ull, val);
  1764. EXPECT_FALSE(is_invalid_value);
  1765. }
  1766. TEST(GetHeaderValueTest, Range) {
  1767. {
  1768. Headers headers = {make_range_header({{1, -1}})};
  1769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1770. EXPECT_STREQ("bytes=1-", val);
  1771. }
  1772. {
  1773. Headers headers = {make_range_header({{-1, 1}})};
  1774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1775. EXPECT_STREQ("bytes=-1", val);
  1776. }
  1777. {
  1778. Headers headers = {make_range_header({{1, 10}})};
  1779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1780. EXPECT_STREQ("bytes=1-10", val);
  1781. }
  1782. {
  1783. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1785. EXPECT_STREQ("bytes=1-10, 100-", val);
  1786. }
  1787. {
  1788. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1789. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1790. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1791. }
  1792. {
  1793. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1794. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1795. EXPECT_STREQ("bytes=0-0, -1", val);
  1796. }
  1797. }
  1798. TEST(BearerTokenAuthTest, SchemeValidation) {
  1799. // A value shorter than "Bearer " must not throw from the fixed-length
  1800. // substr, and a non-Bearer scheme must not be reported as a token.
  1801. struct {
  1802. const char *value;
  1803. const char *expected;
  1804. } cases[] = {
  1805. {"x", ""},
  1806. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1807. {"Bearer abc123", "abc123"},
  1808. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1809. };
  1810. for (const auto &c : cases) {
  1811. Request req;
  1812. req.set_header("Authorization", c.value);
  1813. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1814. }
  1815. }
  1816. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1817. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1818. // to depend on the standard library (libstdc++ handed back duplicates in
  1819. // reverse insertion order, libc++ in insertion order).
  1820. Request req;
  1821. req.set_header("Accept-Encoding", "gzip");
  1822. req.set_header("Accept-Encoding", "deflate");
  1823. req.set_header("Accept-Encoding", "br");
  1824. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1825. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1826. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1827. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1828. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1829. }
  1830. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1831. Request req;
  1832. req.set_header("X-Test", "only");
  1833. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1834. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1835. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1836. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1837. }
  1838. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1839. Request req;
  1840. req.set_header("X-First", "1");
  1841. req.set_header("X-Test", "2");
  1842. req.params.emplace("first", "1");
  1843. req.params.emplace("test", "2");
  1844. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1845. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1846. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1847. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1848. // The second one is negative when read as a signed value
  1849. const auto max_id = (std::numeric_limits<size_t>::max)();
  1850. for (auto id : {max_id / 2, max_id}) {
  1851. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1852. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1853. EXPECT_EQ("", req.get_param_value("test", id));
  1854. EXPECT_EQ("", req.form.get_field("test", id));
  1855. EXPECT_EQ("", req.form.get_file("test", id).content);
  1856. }
  1857. }
  1858. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1859. Headers headers;
  1860. headers.emplace("Host", "example.com");
  1861. headers.emplace("Accept-Encoding", "gzip");
  1862. headers.emplace("User-Agent", "test");
  1863. headers.emplace("Accept-Encoding", "deflate");
  1864. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1865. "Accept-Encoding=deflate ",
  1866. entries_to_string(headers));
  1867. }
  1868. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1869. Headers headers = {{"Content-Type", "text/html"},
  1870. {"CONTENT-TYPE", "text/xml"}};
  1871. EXPECT_EQ(2U, headers.count("content-type"));
  1872. auto it = headers.find("content-type");
  1873. ASSERT_TRUE(it != headers.end());
  1874. EXPECT_EQ("text/html", it->second);
  1875. }
  1876. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1877. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1878. // drop only those fields and leave everything positioned between them.
  1879. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1880. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1881. auto rng = headers.equal_range("a");
  1882. headers.erase(rng.first, rng.second);
  1883. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1884. }
  1885. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1886. Headers headers = {
  1887. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1888. EXPECT_EQ(3U, headers.erase("A"));
  1889. EXPECT_EQ(0U, headers.count("A"));
  1890. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1891. }
  1892. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1893. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1894. headers.emplace_front("Host", "example.com");
  1895. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1896. entries_to_string(headers));
  1897. }
  1898. TEST(ParseHeaderValueTest, Range) {
  1899. {
  1900. Ranges ranges;
  1901. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1902. EXPECT_TRUE(ret);
  1903. EXPECT_EQ(1u, ranges.size());
  1904. EXPECT_EQ(1u, ranges[0].first);
  1905. EXPECT_EQ(-1, ranges[0].second);
  1906. }
  1907. {
  1908. Ranges ranges;
  1909. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1910. EXPECT_TRUE(ret);
  1911. EXPECT_EQ(1u, ranges.size());
  1912. EXPECT_EQ(-1, ranges[0].first);
  1913. EXPECT_EQ(1u, ranges[0].second);
  1914. }
  1915. {
  1916. Ranges ranges;
  1917. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1918. EXPECT_TRUE(ret);
  1919. EXPECT_EQ(1u, ranges.size());
  1920. EXPECT_EQ(1u, ranges[0].first);
  1921. EXPECT_EQ(10u, ranges[0].second);
  1922. }
  1923. {
  1924. Ranges ranges;
  1925. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1926. EXPECT_FALSE(ret);
  1927. }
  1928. {
  1929. Ranges ranges;
  1930. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1931. EXPECT_TRUE(ret);
  1932. EXPECT_EQ(2u, ranges.size());
  1933. EXPECT_EQ(1u, ranges[0].first);
  1934. EXPECT_EQ(10u, ranges[0].second);
  1935. EXPECT_EQ(100u, ranges[1].first);
  1936. EXPECT_EQ(-1, ranges[1].second);
  1937. }
  1938. {
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ(3u, ranges.size());
  1944. EXPECT_EQ(1u, ranges[0].first);
  1945. EXPECT_EQ(10u, ranges[0].second);
  1946. EXPECT_EQ(100u, ranges[1].first);
  1947. EXPECT_EQ(200u, ranges[1].second);
  1948. EXPECT_EQ(300u, ranges[2].first);
  1949. EXPECT_EQ(400u, ranges[2].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1962. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1963. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1964. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1965. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1966. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1967. EXPECT_FALSE(
  1968. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1969. EXPECT_TRUE(ranges.empty());
  1970. }
  1971. {
  1972. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1973. // remainder of the representation, so it stays accepted.
  1974. Ranges ranges;
  1975. auto ret =
  1976. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1977. EXPECT_TRUE(ret);
  1978. ASSERT_EQ(1u, ranges.size());
  1979. EXPECT_EQ(0, ranges[0].first);
  1980. EXPECT_EQ(-1, ranges[0].second);
  1981. }
  1982. // RFC 9110 14.1: range unit names are case-insensitive.
  1983. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1984. Ranges ranges;
  1985. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1986. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1987. }
  1988. }
  1989. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1990. Request req;
  1991. req.set_header("Accept-Encoding", "gzip");
  1992. Response res;
  1993. res.set_header("Content-Type", "text/plain");
  1994. auto ret = detail::encoding_type(req, res);
  1995. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1997. #else
  1998. EXPECT_TRUE(ret == detail::EncodingType::None);
  1999. #endif
  2000. }
  2001. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2002. Request req;
  2003. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2004. Response res;
  2005. res.set_header("Content-Type", "text/plain");
  2006. auto ret = detail::encoding_type(req, res);
  2007. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2009. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2010. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2011. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2012. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2013. #else
  2014. EXPECT_TRUE(ret == detail::EncodingType::None);
  2015. #endif
  2016. }
  2017. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding",
  2020. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2021. Response res;
  2022. res.set_header("Content-Type", "text/plain");
  2023. auto ret = detail::encoding_type(req, res);
  2024. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2026. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2028. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2029. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2030. #else
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. #endif
  2033. }
  2034. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2035. // All supported encodings rejected with q=0 should return None
  2036. Request req;
  2037. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2038. Response res;
  2039. res.set_header("Content-Type", "text/plain");
  2040. auto ret = detail::encoding_type(req, res);
  2041. EXPECT_TRUE(ret == detail::EncodingType::None);
  2042. }
  2043. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2044. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2045. Request req;
  2046. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2047. Response res;
  2048. res.set_header("Content-Type", "text/plain");
  2049. auto ret = detail::encoding_type(req, res);
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. }
  2052. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2053. Request req;
  2054. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2055. Response res;
  2056. res.set_header("Content-Type", "text/plain");
  2057. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2058. }
  2059. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2060. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2061. Request req;
  2062. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2063. Response res;
  2064. res.set_header("Content-Type", "text/plain");
  2065. auto ret = detail::encoding_type(req, res);
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. }
  2068. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2069. // RFC 7231: Accept-Encoding values are case-insensitive
  2070. Request req;
  2071. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2072. Response res;
  2073. res.set_header("Content-Type", "text/plain");
  2074. auto ret = detail::encoding_type(req, res);
  2075. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2077. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2078. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2079. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2081. #else
  2082. EXPECT_TRUE(ret == detail::EncodingType::None);
  2083. #endif
  2084. }
  2085. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2086. // q value should determine priority, not hardcoded order
  2087. Request req;
  2088. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2089. Response res;
  2090. res.set_header("Content-Type", "text/plain");
  2091. auto ret = detail::encoding_type(req, res);
  2092. // gzip has highest q=1.0, so it should be selected even though
  2093. // br and zstd are also supported
  2094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2096. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2098. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #else
  2101. EXPECT_TRUE(ret == detail::EncodingType::None);
  2102. #endif
  2103. }
  2104. TEST(BufferStreamTest, read) {
  2105. detail::BufferStream strm1;
  2106. Stream &strm = strm1;
  2107. EXPECT_EQ(5, strm.write("hello"));
  2108. char buf[512];
  2109. EXPECT_EQ(2, strm.read(buf, 2));
  2110. EXPECT_EQ('h', buf[0]);
  2111. EXPECT_EQ('e', buf[1]);
  2112. EXPECT_EQ(2, strm.read(buf, 2));
  2113. EXPECT_EQ('l', buf[0]);
  2114. EXPECT_EQ('l', buf[1]);
  2115. EXPECT_EQ(1, strm.read(buf, 1));
  2116. EXPECT_EQ('o', buf[0]);
  2117. EXPECT_EQ(0, strm.read(buf, 1));
  2118. }
  2119. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2120. auto host = "www.httpwatch.com";
  2121. auto ip = hosted_at(host);
  2122. EXPECT_EQ("23.96.13.243", ip);
  2123. std::vector<std::string> addrs;
  2124. hosted_at(host, addrs);
  2125. EXPECT_EQ(1u, addrs.size());
  2126. }
  2127. #if 0 // It depends on each test environment...
  2128. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2129. auto host = "www.youtube.com";
  2130. std::vector<std::string> addrs;
  2131. hosted_at(host, addrs);
  2132. EXPECT_EQ(20u, addrs.size());
  2133. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2134. EXPECT_TRUE(it != addrs.end());
  2135. }
  2136. #endif
  2137. class ChunkedEncodingTest : public ::testing::Test {
  2138. protected:
  2139. ChunkedEncodingTest()
  2140. : cli_(HOST, PORT)
  2141. #ifdef CPPHTTPLIB_SSL_ENABLED
  2142. ,
  2143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2144. #endif
  2145. {
  2146. cli_.set_connection_timeout(2);
  2147. #ifdef CPPHTTPLIB_SSL_ENABLED
  2148. cli_.enable_server_certificate_verification(false);
  2149. #endif
  2150. }
  2151. virtual void SetUp() {
  2152. read_file("./image.jpg", image_data_);
  2153. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2154. res.set_content("Hello World!", "text/plain");
  2155. });
  2156. svr_.Get(
  2157. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2158. res.set_chunked_content_provider(
  2159. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2160. size_t remaining = image_data_.size() - offset;
  2161. if (remaining == 0) {
  2162. sink.done();
  2163. } else {
  2164. constexpr size_t CHUNK_SIZE = 1024;
  2165. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2166. sink.write(&image_data_[offset], send_size);
  2167. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2168. }
  2169. return true;
  2170. });
  2171. });
  2172. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2173. svr_.wait_until_ready();
  2174. }
  2175. virtual void TearDown() {
  2176. svr_.stop();
  2177. if (!request_threads_.empty()) {
  2178. std::this_thread::sleep_for(std::chrono::seconds(1));
  2179. for (auto &t : request_threads_) {
  2180. t.join();
  2181. }
  2182. }
  2183. t_.join();
  2184. }
  2185. #ifdef CPPHTTPLIB_SSL_ENABLED
  2186. SSLClient cli_;
  2187. SSLServer svr_;
  2188. #else
  2189. Client cli_;
  2190. Server svr_;
  2191. #endif
  2192. thread t_;
  2193. std::vector<thread> request_threads_;
  2194. std::string image_data_;
  2195. };
  2196. TEST_F(ChunkedEncodingTest, NormalGet) {
  2197. auto res = cli_.Get("/chunked");
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. std::string out;
  2200. read_file("./image.jpg", out);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ(out, res->body);
  2203. }
  2204. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2205. std::string body;
  2206. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2207. body.append(data, data_length);
  2208. return true;
  2209. });
  2210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2211. std::string out;
  2212. read_file("./image.jpg", out);
  2213. EXPECT_EQ(StatusCode::OK_200, res->status);
  2214. EXPECT_EQ(out, body);
  2215. }
  2216. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2217. std::string body;
  2218. auto res = cli_.Get(
  2219. "/chunked",
  2220. [&](const Response &response) {
  2221. EXPECT_EQ(StatusCode::OK_200, response.status);
  2222. return true;
  2223. },
  2224. [&](const char *data, size_t data_length) {
  2225. body.append(data, data_length);
  2226. return true;
  2227. });
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, body);
  2233. }
  2234. TEST(RangeTest, FromHTTPBin_Online) {
  2235. auto host = "httpbingo.org";
  2236. auto path = std::string{"/range/32"};
  2237. #ifdef CPPHTTPLIB_SSL_ENABLED
  2238. auto port = 443;
  2239. SSLClient cli(host, port);
  2240. #else
  2241. auto port = 80;
  2242. Client cli(host, port);
  2243. #endif
  2244. cli.set_connection_timeout(5);
  2245. {
  2246. auto res = cli.Get(path);
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. }
  2251. {
  2252. Headers headers = {make_range_header({{1, -1}})};
  2253. auto res = cli.Get(path, headers);
  2254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2255. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2257. }
  2258. {
  2259. Headers headers = {make_range_header({{1, 10}})};
  2260. auto res = cli.Get(path, headers);
  2261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2262. EXPECT_EQ("bcdefghijk", res->body);
  2263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2264. }
  2265. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2266. // entire resource, while the original httpbin returned 200. Both are
  2267. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2268. {
  2269. Headers headers = {make_range_header({{0, 31}})};
  2270. auto res = cli.Get(path, headers);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2274. res->status == StatusCode::PartialContent_206);
  2275. }
  2276. {
  2277. Headers headers = {make_range_header({{0, -1}})};
  2278. auto res = cli.Get(path, headers);
  2279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2280. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2281. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2282. res->status == StatusCode::PartialContent_206);
  2283. }
  2284. // go-httpbin returns 206 with clamped range for over-range requests,
  2285. // while the original httpbin returned 416. Both behaviors are observed
  2286. // in real servers, so we only verify the request succeeds.
  2287. {
  2288. Headers headers = {make_range_header({{0, 32}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. }
  2292. }
  2293. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2294. auto host = "unresolvableaddress.local";
  2295. auto path = std::string{"/"};
  2296. #ifdef CPPHTTPLIB_SSL_ENABLED
  2297. auto port = 443;
  2298. SSLClient cli(host, port);
  2299. #else
  2300. auto port = 80;
  2301. Client cli(host, port);
  2302. #endif
  2303. cli.set_connection_timeout(1);
  2304. {
  2305. auto res = cli.Get(path);
  2306. ASSERT_FALSE(res);
  2307. }
  2308. std::this_thread::sleep_for(std::chrono::seconds(8));
  2309. }
  2310. #if defined(__linux__) && defined(__GLIBC__) && \
  2311. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2312. // Forward declaration: in split builds split.py strips `inline` and moves the
  2313. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2314. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2315. // against the symbol in both header-only and split builds.
  2316. namespace httplib {
  2317. namespace detail {
  2318. int getaddrinfo_with_timeout(const char *node, const char *service,
  2319. const struct addrinfo *hints,
  2320. struct addrinfo **res, time_t timeout_sec);
  2321. } // namespace detail
  2322. } // namespace httplib
  2323. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2324. //
  2325. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2326. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2327. // gai_suspend() call hits the connection timeout the function calls
  2328. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2329. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2330. // still alive and still references the now-destroyed stack frame.
  2331. //
  2332. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2333. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2334. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2335. // and runs them in a container.
  2336. namespace {
  2337. bool should_run_issue_2431_tests() {
  2338. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2339. return v && *v && std::string(v) != "0";
  2340. }
  2341. std::string unique_unresolvable_host(int n) {
  2342. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2343. // glibc still asks the configured nameserver — which is exactly the path
  2344. // we want to exercise. A unique label per call avoids the resolver cache.
  2345. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2346. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2347. std::to_string(n) + ".invalid";
  2348. }
  2349. } // namespace
  2350. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2351. if (!should_run_issue_2431_tests()) {
  2352. GTEST_SKIP()
  2353. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2354. }
  2355. for (int i = 0; i < 8; ++i) {
  2356. struct addrinfo hints;
  2357. memset(&hints, 0, sizeof(hints));
  2358. hints.ai_family = AF_UNSPEC;
  2359. hints.ai_socktype = SOCK_STREAM;
  2360. auto host = unique_unresolvable_host(i);
  2361. struct addrinfo *result = nullptr;
  2362. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2363. &result, /*timeout_sec=*/1);
  2364. if (rc == 0 && result) { freeaddrinfo(result); }
  2365. }
  2366. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2367. // stack region they still believe holds their gaicb.
  2368. std::this_thread::sleep_for(std::chrono::seconds(3));
  2369. }
  2370. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2371. if (!should_run_issue_2431_tests()) {
  2372. GTEST_SKIP()
  2373. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2374. }
  2375. std::atomic<bool> stop{false};
  2376. std::vector<std::thread> threads;
  2377. for (int t = 0; t < 8; ++t) {
  2378. threads.emplace_back([t, &stop] {
  2379. int i = 0;
  2380. while (!stop.load(std::memory_order_relaxed)) {
  2381. struct addrinfo hints;
  2382. memset(&hints, 0, sizeof(hints));
  2383. hints.ai_family = AF_UNSPEC;
  2384. hints.ai_socktype = SOCK_STREAM;
  2385. auto host = unique_unresolvable_host(t * 100000 + i++);
  2386. struct addrinfo *result = nullptr;
  2387. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2388. &result, /*timeout_sec=*/1);
  2389. if (rc == 0 && result) { freeaddrinfo(result); }
  2390. }
  2391. });
  2392. }
  2393. std::this_thread::sleep_for(std::chrono::seconds(8));
  2394. stop.store(true, std::memory_order_relaxed);
  2395. for (auto &th : threads) {
  2396. th.join();
  2397. }
  2398. std::this_thread::sleep_for(std::chrono::seconds(3));
  2399. }
  2400. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2401. if (!should_run_issue_2431_tests()) {
  2402. GTEST_SKIP()
  2403. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2404. }
  2405. std::atomic<bool> stop{false};
  2406. std::vector<std::thread> threads;
  2407. for (int t = 0; t < 8; ++t) {
  2408. threads.emplace_back([t, &stop] {
  2409. int i = 0;
  2410. while (!stop.load(std::memory_order_relaxed)) {
  2411. auto host = unique_unresolvable_host(t * 100000 + i++);
  2412. Client cli(host, 80);
  2413. cli.set_connection_timeout(1, 0);
  2414. cli.set_read_timeout(1, 0);
  2415. cli.set_write_timeout(1, 0);
  2416. (void)cli.Get("/");
  2417. }
  2418. });
  2419. }
  2420. std::this_thread::sleep_for(std::chrono::seconds(8));
  2421. stop.store(true, std::memory_order_relaxed);
  2422. for (auto &th : threads) {
  2423. th.join();
  2424. }
  2425. std::this_thread::sleep_for(std::chrono::seconds(3));
  2426. }
  2427. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2428. TEST(ConnectionErrorTest, InvalidHost) {
  2429. auto host = "-abcde.com";
  2430. #ifdef CPPHTTPLIB_SSL_ENABLED
  2431. auto port = 443;
  2432. SSLClient cli(host, port);
  2433. #else
  2434. auto port = 80;
  2435. Client cli(host, port);
  2436. #endif
  2437. cli.set_connection_timeout(std::chrono::seconds(2));
  2438. auto res = cli.Get("/");
  2439. ASSERT_TRUE(!res);
  2440. EXPECT_EQ(Error::Connection, res.error());
  2441. }
  2442. TEST(ConnectionErrorTest, InvalidHost2) {
  2443. auto host = "httpcan.org/";
  2444. #ifdef CPPHTTPLIB_SSL_ENABLED
  2445. SSLClient cli(host);
  2446. #else
  2447. Client cli(host);
  2448. #endif
  2449. cli.set_connection_timeout(std::chrono::seconds(2));
  2450. auto res = cli.Get("/");
  2451. ASSERT_TRUE(!res);
  2452. EXPECT_EQ(Error::Connection, res.error());
  2453. }
  2454. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2455. auto host = "httpcan.org/";
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. SSLClient cli(host);
  2458. #else
  2459. Client cli(host);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. stringstream s;
  2465. s << "error code: " << res.error();
  2466. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2467. }
  2468. TEST(ConnectionErrorTest, InvalidPort) {
  2469. auto host = "localhost";
  2470. auto port = 44380;
  2471. #ifdef CPPHTTPLIB_SSL_ENABLED
  2472. SSLClient cli(host, port);
  2473. #else
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_TRUE(Error::Connection == res.error() ||
  2480. Error::ConnectionTimeout == res.error());
  2481. }
  2482. TEST(ConnectionErrorTest, Timeout_Online) {
  2483. auto host = "google.com";
  2484. #ifdef CPPHTTPLIB_SSL_ENABLED
  2485. auto port = 44380;
  2486. SSLClient cli(host, port);
  2487. #else
  2488. auto port = 8080;
  2489. Client cli(host, port);
  2490. #endif
  2491. cli.set_connection_timeout(std::chrono::seconds(2));
  2492. // only probe one address type so that the error reason
  2493. // correlates to the timed-out IPv4, not the unsupported
  2494. // IPv6 connection attempt
  2495. cli.set_address_family(AF_INET);
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2499. }
  2500. TEST(CancelTest, NoCancel_Online) {
  2501. auto host = "httpbingo.org";
  2502. auto path = std::string{"/range/32"};
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. auto port = 443;
  2505. SSLClient cli(host, port);
  2506. #else
  2507. auto port = 80;
  2508. Client cli(host, port);
  2509. #endif
  2510. cli.set_connection_timeout(std::chrono::seconds(5));
  2511. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. }
  2516. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2517. // Use /bytes with a large payload so that the DownloadProgress callback
  2518. // (which only fires for Content-Length responses) is invoked before the
  2519. // entire body is received, giving cancellation a chance to fire.
  2520. auto host = "httpbingo.org";
  2521. auto path = std::string{"/bytes/524288"};
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. auto port = 443;
  2524. SSLClient cli(host, port);
  2525. #else
  2526. auto port = 80;
  2527. Client cli(host, port);
  2528. #endif
  2529. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. TEST(CancelTest, WithCancelLargePayload_Online) {
  2535. auto host = "httpbingo.org";
  2536. auto path = std::string{"/bytes/524288"};
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. auto port = 443;
  2539. SSLClient cli(host, port);
  2540. #else
  2541. auto port = 80;
  2542. Client cli(host, port);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. uint32_t count = 0;
  2546. auto res =
  2547. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_EQ(Error::Canceled, res.error());
  2550. }
  2551. TEST(CancelTest, NoCancelPost) {
  2552. Server svr;
  2553. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2554. res.set_content("Hello World!", "text/plain");
  2555. });
  2556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2557. auto se = detail::scope_exit([&] {
  2558. svr.stop();
  2559. thread.join();
  2560. ASSERT_FALSE(svr.is_running());
  2561. });
  2562. svr.wait_until_ready();
  2563. Client cli(HOST, PORT);
  2564. cli.set_connection_timeout(std::chrono::seconds(5));
  2565. auto res =
  2566. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2567. "application/json", [](uint64_t, uint64_t) { return true; });
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ("Hello World!", res->body);
  2570. EXPECT_EQ(StatusCode::OK_200, res->status);
  2571. }
  2572. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2573. Server svr;
  2574. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2575. res.set_content("Hello World!", "text/plain");
  2576. });
  2577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2578. auto se = detail::scope_exit([&] {
  2579. svr.stop();
  2580. thread.join();
  2581. ASSERT_FALSE(svr.is_running());
  2582. });
  2583. svr.wait_until_ready();
  2584. Client cli(HOST, PORT);
  2585. cli.set_connection_timeout(std::chrono::seconds(5));
  2586. auto res =
  2587. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2588. "application/json", [](uint64_t, uint64_t) { return false; });
  2589. ASSERT_TRUE(!res);
  2590. EXPECT_EQ(Error::Canceled, res.error());
  2591. }
  2592. TEST(CancelTest, WithCancelLargePayloadPost) {
  2593. Server svr;
  2594. svr.set_payload_max_length(200 * 1024 * 1024);
  2595. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2596. res.set_content(LARGE_DATA, "text/plain");
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. Client cli(HOST, PORT);
  2606. cli.set_payload_max_length(200 * 1024 * 1024);
  2607. cli.set_connection_timeout(std::chrono::seconds(5));
  2608. auto res =
  2609. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2610. "application/json", [](uint64_t, uint64_t) { return false; });
  2611. ASSERT_TRUE(!res);
  2612. EXPECT_EQ(Error::Canceled, res.error());
  2613. }
  2614. TEST(CancelTest, NoCancelPut) {
  2615. Server svr;
  2616. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("Hello World!", "text/plain");
  2618. });
  2619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2620. auto se = detail::scope_exit([&] {
  2621. svr.stop();
  2622. thread.join();
  2623. ASSERT_FALSE(svr.is_running());
  2624. });
  2625. svr.wait_until_ready();
  2626. Client cli(HOST, PORT);
  2627. cli.set_connection_timeout(std::chrono::seconds(5));
  2628. auto res =
  2629. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2630. "application/json", [](uint64_t, uint64_t) { return true; });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ("Hello World!", res->body);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. }
  2635. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2636. Server svr;
  2637. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!", "text/plain");
  2639. });
  2640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2641. auto se = detail::scope_exit([&] {
  2642. svr.stop();
  2643. thread.join();
  2644. ASSERT_FALSE(svr.is_running());
  2645. });
  2646. svr.wait_until_ready();
  2647. Client cli(HOST, PORT);
  2648. cli.set_connection_timeout(std::chrono::seconds(5));
  2649. auto res =
  2650. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2651. "application/json", [](uint64_t, uint64_t) { return false; });
  2652. ASSERT_TRUE(!res);
  2653. EXPECT_EQ(Error::Canceled, res.error());
  2654. }
  2655. TEST(CancelTest, WithCancelLargePayloadPut) {
  2656. Server svr;
  2657. svr.set_payload_max_length(200 * 1024 * 1024);
  2658. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2659. res.set_content(LARGE_DATA, "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. Client cli(HOST, PORT);
  2669. cli.set_payload_max_length(200 * 1024 * 1024);
  2670. cli.set_connection_timeout(std::chrono::seconds(5));
  2671. auto res =
  2672. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2673. "application/json", [](uint64_t, uint64_t) { return false; });
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Canceled, res.error());
  2676. }
  2677. TEST(CancelTest, NoCancelPatch) {
  2678. Server svr;
  2679. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2680. res.set_content("Hello World!", "text/plain");
  2681. });
  2682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2683. auto se = detail::scope_exit([&] {
  2684. svr.stop();
  2685. thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, PORT);
  2690. cli.set_connection_timeout(std::chrono::seconds(5));
  2691. auto res =
  2692. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2693. "application/json", [](uint64_t, uint64_t) { return true; });
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ("Hello World!", res->body);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. }
  2698. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2699. Server svr;
  2700. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2701. res.set_content("Hello World!", "text/plain");
  2702. });
  2703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2704. auto se = detail::scope_exit([&] {
  2705. svr.stop();
  2706. thread.join();
  2707. ASSERT_FALSE(svr.is_running());
  2708. });
  2709. svr.wait_until_ready();
  2710. Client cli(HOST, PORT);
  2711. cli.set_connection_timeout(std::chrono::seconds(5));
  2712. auto res =
  2713. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2714. "application/json", [](uint64_t, uint64_t) { return false; });
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Canceled, res.error());
  2717. }
  2718. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2719. Server svr;
  2720. svr.set_payload_max_length(200 * 1024 * 1024);
  2721. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2722. res.set_content(LARGE_DATA, "text/plain");
  2723. });
  2724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2725. auto se = detail::scope_exit([&] {
  2726. svr.stop();
  2727. thread.join();
  2728. ASSERT_FALSE(svr.is_running());
  2729. });
  2730. svr.wait_until_ready();
  2731. Client cli(HOST, PORT);
  2732. cli.set_payload_max_length(200 * 1024 * 1024);
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res =
  2735. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2736. "application/json", [](uint64_t, uint64_t) { return false; });
  2737. ASSERT_TRUE(!res);
  2738. EXPECT_EQ(Error::Canceled, res.error());
  2739. }
  2740. TEST(CancelTest, NoCancelDelete) {
  2741. Server svr;
  2742. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2743. res.set_content("Hello World!", "text/plain");
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. Client cli(HOST, PORT);
  2753. cli.set_connection_timeout(std::chrono::seconds(5));
  2754. auto res =
  2755. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2756. "application/json", [](uint64_t, uint64_t) { return true; });
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. EXPECT_EQ("Hello World!", res->body);
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. }
  2761. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2762. Server svr;
  2763. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. Client cli(HOST, PORT);
  2774. cli.set_connection_timeout(std::chrono::seconds(5));
  2775. auto res =
  2776. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2777. "application/json", [](uint64_t, uint64_t) { return false; });
  2778. ASSERT_TRUE(!res);
  2779. EXPECT_EQ(Error::Canceled, res.error());
  2780. }
  2781. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2782. Server svr;
  2783. svr.set_payload_max_length(200 * 1024 * 1024);
  2784. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2785. res.set_content(LARGE_DATA, "text/plain");
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. cli.set_payload_max_length(200 * 1024 * 1024);
  2796. cli.set_connection_timeout(std::chrono::seconds(5));
  2797. auto res =
  2798. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2799. "application/json", [](uint64_t, uint64_t) { return false; });
  2800. ASSERT_TRUE(!res);
  2801. EXPECT_EQ(Error::Canceled, res.error());
  2802. }
  2803. static std::string remove_whitespace(const std::string &input) {
  2804. std::string output;
  2805. output.reserve(input.size());
  2806. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2807. [](unsigned char c) { return !std::isspace(c); });
  2808. return output;
  2809. }
  2810. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2811. auto host = "httpbingo.org";
  2812. auto path = std::string{"/basic-auth/hello/world"};
  2813. #ifdef CPPHTTPLIB_SSL_ENABLED
  2814. auto port = 443;
  2815. SSLClient cli(host, port);
  2816. #else
  2817. auto port = 80;
  2818. Client cli(host, port);
  2819. #endif
  2820. {
  2821. auto res = cli.Get(path);
  2822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2823. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2824. }
  2825. {
  2826. auto res = cli.Get(
  2827. path, Headers{make_basic_authentication_header("hello", "world")});
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. auto body = remove_whitespace(res->body);
  2830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2832. EXPECT_EQ(StatusCode::OK_200, res->status);
  2833. }
  2834. {
  2835. cli.set_basic_auth("hello", "world");
  2836. auto res = cli.Get(path);
  2837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2838. auto body = remove_whitespace(res->body);
  2839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2841. EXPECT_EQ(StatusCode::OK_200, res->status);
  2842. }
  2843. {
  2844. cli.set_basic_auth("hello", "bad");
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. cli.set_basic_auth("bad", "world");
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2854. }
  2855. }
  2856. #ifdef CPPHTTPLIB_SSL_ENABLED
  2857. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2858. auto host = "httpbingo.org";
  2859. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2860. auto paths = std::vector<std::string>{
  2861. "/digest-auth/auth/hello/world/MD5",
  2862. "/digest-auth/auth/hello/world/SHA-256",
  2863. };
  2864. auto port = 443;
  2865. SSLClient cli(host, port);
  2866. {
  2867. auto res = cli.Get(unauth_path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. cli.set_digest_auth("hello", "world");
  2873. for (const auto &path : paths) {
  2874. auto res = cli.Get(path.c_str());
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. auto body = remove_whitespace(res->body);
  2877. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2878. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. cli.set_digest_auth("hello", "bad");
  2882. for (const auto &path : paths) {
  2883. auto res = cli.Get(path.c_str());
  2884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2885. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2886. }
  2887. }
  2888. }
  2889. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2890. // comma-separated list of challenges, and each challenge may itself carry a
  2891. // comma-separated auth-param list, so a server can legally offer Basic
  2892. // before Digest, either as two field lines or packed into one. Runs one 401
  2893. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2894. // value() joins them in receipt order) and checks that the retry carries a
  2895. // well-formed Digest Authorization header naming expected_realm.
  2896. static void
  2897. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2898. const std::string &expected_realm) {
  2899. std::atomic<int> hits{0};
  2900. Server svr;
  2901. svr.Get("/x", [&](const Request &req, Response &res) {
  2902. if (++hits == 1) {
  2903. res.status = StatusCode::Unauthorized_401;
  2904. for (const auto &challenge : challenges) {
  2905. res.set_header("WWW-Authenticate", challenge);
  2906. }
  2907. } else {
  2908. auto authorization = req.get_header_value("Authorization");
  2909. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2910. EXPECT_NE(std::string::npos,
  2911. authorization.find("realm=\"" + expected_realm + "\""));
  2912. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2913. res.set_content("ok", "text/plain");
  2914. }
  2915. });
  2916. auto port = svr.bind_to_any_port(HOST);
  2917. std::thread t([&]() { svr.listen_after_bind(); });
  2918. auto se = detail::scope_exit([&] {
  2919. svr.stop();
  2920. t.join();
  2921. });
  2922. svr.wait_until_ready();
  2923. Client cli(HOST, port);
  2924. cli.set_digest_auth("hello", "world");
  2925. auto res = cli.Get("/x");
  2926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2927. EXPECT_EQ(2, hits.load());
  2928. }
  2929. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2930. static const char *kDigestChallenge =
  2931. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2932. "algorithm=MD5";
  2933. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2934. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2935. "testrealm");
  2936. }
  2937. // Same challenge list with the schemes in the opposite order, to make sure
  2938. // the fix above didn't just special-case "Basic first".
  2939. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2940. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2941. "testrealm");
  2942. }
  2943. // A comma inside a quoted auth-param value must not be mistaken for the
  2944. // separator between two challenges (or two auth-params).
  2945. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2946. run_digest_challenge_list_test(
  2947. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2948. "algorithm=MD5"},
  2949. "test,realm");
  2950. }
  2951. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2952. // make_digest_authentication_header() dereferences both unconditionally, so
  2953. // a server sending a challenge missing either one must not be treated as
  2954. // usable -- doing so used to crash the client with std::out_of_range.
  2955. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2958. res.status = StatusCode::Unauthorized_401;
  2959. res.set_header("WWW-Authenticate", challenge);
  2960. });
  2961. auto port = svr.bind_to_any_port(HOST);
  2962. std::thread t([&]() { svr.listen_after_bind(); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. t.join();
  2966. });
  2967. svr.wait_until_ready();
  2968. Client cli(HOST, port);
  2969. cli.set_digest_auth("hello", "world");
  2970. auto res = cli.Get("/x");
  2971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2973. }
  2974. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2975. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2976. }
  2977. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2978. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2979. }
  2980. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2981. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2982. }
  2983. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2984. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2985. // when storing the values, so the header builder has to re-escape them (and
  2986. // keep algorithm a bare token); otherwise the value breaks out of its
  2987. // quoted-string and injects extra auth-params into the client's Authorization.
  2988. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2989. std::atomic<int> hits{0};
  2990. std::string authorization;
  2991. Server svr;
  2992. svr.Get("/x", [&](const Request &req, Response &res) {
  2993. if (++hits == 1) {
  2994. res.status = StatusCode::Unauthorized_401;
  2995. // On the wire the quotes embedded in the values are backslash-escaped.
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"testrealm\", "
  2998. "nonce=\"n\\\"; injected=\\\"x\", "
  2999. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3000. } else {
  3001. authorization = req.get_header_value("Authorization");
  3002. res.set_content("ok", "text/plain");
  3003. }
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/x");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(2, hits.load());
  3017. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3018. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3019. // inside its quoted-string rather than starting an "injected" auth-param.
  3020. EXPECT_NE(std::string::npos,
  3021. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3022. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3023. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3024. }
  3025. #endif
  3026. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3027. auto host = "google.com";
  3028. auto another_host = "example.com";
  3029. auto wrong_ip = "0.0.0.0";
  3030. #ifdef CPPHTTPLIB_SSL_ENABLED
  3031. SSLClient cli(host);
  3032. #else
  3033. Client cli(host);
  3034. #endif
  3035. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3036. auto res = cli.Get("/");
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3039. }
  3040. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3041. auto host = "google.com";
  3042. auto wrong_ip = "0.0.0.0";
  3043. #ifdef CPPHTTPLIB_SSL_ENABLED
  3044. SSLClient cli(host);
  3045. #else
  3046. Client cli(host);
  3047. #endif
  3048. cli.set_hostname_addr_map({{host, wrong_ip}});
  3049. auto res = cli.Get("/");
  3050. ASSERT_TRUE(!res);
  3051. EXPECT_EQ(Error::Connection, res.error());
  3052. }
  3053. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3054. // A mapped value that is not an IP literal must be resolved. "localhost"
  3055. // resolves from the hosts file, so this test needs no external DNS.
  3056. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3057. auto host = "target.invalid";
  3058. Server svr;
  3059. std::string received_host;
  3060. svr.Get("/hi", [&](const Request &req, Response &res) {
  3061. received_host = req.get_header_value("Host");
  3062. res.set_content("Hello World!", "text/plain");
  3063. });
  3064. auto port = svr.bind_to_any_port(HOST);
  3065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. Client cli(host, port);
  3073. cli.set_hostname_addr_map({{host, HOST}});
  3074. auto res = cli.Get("/hi");
  3075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3076. EXPECT_EQ(StatusCode::OK_200, res->status);
  3077. // The mapping only redirects the connection; the identity stays host_.
  3078. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3079. }
  3080. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3081. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3082. auto host = "target.invalid";
  3083. Server svr;
  3084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3085. res.set_content("Hello World!", "text/plain");
  3086. });
  3087. auto port = svr.bind_to_any_port("127.0.0.1");
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(host, port);
  3096. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3097. auto res = cli.Get("/hi");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(StatusCode::OK_200, res->status);
  3100. }
  3101. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3102. // An empty mapped value must leave host_ as the connection target. Without
  3103. // that guard the empty value would become the host argument, getaddrinfo
  3104. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3105. // loopback - silently connecting somewhere the caller never asked for.
  3106. // The server listens on loopback, so such a fallback would succeed and is
  3107. // therefore observable as a failure of this test.
  3108. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3109. Server svr;
  3110. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3111. res.set_content("Hello World!", "text/plain");
  3112. });
  3113. auto port = svr.bind_to_any_port(HOST);
  3114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3115. auto se = detail::scope_exit([&] {
  3116. svr.stop();
  3117. thread.join();
  3118. ASSERT_FALSE(svr.is_running());
  3119. });
  3120. svr.wait_until_ready();
  3121. Client cli(blackhole, port);
  3122. cli.set_hostname_addr_map({{blackhole, ""}});
  3123. cli.set_connection_timeout(1);
  3124. auto res = cli.Get("/hi");
  3125. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3126. }
  3127. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3128. auto host = "httpbingo.org";
  3129. auto path = std::string{"/absolute-redirect/3"};
  3130. #ifdef CPPHTTPLIB_SSL_ENABLED
  3131. SSLClient cli(host);
  3132. #else
  3133. Client cli(host);
  3134. #endif
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get(path);
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(RedirectTest, Redirect_Online) {
  3141. auto host = "httpbingo.org";
  3142. auto path = std::string{"/redirect/3"};
  3143. #ifdef CPPHTTPLIB_SSL_ENABLED
  3144. SSLClient cli(host);
  3145. #else
  3146. Client cli(host);
  3147. #endif
  3148. cli.set_follow_location(true);
  3149. auto res = cli.Get(path);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. }
  3153. TEST(RelativeRedirectTest, Redirect_Online) {
  3154. auto host = "httpbingo.org";
  3155. auto path = std::string{"/relative-redirect/3"};
  3156. #ifdef CPPHTTPLIB_SSL_ENABLED
  3157. SSLClient cli(host);
  3158. #else
  3159. Client cli(host);
  3160. #endif
  3161. cli.set_follow_location(true);
  3162. auto res = cli.Get(path);
  3163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3164. EXPECT_EQ(StatusCode::OK_200, res->status);
  3165. }
  3166. TEST(TooManyRedirectTest, Redirect_Online) {
  3167. auto host = "httpbingo.org";
  3168. auto path = std::string{"/redirect/21"};
  3169. #ifdef CPPHTTPLIB_SSL_ENABLED
  3170. SSLClient cli(host);
  3171. #else
  3172. Client cli(host);
  3173. #endif
  3174. cli.set_follow_location(true);
  3175. auto res = cli.Get(path);
  3176. ASSERT_TRUE(!res);
  3177. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3178. }
  3179. #ifdef CPPHTTPLIB_SSL_ENABLED
  3180. TEST(YahooRedirectTest, Redirect_Online) {
  3181. Client cli("yahoo.com");
  3182. auto res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3185. cli.set_follow_location(true);
  3186. res = cli.Get("/");
  3187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3188. EXPECT_EQ(StatusCode::OK_200, res->status);
  3189. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3190. }
  3191. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3192. #define REDIR_HOST "httpbingo.org"
  3193. #define REDIR_PATH "/redirect-to"
  3194. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3195. SSLClient cli(REDIR_HOST);
  3196. cli.set_follow_location(true);
  3197. auto res =
  3198. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3203. SSLClient cli(REDIR_HOST);
  3204. cli.set_follow_location(true);
  3205. Params params;
  3206. params.emplace("url", "http://example.com");
  3207. params.emplace("status_code", "302");
  3208. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. }
  3212. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3213. SSLClient cli(REDIR_HOST);
  3214. cli.set_follow_location(true);
  3215. Params params;
  3216. params.emplace("url", "http://example.com");
  3217. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(UrlWithSpace, Redirect_Online) {
  3222. SSLClient cli("edge.forgecdn.net");
  3223. cli.set_follow_location(true);
  3224. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3228. }
  3229. #endif
  3230. #if !defined(_WIN32) && !defined(_WIN64)
  3231. TEST(ReceiveSignals, Signal) {
  3232. auto setupSignalHandlers = []() {
  3233. struct sigaction act;
  3234. sigemptyset(&act.sa_mask);
  3235. act.sa_flags = SA_SIGINFO;
  3236. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3237. switch (sig) {
  3238. case SIGINT:
  3239. default: break;
  3240. }
  3241. };
  3242. ::sigaction(SIGINT, &act, nullptr);
  3243. };
  3244. Server svr;
  3245. int port = 0;
  3246. auto thread = std::thread([&]() {
  3247. setupSignalHandlers();
  3248. port = svr.bind_to_any_port(HOST);
  3249. svr.listen_after_bind();
  3250. });
  3251. auto se = detail::scope_exit([&] {
  3252. svr.stop();
  3253. thread.join();
  3254. ASSERT_FALSE(svr.is_running());
  3255. });
  3256. svr.wait_until_ready();
  3257. ASSERT_TRUE(svr.is_running());
  3258. pthread_kill(thread.native_handle(), SIGINT);
  3259. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3260. ASSERT_TRUE(svr.is_running());
  3261. }
  3262. #endif
  3263. TEST(RedirectToDifferentPort, Redirect) {
  3264. Server svr1;
  3265. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3266. res.set_content("Hello World!", "text/plain");
  3267. });
  3268. int svr1_port = 0;
  3269. auto thread1 = std::thread([&]() {
  3270. svr1_port = svr1.bind_to_any_port(HOST);
  3271. svr1.listen_after_bind();
  3272. });
  3273. Server svr2;
  3274. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3275. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3276. });
  3277. int svr2_port = 0;
  3278. auto thread2 = std::thread([&]() {
  3279. svr2_port = svr2.bind_to_any_port(HOST);
  3280. svr2.listen_after_bind();
  3281. });
  3282. auto se = detail::scope_exit([&] {
  3283. svr2.stop();
  3284. thread2.join();
  3285. svr1.stop();
  3286. thread1.join();
  3287. ASSERT_FALSE(svr2.is_running());
  3288. ASSERT_FALSE(svr1.is_running());
  3289. });
  3290. svr1.wait_until_ready();
  3291. svr2.wait_until_ready();
  3292. Client cli("localhost", svr2_port);
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/2");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ("Hello World!", res->body);
  3298. }
  3299. // GET /redir on one server redirects to /target on another port, so the
  3300. // client follows it with a new client.
  3301. static Result
  3302. GetThroughRedirectToDifferentPort(Server::Handler target,
  3303. const std::function<void(Client &)> &setup,
  3304. const Headers &headers = Headers()) {
  3305. Server target_svr;
  3306. target_svr.Get("/target", target);
  3307. int target_port = 0;
  3308. auto target_thread = std::thread([&]() {
  3309. target_port = target_svr.bind_to_any_port(HOST);
  3310. target_svr.listen_after_bind();
  3311. });
  3312. Server origin_svr;
  3313. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3314. res.set_redirect(
  3315. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3316. });
  3317. int origin_port = 0;
  3318. auto origin_thread = std::thread([&]() {
  3319. origin_port = origin_svr.bind_to_any_port(HOST);
  3320. origin_svr.listen_after_bind();
  3321. });
  3322. auto se = detail::scope_exit([&] {
  3323. origin_svr.stop();
  3324. origin_thread.join();
  3325. target_svr.stop();
  3326. target_thread.join();
  3327. });
  3328. target_svr.wait_until_ready();
  3329. origin_svr.wait_until_ready();
  3330. Client cli("localhost", origin_port);
  3331. cli.set_follow_location(true);
  3332. setup(cli);
  3333. return cli.Get("/redir", headers);
  3334. }
  3335. static void
  3336. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3337. std::string captured_authorization;
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [&](const Request &req, Response &res) {
  3340. captured_authorization = req.get_header_value("Authorization");
  3341. res.set_content("OK", "text/plain");
  3342. },
  3343. set_auth);
  3344. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3345. EXPECT_EQ(StatusCode::OK_200, result->status);
  3346. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3347. EXPECT_TRUE(captured_authorization.empty());
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3354. TestDoNotForwardCredentialsOnRedirect(
  3355. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3356. }
  3357. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3358. std::string captured_cookie;
  3359. auto result = GetThroughRedirectToDifferentPort(
  3360. [&](const Request &req, Response &res) {
  3361. captured_cookie = req.get_header_value("Cookie");
  3362. res.set_content("OK", "text/plain");
  3363. },
  3364. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3365. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3366. EXPECT_EQ(StatusCode::OK_200, result->status);
  3367. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3368. EXPECT_TRUE(captured_cookie.empty());
  3369. }
  3370. TEST(RedirectToSamePort, ForwardCookie) {
  3371. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3372. // header so that ordinary session flows keep working.
  3373. Server svr;
  3374. std::string captured_cookie;
  3375. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3376. res.set_redirect("/target", 302);
  3377. });
  3378. svr.Get("/target", [&](const Request &req, Response &res) {
  3379. captured_cookie = req.get_header_value("Cookie");
  3380. res.set_content("OK", "text/plain");
  3381. });
  3382. auto port = svr.bind_to_any_port(HOST);
  3383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3384. auto se = detail::scope_exit([&] {
  3385. svr.stop();
  3386. thread.join();
  3387. ASSERT_FALSE(svr.is_running());
  3388. });
  3389. svr.wait_until_ready();
  3390. Client cli(HOST, port);
  3391. cli.set_follow_location(true);
  3392. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3393. auto res = cli.Get("/redir", headers);
  3394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3397. }
  3398. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3399. std::string authorization;
  3400. std::string trace_id;
  3401. auto result = GetThroughRedirectToDifferentPort(
  3402. [&](const Request &req, Response &res) {
  3403. authorization = req.get_header_value("Authorization");
  3404. trace_id = req.get_header_value("X-Trace-Id");
  3405. res.set_content("OK", "text/plain");
  3406. },
  3407. [](Client &cli) {
  3408. cli.set_default_headers(
  3409. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3410. });
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // Like a header given with the request, a default one goes along unless it
  3414. // carries credentials (RFC 9110 15.4).
  3415. EXPECT_TRUE(authorization.empty());
  3416. EXPECT_EQ("42", trace_id);
  3417. }
  3418. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3419. auto result = GetThroughRedirectToDifferentPort(
  3420. [](const Request &, Response &res) {
  3421. res.set_content(std::string(2048, 'x'), "text/plain");
  3422. },
  3423. [](Client &cli) { cli.set_payload_max_length(1024); });
  3424. EXPECT_FALSE(result);
  3425. }
  3426. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [](const Request &req, Response &res) {
  3429. // Answer after a second, or once the client gives up.
  3430. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3432. }
  3433. res.set_content("late", "text/plain");
  3434. },
  3435. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3436. ASSERT_FALSE(result);
  3437. EXPECT_EQ(Error::Read, result.error());
  3438. }
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3441. auto result = GetThroughRedirectToDifferentPort(
  3442. [](const Request &, Response &res) {
  3443. res.status = StatusCode::Unauthorized_401;
  3444. res.set_header("WWW-Authenticate",
  3445. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3446. },
  3447. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3450. }
  3451. #endif
  3452. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3453. Server svr;
  3454. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3455. // Port number that overflows int — should not crash
  3456. res.set_redirect("http://localhost:99999999999999999999/target");
  3457. });
  3458. auto port = svr.bind_to_any_port(HOST);
  3459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. Client cli(HOST, port);
  3467. cli.set_follow_location(true);
  3468. auto res = cli.Get("/redir");
  3469. // Should fail gracefully, not crash (no valid response due to bad port)
  3470. EXPECT_FALSE(res);
  3471. }
  3472. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3473. Server svr;
  3474. auto port = svr.bind_to_any_port(HOST);
  3475. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3476. // The server's own port followed by junk must not be followed
  3477. res.set_redirect("http://" + std::string(HOST) + ":" +
  3478. std::to_string(port) + "junk/target");
  3479. });
  3480. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3481. res.set_content("target", "text/plain");
  3482. });
  3483. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. thread.join();
  3487. ASSERT_FALSE(svr.is_running());
  3488. });
  3489. svr.wait_until_ready();
  3490. Client cli(HOST, port);
  3491. cli.set_follow_location(true);
  3492. auto res = cli.Get("/redir");
  3493. EXPECT_FALSE(res);
  3494. }
  3495. TEST(RedirectFromPageWithContent, Redirect) {
  3496. Server svr;
  3497. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("___", "text/plain");
  3499. res.set_redirect("/2");
  3500. });
  3501. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3502. res.set_content("Hello World!", "text/plain");
  3503. });
  3504. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3505. auto se = detail::scope_exit([&] {
  3506. svr.stop();
  3507. th.join();
  3508. ASSERT_FALSE(svr.is_running());
  3509. });
  3510. svr.wait_until_ready();
  3511. {
  3512. Client cli("localhost", PORT);
  3513. cli.set_follow_location(true);
  3514. std::string body;
  3515. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3516. body.append(data, data_length);
  3517. return true;
  3518. });
  3519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. EXPECT_EQ("Hello World!", body);
  3522. }
  3523. {
  3524. Client cli("localhost", PORT);
  3525. std::string body;
  3526. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3527. body.append(data, data_length);
  3528. return true;
  3529. });
  3530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3531. EXPECT_EQ(StatusCode::Found_302, res->status);
  3532. EXPECT_EQ("___", body);
  3533. }
  3534. }
  3535. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3536. Server svr;
  3537. auto port_str = std::to_string(PORT);
  3538. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3539. auto expected_host = "[::1]:" + port_str;
  3540. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3541. res.set_content("___", "text/plain");
  3542. // res.set_redirect("/2");
  3543. res.set_redirect(redirect_url);
  3544. });
  3545. svr.Get("/2", [&](const Request &req, Response &res) {
  3546. auto host_header = req.headers.find("Host");
  3547. ASSERT_TRUE(host_header != req.headers.end());
  3548. EXPECT_EQ(expected_host, host_header->second);
  3549. res.set_content("Hello World!", "text/plain");
  3550. });
  3551. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. th.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3558. // actually starts anything, so the condition !svr.is_running() will
  3559. // always remain true, and the loop never stops.
  3560. // This basically counts how many milliseconds have passed since the
  3561. // call to svr.listen(), and if after 5 seconds nothing started yet
  3562. // aborts the test.
  3563. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3564. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3565. ASSERT_LT(milliseconds, 5000U);
  3566. }
  3567. {
  3568. Client cli("::1", PORT);
  3569. cli.set_follow_location(true);
  3570. std::string body;
  3571. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3572. body.append(data, data_length);
  3573. return true;
  3574. });
  3575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. EXPECT_EQ("Hello World!", body);
  3578. }
  3579. {
  3580. Client cli("::1", PORT);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::Found_302, res->status);
  3588. EXPECT_EQ("___", body);
  3589. }
  3590. }
  3591. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3592. Server svr;
  3593. svr.Get("/foo", [](const Request &req, Response &res) {
  3594. auto a = req.params.find("a");
  3595. if (a != req.params.end()) {
  3596. res.set_content((*a).second, "text/plain");
  3597. res.status = StatusCode::OK_200;
  3598. } else {
  3599. res.status = StatusCode::BadRequest_400;
  3600. }
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. {
  3610. Client cli(HOST, PORT);
  3611. cli.set_path_encode(false);
  3612. auto res = cli.Get("/foo?a=explicitly+encoded");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. // This expects it back with a space, as the `+` won't have been
  3616. // url-encoded, and server-side the params get decoded turning `+`
  3617. // into spaces.
  3618. EXPECT_EQ("explicitly encoded", res->body);
  3619. }
  3620. }
  3621. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3622. // When path encoding is disabled the client must transmit the supplied
  3623. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3624. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3625. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3626. // than a space (0x20). Assert on the raw wire target to catch this.
  3627. Server svr;
  3628. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3629. svr.Get("/foo", [&](const Request &req, Response &res) {
  3630. EXPECT_EQ(expected_target, req.target);
  3631. res.status = StatusCode::OK_200;
  3632. });
  3633. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. {
  3641. Client cli(HOST, PORT);
  3642. cli.set_path_encode(false);
  3643. auto res = cli.Get(expected_target.c_str());
  3644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. }
  3647. }
  3648. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3649. // `open_stream()` used to skip the path encoding that the buffered send
  3650. // path applies, so the same `path` produced different bytes in the request
  3651. // line depending on which API was used. Assert the two agree.
  3652. Server svr;
  3653. std::string target;
  3654. svr.Get(".*", [&](const Request &req, Response &res) {
  3655. target = req.target;
  3656. res.status = StatusCode::OK_200;
  3657. });
  3658. auto port = svr.bind_to_any_port(HOST);
  3659. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3660. auto se = detail::scope_exit([&] {
  3661. svr.stop();
  3662. thread.join();
  3663. ASSERT_FALSE(svr.is_running());
  3664. });
  3665. svr.wait_until_ready();
  3666. struct {
  3667. const char *path;
  3668. const char *expected;
  3669. } cases[] = {
  3670. {"/a b?x=1", "/a%20b?x=1"},
  3671. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3672. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3673. };
  3674. for (const auto &c : cases) {
  3675. Client cli(HOST, port);
  3676. target.clear();
  3677. auto res = cli.Get(c.path);
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3680. auto buffered_target = target;
  3681. target.clear();
  3682. auto handle = cli.open_stream("GET", c.path);
  3683. EXPECT_TRUE(handle.is_valid())
  3684. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3685. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3689. // The `set_path_encode(false)` contract — transmit the supplied target
  3690. // verbatim — must hold for the streaming API too.
  3691. Server svr;
  3692. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3693. std::string target;
  3694. svr.Get("/foo", [&](const Request &req, Response &res) {
  3695. target = req.target;
  3696. res.status = StatusCode::OK_200;
  3697. });
  3698. auto port = svr.bind_to_any_port(HOST);
  3699. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3700. auto se = detail::scope_exit([&] {
  3701. svr.stop();
  3702. thread.join();
  3703. ASSERT_FALSE(svr.is_running());
  3704. });
  3705. svr.wait_until_ready();
  3706. {
  3707. Client cli(HOST, port);
  3708. cli.set_path_encode(false);
  3709. auto handle = cli.open_stream("GET", expected_target);
  3710. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3711. EXPECT_EQ(expected_target, target);
  3712. }
  3713. }
  3714. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3715. // With path encoding enabled a CR/LF in the target is percent-encoded
  3716. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3717. // write_request_line still backstops `set_path_encode(false)`, which is
  3718. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3719. Server svr;
  3720. // Captured before routing: the decoded path contains a newline, which a
  3721. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3722. std::string target;
  3723. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. return Server::HandlerResponse::Handled;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. {
  3737. Client cli(HOST, port);
  3738. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3739. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3740. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3744. // Every control character is percent-encoded, not just CR/LF, so the target
  3745. // passes the request-target check in write_request_line.
  3746. Server svr;
  3747. std::string target;
  3748. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. return Server::HandlerResponse::Handled;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. auto res = cli.Get("/a\tb\x1b\x7f");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ("/a%09b%1B%7F", target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3769. // Nothing may reach the wire: a raw CR/LF target would split the request
  3770. // line and inject headers.
  3771. Server svr;
  3772. // Pre-routing so that "not called" means nothing reached the server at all,
  3773. // rather than merely failing to match a handler pattern.
  3774. auto handler_called = false;
  3775. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3776. handler_called = true;
  3777. res.status = StatusCode::OK_200;
  3778. return Server::HandlerResponse::Handled;
  3779. });
  3780. auto port = svr.bind_to_any_port(HOST);
  3781. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3782. auto se = detail::scope_exit([&] {
  3783. svr.stop();
  3784. thread.join();
  3785. ASSERT_FALSE(svr.is_running());
  3786. });
  3787. svr.wait_until_ready();
  3788. {
  3789. Client cli(HOST, port);
  3790. cli.set_path_encode(false);
  3791. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3792. EXPECT_FALSE(handle.is_valid());
  3793. EXPECT_EQ(Error::Write, handle.error);
  3794. EXPECT_FALSE(handler_called);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3798. // Which of the two branches runs is decided by whether the query component
  3799. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3800. // an empty query and must still fall back to building one from
  3801. // `req.params`, while a non-empty query must win over `req.params`.
  3802. Server svr;
  3803. std::string target;
  3804. svr.Get("/foo", [&](const Request &req, Response &res) {
  3805. target = req.target;
  3806. res.status = StatusCode::OK_200;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. // Trailing `?` -> empty query component -> `req.params` is used.
  3818. Client cli(HOST, port);
  3819. Request req;
  3820. req.method = "GET";
  3821. req.path = "/foo?";
  3822. req.params.emplace("a", "1");
  3823. target.clear();
  3824. auto res = cli.send(req);
  3825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3826. EXPECT_EQ("/foo?a=1", target);
  3827. }
  3828. {
  3829. // Non-empty query in `req.path` -> `req.params` is not appended.
  3830. Client cli(HOST, port);
  3831. Request req;
  3832. req.method = "GET";
  3833. req.path = "/foo?b=2";
  3834. req.params.emplace("a", "1");
  3835. target.clear();
  3836. auto res = cli.send(req);
  3837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3838. EXPECT_EQ("/foo?b=2", target);
  3839. }
  3840. }
  3841. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3842. Server svr;
  3843. svr.Get("/", [](const Request &req, Response &) {
  3844. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3845. });
  3846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3847. auto se = detail::scope_exit([&] {
  3848. svr.stop();
  3849. thread.join();
  3850. ASSERT_FALSE(svr.is_running());
  3851. });
  3852. svr.wait_until_ready();
  3853. {
  3854. Client cli(HOST, PORT);
  3855. cli.set_path_encode(false);
  3856. auto res = cli.Get("/?something=%0A");
  3857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3858. EXPECT_EQ(StatusCode::OK_200, res->status);
  3859. }
  3860. }
  3861. TEST(BindServerTest, BindDualStack) {
  3862. Server svr;
  3863. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3864. res.set_content("Hello World!", "text/plain");
  3865. });
  3866. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. thread.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. {
  3874. Client cli("127.0.0.1", PORT);
  3875. auto res = cli.Get("/1");
  3876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. EXPECT_EQ("Hello World!", res->body);
  3879. }
  3880. {
  3881. Client cli("::1", PORT);
  3882. auto res = cli.Get("/1");
  3883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3884. EXPECT_EQ(StatusCode::OK_200, res->status);
  3885. EXPECT_EQ("Hello World!", res->body);
  3886. }
  3887. }
  3888. TEST(BindServerTest, BindAndListenSeparately) {
  3889. Server svr;
  3890. int port = svr.bind_to_any_port("0.0.0.0");
  3891. ASSERT_TRUE(svr.is_valid());
  3892. ASSERT_TRUE(port > 0);
  3893. svr.stop();
  3894. }
  3895. // Reports whether anything is still listening on a loopback port. A plain
  3896. // connect() is used instead of a Client request because a socket left bound by
  3897. // mistake accepts the connection into its backlog and never answers, which
  3898. // would hang the test instead of failing it.
  3899. static bool is_loopback_port_accepting(int port) {
  3900. sockaddr_in addr{};
  3901. addr.sin_family = AF_INET;
  3902. addr.sin_port = htons(static_cast<uint16_t>(port));
  3903. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3904. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3905. EXPECT_NE(sock, INVALID_SOCKET);
  3906. if (sock == INVALID_SOCKET) { return false; }
  3907. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3908. static_cast<socklen_t>(sizeof(addr)));
  3909. detail::close_socket(sock);
  3910. return ret == 0;
  3911. }
  3912. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3913. Server svr;
  3914. auto port = svr.bind_to_any_port("127.0.0.1");
  3915. ASSERT_TRUE(port > 0);
  3916. svr.stop();
  3917. // bind_to_any_port() already called listen(2), so until stop() closed the
  3918. // descriptor the port kept accepting connections into the backlog. ASSERT
  3919. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3920. // below blocks forever in the accept loop.
  3921. ASSERT_FALSE(is_loopback_port_accepting(port));
  3922. // Nothing is left to accept on, so listen_after_bind() must report failure
  3923. // instead of returning success without ever serving.
  3924. EXPECT_FALSE(svr.listen_after_bind());
  3925. // The failed listen marks the server decommissioned, so a waiter returns
  3926. // instead of spinning forever.
  3927. svr.wait_until_ready();
  3928. }
  3929. #ifdef CPPHTTPLIB_SSL_ENABLED
  3930. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3932. CLIENT_CA_CERT_DIR);
  3933. int port = svr.bind_to_any_port("0.0.0.0");
  3934. ASSERT_TRUE(svr.is_valid());
  3935. ASSERT_TRUE(port > 0);
  3936. svr.stop();
  3937. }
  3938. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3939. // or a rejected CustomRoute() registration would not stop the server binding.
  3940. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3942. CLIENT_CA_CERT_DIR);
  3943. ASSERT_TRUE(svr.is_valid());
  3944. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3945. EXPECT_FALSE(svr.is_valid());
  3946. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3947. }
  3948. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3949. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3950. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3951. int port = svr.bind_to_any_port("0.0.0.0");
  3952. ASSERT_TRUE(svr.is_valid());
  3953. ASSERT_TRUE(port > 0);
  3954. svr.stop();
  3955. }
  3956. TEST(BindServerTest, UpdateCertsPem) {
  3957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. // Read PEM files
  3962. std::string cert_pem, key_pem, ca_pem;
  3963. read_file(SERVER_CERT_FILE, cert_pem);
  3964. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3965. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3966. // Update server certificates using PEM API
  3967. ASSERT_TRUE(
  3968. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3969. ASSERT_TRUE(svr.is_valid());
  3970. svr.stop();
  3971. }
  3972. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3973. // Start server with client CA (enables client auth)
  3974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3975. ASSERT_TRUE(svr.is_valid());
  3976. bool handler_called = false;
  3977. svr.Get("/test", [&](const Request &req, Response &res) {
  3978. handler_called = true;
  3979. // Verify client certificate is present
  3980. auto cert = req.peer_cert();
  3981. EXPECT_TRUE(static_cast<bool>(cert));
  3982. res.set_content("ok", "text/plain");
  3983. });
  3984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3985. auto se = detail::scope_exit([&] {
  3986. svr.stop();
  3987. t.join();
  3988. ASSERT_FALSE(svr.is_running());
  3989. });
  3990. svr.wait_until_ready();
  3991. // Read PEM files
  3992. std::string cert_pem, key_pem, ca_pem;
  3993. read_file(SERVER_CERT_FILE, cert_pem);
  3994. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3995. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3996. // Update server certificates and client CA using PEM API while server running
  3997. ASSERT_TRUE(
  3998. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3999. // Connect with client certificate
  4000. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4001. cli.enable_server_certificate_verification(false);
  4002. cli.set_connection_timeout(30);
  4003. auto res = cli.Get("/test");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. ASSERT_EQ(StatusCode::OK_200, res->status);
  4006. ASSERT_TRUE(handler_called);
  4007. EXPECT_EQ("ok", res->body);
  4008. }
  4009. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.Get("/test", [](const Request &, Response &res) {
  4013. res.set_content("ok", "text/plain");
  4014. });
  4015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. t.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. auto get = [] {
  4023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4024. cli.enable_server_certificate_verification(false);
  4025. return cli.Get("/test");
  4026. };
  4027. ASSERT_TRUE(get());
  4028. // A CA that did not sign the client's certificate takes the old one's place.
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(SERVER_CERT2_FILE, ca_pem);
  4033. ASSERT_TRUE(
  4034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4035. EXPECT_FALSE(get());
  4036. }
  4037. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.Get("/test", [](const Request &, Response &res) {
  4041. res.set_content("ok", "text/plain");
  4042. });
  4043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4044. auto se = detail::scope_exit([&] {
  4045. svr.stop();
  4046. t.join();
  4047. ASSERT_FALSE(svr.is_running());
  4048. });
  4049. svr.wait_until_ready();
  4050. // A connection that sends no ClientHello keeps its handshake in progress,
  4051. // once the server has had a moment to start it.
  4052. auto error = Error::Success;
  4053. auto sock = detail::create_client_socket(
  4054. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4055. /*connection_timeout_sec=*/5, 0,
  4056. /*read_timeout_sec=*/5, 0,
  4057. /*write_timeout_sec=*/5, 0, std::string(), error);
  4058. ASSERT_NE(INVALID_SOCKET, sock);
  4059. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4060. std::string cert_pem, key_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. auto update = std::async(std::launch::async, [&]() {
  4064. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4065. });
  4066. EXPECT_EQ(std::future_status::timeout,
  4067. update.wait_for(std::chrono::milliseconds(200)));
  4068. detail::close_socket(sock);
  4069. EXPECT_TRUE(update.get());
  4070. SSLClient cli(HOST, PORT);
  4071. cli.enable_server_certificate_verification(false);
  4072. auto res = cli.Get("/test");
  4073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. }
  4076. #endif
  4077. TEST(ErrorHandlerTest, ContentLength) {
  4078. Server svr;
  4079. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4080. res.status = StatusCode::OK_200;
  4081. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4082. "text/html"); // <= Content-Length still 13
  4083. });
  4084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4085. res.set_content("Hello World!\n", "text/plain");
  4086. res.status = 524;
  4087. });
  4088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4089. auto se = detail::scope_exit([&] {
  4090. svr.stop();
  4091. thread.join();
  4092. ASSERT_FALSE(svr.is_running());
  4093. });
  4094. svr.wait_until_ready();
  4095. {
  4096. Client cli(HOST, PORT);
  4097. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4101. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4103. }
  4104. }
  4105. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4106. TEST(ExceptionTest, WithoutExceptionHandler) {
  4107. Server svr;
  4108. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4109. throw std::runtime_error("exception...");
  4110. });
  4111. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4112. throw std::runtime_error("exception\r\n...");
  4113. });
  4114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4115. auto se = detail::scope_exit([&] {
  4116. svr.stop();
  4117. listen_thread.join();
  4118. ASSERT_FALSE(svr.is_running());
  4119. });
  4120. svr.wait_until_ready();
  4121. Client cli("localhost", PORT);
  4122. {
  4123. auto res = cli.Get("/exception");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4126. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4127. }
  4128. {
  4129. auto res = cli.Get("/unknown");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4132. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4133. }
  4134. }
  4135. TEST(ExceptionTest, WithExceptionHandler) {
  4136. Server svr;
  4137. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4138. std::exception_ptr ep) {
  4139. EXPECT_FALSE(ep == nullptr);
  4140. try {
  4141. std::rethrow_exception(ep);
  4142. } catch (std::exception &e) {
  4143. EXPECT_EQ("abc", std::string(e.what()));
  4144. } catch (...) {}
  4145. res.status = StatusCode::InternalServerError_500;
  4146. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4147. "text/html"); // <= Content-Length still 13 at this point
  4148. });
  4149. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4150. res.set_content("Hello World!\n", "text/plain");
  4151. throw std::runtime_error("abc");
  4152. });
  4153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4154. auto se = detail::scope_exit([&] {
  4155. svr.stop();
  4156. thread.join();
  4157. ASSERT_FALSE(svr.is_running());
  4158. });
  4159. svr.wait_until_ready();
  4160. for (size_t i = 0; i < 10; i++) {
  4161. Client cli(HOST, PORT);
  4162. for (size_t j = 0; j < 100; j++) {
  4163. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4166. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4167. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4169. }
  4170. cli.set_keep_alive(true);
  4171. for (size_t j = 0; j < 100; j++) {
  4172. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4174. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4176. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4178. }
  4179. }
  4180. }
  4181. TEST(ExceptionTest, AndErrorHandler) {
  4182. Server svr;
  4183. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4184. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4185. });
  4186. svr.set_exception_handler(
  4187. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4188. EXPECT_FALSE(ep == nullptr);
  4189. try {
  4190. std::rethrow_exception(ep);
  4191. } catch (std::exception &e) {
  4192. res.set_content(e.what(), "text/html");
  4193. } catch (...) {}
  4194. res.status = StatusCode::InternalServerError_500;
  4195. });
  4196. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4197. throw std::runtime_error("EXCEPTION");
  4198. });
  4199. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4200. res.set_content("ERROR", "text/html");
  4201. res.status = StatusCode::InternalServerError_500;
  4202. });
  4203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. thread.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. Client cli(HOST, PORT);
  4211. {
  4212. auto res = cli.Get("/exception");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4215. EXPECT_EQ("EXCEPTION", res->body);
  4216. }
  4217. {
  4218. auto res = cli.Get("/error");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4221. EXPECT_EQ("ERROR", res->body);
  4222. }
  4223. {
  4224. auto res = cli.Get("/invalid");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4227. EXPECT_EQ("NOT_FOUND", res->body);
  4228. }
  4229. }
  4230. #endif
  4231. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4232. // process_request() wraps only routing() in a try/catch, so an exception from
  4233. // any other user callback used to unwind into the task queue - which does not
  4234. // catch - and terminate the process. Each test below runs the server on a
  4235. // single worker thread: a guard that catches the exception but still loses the
  4236. // thread would otherwise be hidden by a spare worker serving the follow-up
  4237. // request. Note that a regression here aborts the whole test binary rather
  4238. // than failing one test.
  4239. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4240. Server svr;
  4241. svr.new_task_queue = [] { return new ThreadPool(1); };
  4242. std::atomic<int> reported{0};
  4243. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4244. if (err == Error::UserCallbackException) { reported++; }
  4245. });
  4246. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4247. res.set_content_provider(
  4248. 1024, "text/plain",
  4249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4250. sink.write("hello", 5);
  4251. throw std::runtime_error("from the content provider");
  4252. });
  4253. });
  4254. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("ok", "text/plain");
  4256. });
  4257. auto port = svr.bind_to_any_port(HOST);
  4258. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. listen_thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, port);
  4267. cli.set_read_timeout(5, 0);
  4268. EXPECT_FALSE(cli.Get("/throw"));
  4269. }
  4270. EXPECT_TRUE(svr.is_running());
  4271. EXPECT_EQ(1, reported.load());
  4272. // A request on a fresh connection is still served.
  4273. {
  4274. Client cli(HOST, port);
  4275. auto res = cli.Get("/ok");
  4276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4277. EXPECT_EQ(StatusCode::OK_200, res->status);
  4278. EXPECT_EQ("ok", res->body);
  4279. }
  4280. }
  4281. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4282. Server svr;
  4283. svr.new_task_queue = [] { return new ThreadPool(1); };
  4284. std::atomic<bool> should_throw{true};
  4285. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4286. res.set_content("hi", "text/plain");
  4287. });
  4288. svr.set_post_routing_handler(
  4289. [&](const Request & /*req*/, Response & /*res*/) {
  4290. if (should_throw) {
  4291. throw std::runtime_error("from the post-routing handler");
  4292. }
  4293. });
  4294. auto port = svr.bind_to_any_port(HOST);
  4295. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4296. auto se = detail::scope_exit([&] {
  4297. svr.stop();
  4298. listen_thread.join();
  4299. ASSERT_FALSE(svr.is_running());
  4300. });
  4301. svr.wait_until_ready();
  4302. {
  4303. Client cli(HOST, port);
  4304. cli.set_read_timeout(5, 0);
  4305. EXPECT_FALSE(cli.Get("/hi"));
  4306. }
  4307. EXPECT_TRUE(svr.is_running());
  4308. should_throw = false;
  4309. {
  4310. Client cli(HOST, port);
  4311. auto res = cli.Get("/hi");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ("hi", res->body);
  4315. }
  4316. }
  4317. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4318. // The guard reports the caught exception through the error logger, which is
  4319. // a user callback too. A logger that throws has to be contained as well, or
  4320. // the process would terminate from inside the catch.
  4321. Server svr;
  4322. svr.new_task_queue = [] { return new ThreadPool(1); };
  4323. std::atomic<int> reported{0};
  4324. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4325. if (err == Error::UserCallbackException) {
  4326. reported++;
  4327. throw std::runtime_error("from the error logger");
  4328. }
  4329. });
  4330. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4331. res.set_content_provider(
  4332. 1024, "text/plain",
  4333. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4334. sink.write("hello", 5);
  4335. throw std::runtime_error("from the content provider");
  4336. });
  4337. });
  4338. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4339. res.set_content("ok", "text/plain");
  4340. });
  4341. auto port = svr.bind_to_any_port(HOST);
  4342. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4343. auto se = detail::scope_exit([&] {
  4344. svr.stop();
  4345. listen_thread.join();
  4346. ASSERT_FALSE(svr.is_running());
  4347. });
  4348. svr.wait_until_ready();
  4349. {
  4350. Client cli(HOST, port);
  4351. cli.set_read_timeout(5, 0);
  4352. EXPECT_FALSE(cli.Get("/throw"));
  4353. }
  4354. EXPECT_TRUE(svr.is_running());
  4355. EXPECT_EQ(1, reported.load());
  4356. {
  4357. Client cli(HOST, port);
  4358. auto res = cli.Get("/ok");
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("ok", res->body);
  4362. }
  4363. }
  4364. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4365. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4366. // so the exception unwinds through the ws::WebSocket object on its way to
  4367. // the guard. None of the HTTP cases above cross that.
  4368. Server svr;
  4369. svr.new_task_queue = [] { return new ThreadPool(1); };
  4370. std::atomic<int> reported{0};
  4371. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4372. if (err == Error::UserCallbackException) { reported++; }
  4373. });
  4374. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4375. throw std::runtime_error("from the WebSocket handler");
  4376. });
  4377. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4378. res.set_content("ok", "text/plain");
  4379. });
  4380. auto port = svr.bind_to_any_port(HOST);
  4381. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. listen_thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4390. "/ws");
  4391. auto res = client.connect();
  4392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4393. // The server dropped the connection instead of dying.
  4394. std::string msg;
  4395. EXPECT_FALSE(client.read(msg));
  4396. client.close();
  4397. }
  4398. EXPECT_TRUE(svr.is_running());
  4399. EXPECT_EQ(1, reported.load());
  4400. {
  4401. Client cli(HOST, port);
  4402. auto res = cli.Get("/ok");
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ("ok", res->body);
  4406. }
  4407. }
  4408. #ifdef CPPHTTPLIB_SSL_ENABLED
  4409. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4410. // SSLServer::process_and_close_socket() is a separate overload with its own
  4411. // guard, so it is exercised on its own.
  4412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4413. ASSERT_TRUE(svr.is_valid());
  4414. svr.new_task_queue = [] { return new ThreadPool(1); };
  4415. std::atomic<int> reported{0};
  4416. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4417. if (err == Error::UserCallbackException) { reported++; }
  4418. });
  4419. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4420. res.set_content_provider(
  4421. 1024, "text/plain",
  4422. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4423. sink.write("hello", 5);
  4424. throw std::runtime_error("from the content provider");
  4425. });
  4426. });
  4427. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("ok", "text/plain");
  4429. });
  4430. auto port = svr.bind_to_any_port(HOST);
  4431. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. listen_thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. {
  4439. SSLClient cli(HOST, port);
  4440. cli.enable_server_certificate_verification(false);
  4441. cli.set_read_timeout(5, 0);
  4442. EXPECT_FALSE(cli.Get("/throw"));
  4443. }
  4444. EXPECT_TRUE(svr.is_running());
  4445. EXPECT_EQ(1, reported.load());
  4446. {
  4447. SSLClient cli(HOST, port);
  4448. cli.enable_server_certificate_verification(false);
  4449. auto res = cli.Get("/ok");
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::OK_200, res->status);
  4452. EXPECT_EQ("ok", res->body);
  4453. }
  4454. }
  4455. #endif
  4456. #endif
  4457. TEST(NoContentTest, ContentLength) {
  4458. Server svr;
  4459. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4460. res.status = StatusCode::NoContent_204;
  4461. });
  4462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4463. auto se = detail::scope_exit([&] {
  4464. svr.stop();
  4465. thread.join();
  4466. ASSERT_FALSE(svr.is_running());
  4467. });
  4468. svr.wait_until_ready();
  4469. {
  4470. Client cli(HOST, PORT);
  4471. auto res = cli.Get("/hi");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4474. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4475. }
  4476. }
  4477. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4478. #ifdef CPPHTTPLIB_SSL_ENABLED
  4479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4480. ASSERT_TRUE(svr.is_valid());
  4481. #else
  4482. Server svr;
  4483. #endif
  4484. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4485. if (req.path == "/routing_handler") {
  4486. res.set_header("PRE_ROUTING", "on");
  4487. res.set_content("Routing Handler", "text/plain");
  4488. return httplib::Server::HandlerResponse::Handled;
  4489. }
  4490. return httplib::Server::HandlerResponse::Unhandled;
  4491. });
  4492. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4493. res.set_content("Error", "text/html");
  4494. });
  4495. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4496. if (req.path == "/routing_handler") {
  4497. res.set_header("POST_ROUTING", "on");
  4498. }
  4499. });
  4500. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4501. res.set_content("Hello World!\n", "text/plain");
  4502. });
  4503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4504. auto se = detail::scope_exit([&] {
  4505. svr.stop();
  4506. thread.join();
  4507. ASSERT_FALSE(svr.is_running());
  4508. });
  4509. svr.wait_until_ready();
  4510. {
  4511. #ifdef CPPHTTPLIB_SSL_ENABLED
  4512. SSLClient cli(HOST, PORT);
  4513. cli.enable_server_certificate_verification(false);
  4514. #else
  4515. Client cli(HOST, PORT);
  4516. #endif
  4517. auto res = cli.Get("/routing_handler");
  4518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4519. EXPECT_EQ(StatusCode::OK_200, res->status);
  4520. EXPECT_EQ("Routing Handler", res->body);
  4521. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4522. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4523. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4524. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4525. }
  4526. {
  4527. #ifdef CPPHTTPLIB_SSL_ENABLED
  4528. SSLClient cli(HOST, PORT);
  4529. cli.enable_server_certificate_verification(false);
  4530. #else
  4531. Client cli(HOST, PORT);
  4532. #endif
  4533. auto res = cli.Get("/hi");
  4534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ("Hello World!\n", res->body);
  4537. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4538. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4539. }
  4540. {
  4541. #ifdef CPPHTTPLIB_SSL_ENABLED
  4542. SSLClient cli(HOST, PORT);
  4543. cli.enable_server_certificate_verification(false);
  4544. #else
  4545. Client cli(HOST, PORT);
  4546. #endif
  4547. auto res = cli.Get("/aaa");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4550. EXPECT_EQ("Error", res->body);
  4551. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4552. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4553. }
  4554. }
  4555. TEST(RequestHandlerTest, PreRequestHandler) {
  4556. auto route_path = "/user/:user";
  4557. Server svr;
  4558. svr.Get("/hi", [](const Request &, Response &res) {
  4559. res.set_content("hi", "text/plain");
  4560. });
  4561. svr.Get(route_path, [](const Request &req, Response &res) {
  4562. res.set_content(req.path_params.at("user"), "text/plain");
  4563. });
  4564. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4565. if (req.matched_route == route_path) {
  4566. auto user = req.path_params.at("user");
  4567. if (user != "john") {
  4568. res.status = StatusCode::Forbidden_403;
  4569. res.set_content("error", "text/html");
  4570. return Server::HandlerResponse::Handled;
  4571. }
  4572. }
  4573. return Server::HandlerResponse::Unhandled;
  4574. });
  4575. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4576. auto se = detail::scope_exit([&] {
  4577. svr.stop();
  4578. thread.join();
  4579. ASSERT_FALSE(svr.is_running());
  4580. });
  4581. svr.wait_until_ready();
  4582. Client cli(HOST, PORT);
  4583. {
  4584. auto res = cli.Get("/hi");
  4585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4586. EXPECT_EQ(StatusCode::OK_200, res->status);
  4587. EXPECT_EQ("hi", res->body);
  4588. }
  4589. {
  4590. auto res = cli.Get("/user/john");
  4591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. EXPECT_EQ("john", res->body);
  4594. }
  4595. {
  4596. auto res = cli.Get("/user/invalid-user");
  4597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4598. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4599. EXPECT_EQ("error", res->body);
  4600. }
  4601. }
  4602. // The pre-request handler must run before the request body is read, so a
  4603. // rejected request never forces the server to buffer a (potentially large)
  4604. // body. Here the posted body is larger than the payload limit: if the body
  4605. // were read first the server would answer 413, but because the pre-request
  4606. // handler runs first it answers 403 and the body is never read.
  4607. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4608. Server svr;
  4609. svr.set_payload_max_length(8);
  4610. auto handler_ran = false;
  4611. svr.Post("/reject", [&](const Request &req, Response &res) {
  4612. handler_ran = true;
  4613. res.set_content(req.body, "text/plain");
  4614. });
  4615. svr.Post("/accept", [](const Request &req, Response &res) {
  4616. res.set_content(req.body, "text/plain");
  4617. });
  4618. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4619. if (req.matched_route == "/reject") {
  4620. res.status = StatusCode::Forbidden_403;
  4621. res.set_content("denied", "text/plain");
  4622. return Server::HandlerResponse::Handled;
  4623. }
  4624. return Server::HandlerResponse::Unhandled;
  4625. });
  4626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4627. auto se = detail::scope_exit([&] {
  4628. svr.stop();
  4629. thread.join();
  4630. ASSERT_FALSE(svr.is_running());
  4631. });
  4632. svr.wait_until_ready();
  4633. Client cli(HOST, PORT);
  4634. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4635. // rejects with 403 before the body is read, so 413 is never reached.
  4636. {
  4637. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4640. EXPECT_EQ("denied", res->body);
  4641. EXPECT_FALSE(handler_ran);
  4642. }
  4643. // An approved route still reads the body and enforces the payload limit.
  4644. {
  4645. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4647. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4648. }
  4649. }
  4650. TEST(UserDataTest, BasicOperations) {
  4651. httplib::UserData ud;
  4652. // Initially empty
  4653. EXPECT_FALSE(ud.has("key"));
  4654. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4655. // set and get
  4656. ud.set("key", 42);
  4657. EXPECT_TRUE(ud.has("key"));
  4658. auto *p = ud.get<int>("key");
  4659. ASSERT_NE(nullptr, p);
  4660. EXPECT_EQ(42, *p);
  4661. // Type mismatch → nullptr
  4662. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4663. // Overwrite with different type
  4664. ud.set("key", std::string("hello"));
  4665. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4666. auto *s = ud.get<std::string>("key");
  4667. ASSERT_NE(nullptr, s);
  4668. EXPECT_EQ("hello", *s);
  4669. // erase
  4670. ud.erase("key");
  4671. EXPECT_FALSE(ud.has("key"));
  4672. // clear
  4673. ud.set("a", 1);
  4674. ud.set("b", 2);
  4675. ud.clear();
  4676. EXPECT_FALSE(ud.has("a"));
  4677. EXPECT_FALSE(ud.has("b"));
  4678. }
  4679. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4680. struct AuthCtx {
  4681. std::string user_id;
  4682. };
  4683. Server svr;
  4684. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4685. res.user_data.set("auth", AuthCtx{"alice"});
  4686. return Server::HandlerResponse::Unhandled;
  4687. });
  4688. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4689. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4690. ASSERT_NE(nullptr, ctx);
  4691. res.set_content("Hello " + ctx->user_id, "text/plain");
  4692. });
  4693. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4694. auto se = detail::scope_exit([&] {
  4695. svr.stop();
  4696. thread.join();
  4697. ASSERT_FALSE(svr.is_running());
  4698. });
  4699. svr.wait_until_ready();
  4700. Client cli(HOST, PORT);
  4701. auto res = cli.Get("/me");
  4702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("Hello alice", res->body);
  4705. }
  4706. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4707. struct RoleCtx {
  4708. std::string role;
  4709. };
  4710. Server svr;
  4711. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4712. res.user_data.set("role", RoleCtx{"admin"});
  4713. return Server::HandlerResponse::Unhandled;
  4714. });
  4715. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4716. auto *ctx = res.user_data.get<RoleCtx>("role");
  4717. ASSERT_NE(nullptr, ctx);
  4718. res.set_content(ctx->role, "text/plain");
  4719. });
  4720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4721. auto se = detail::scope_exit([&] {
  4722. svr.stop();
  4723. thread.join();
  4724. ASSERT_FALSE(svr.is_running());
  4725. });
  4726. svr.wait_until_ready();
  4727. Client cli(HOST, PORT);
  4728. auto res = cli.Get("/role");
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ("admin", res->body);
  4732. }
  4733. TEST(InvalidFormatTest, StatusCode) {
  4734. Server svr;
  4735. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4736. res.set_content("Hello World!\n", "text/plain");
  4737. res.status = 9999; // Status should be a three-digit code...
  4738. });
  4739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4740. auto se = detail::scope_exit([&] {
  4741. svr.stop();
  4742. thread.join();
  4743. ASSERT_FALSE(svr.is_running());
  4744. });
  4745. svr.wait_until_ready();
  4746. {
  4747. Client cli(HOST, PORT);
  4748. auto res = cli.Get("/hi");
  4749. ASSERT_FALSE(res);
  4750. }
  4751. }
  4752. TEST(URLFragmentTest, WithFragment) {
  4753. Server svr;
  4754. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4755. EXPECT_TRUE(req.target == "/hi");
  4756. });
  4757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4758. auto se = detail::scope_exit([&] {
  4759. svr.stop();
  4760. thread.join();
  4761. ASSERT_FALSE(svr.is_running());
  4762. });
  4763. svr.wait_until_ready();
  4764. {
  4765. Client cli(HOST, PORT);
  4766. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4767. EXPECT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::OK_200, res->status);
  4769. res = cli.Get("/hi%23key1=val1=key2=val2");
  4770. EXPECT_TRUE(res);
  4771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4772. }
  4773. }
  4774. TEST(HeaderWriter, SetHeaderWriter) {
  4775. Server svr;
  4776. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4777. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4778. return detail::write_headers(strm, hdrs);
  4779. });
  4780. svr.Get("/hi", [](const Request &req, Response &res) {
  4781. auto it = req.headers.find("CustomClientHeader");
  4782. EXPECT_TRUE(it != req.headers.end());
  4783. EXPECT_EQ(it->second, "CustomClientValue");
  4784. res.set_content("Hello World!\n", "text/plain");
  4785. });
  4786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4787. auto se = detail::scope_exit([&] {
  4788. svr.stop();
  4789. thread.join();
  4790. ASSERT_FALSE(svr.is_running());
  4791. });
  4792. svr.wait_until_ready();
  4793. {
  4794. Client cli(HOST, PORT);
  4795. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4796. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4797. return detail::write_headers(strm, hdrs);
  4798. });
  4799. auto res = cli.Get("/hi");
  4800. EXPECT_TRUE(res);
  4801. EXPECT_EQ(StatusCode::OK_200, res->status);
  4802. auto it = res->headers.find("CustomServerHeader");
  4803. EXPECT_TRUE(it != res->headers.end());
  4804. EXPECT_EQ(it->second, "CustomServerValue");
  4805. }
  4806. }
  4807. class ServerTest : public ::testing::Test {
  4808. protected:
  4809. ServerTest()
  4810. : cli_(HOST, PORT)
  4811. #ifdef CPPHTTPLIB_SSL_ENABLED
  4812. ,
  4813. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4814. #endif
  4815. {
  4816. #ifdef CPPHTTPLIB_SSL_ENABLED
  4817. cli_.enable_server_certificate_verification(false);
  4818. #endif
  4819. // Allow LARGE_DATA (100MB) responses
  4820. cli_.set_payload_max_length(200 * 1024 * 1024);
  4821. }
  4822. virtual void SetUp() {
  4823. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4824. svr_.set_payload_max_length(200 * 1024 * 1024);
  4825. svr_.set_mount_point("/", "./www");
  4826. svr_.set_mount_point("/mount", "./www2");
  4827. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4828. svr_.Get("/hi",
  4829. [&](const Request & /*req*/, Response &res) {
  4830. res.set_content("Hello World!", "text/plain");
  4831. })
  4832. .Get("/file_content",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_file_content("./www/dir/test.html");
  4835. })
  4836. .Get("/file_content_with_content_type",
  4837. [&](const Request & /*req*/, Response &res) {
  4838. res.set_file_content("./www/file", "text/plain");
  4839. })
  4840. .Get("/invalid_file_content",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_file_content("./www/dir/invalid_file_path");
  4843. })
  4844. .Get("/http_response_splitting",
  4845. [&](const Request & /*req*/, Response &res) {
  4846. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4847. EXPECT_EQ(0U, res.headers.size());
  4848. EXPECT_FALSE(res.has_header("a"));
  4849. res.set_header("a", "1\nSet-Cookie: a=1");
  4850. EXPECT_EQ(0U, res.headers.size());
  4851. EXPECT_FALSE(res.has_header("a"));
  4852. res.set_header("a", "1\rSet-Cookie: a=1");
  4853. EXPECT_EQ(0U, res.headers.size());
  4854. EXPECT_FALSE(res.has_header("a"));
  4855. res.set_header("a\r\nb", "0");
  4856. EXPECT_EQ(0U, res.headers.size());
  4857. EXPECT_FALSE(res.has_header("a"));
  4858. res.set_header("a\rb", "0");
  4859. EXPECT_EQ(0U, res.headers.size());
  4860. EXPECT_FALSE(res.has_header("a"));
  4861. res.set_header("a\nb", "0");
  4862. EXPECT_EQ(0U, res.headers.size());
  4863. EXPECT_FALSE(res.has_header("a"));
  4864. res.set_redirect("1\r\nSet-Cookie: a=1");
  4865. EXPECT_EQ(0U, res.headers.size());
  4866. EXPECT_FALSE(res.has_header("Location"));
  4867. })
  4868. .Get("/slow",
  4869. [&](const Request & /*req*/, Response &res) {
  4870. std::this_thread::sleep_for(std::chrono::seconds(4));
  4871. res.set_content("slow", "text/plain");
  4872. })
  4873. #if 0
  4874. .Post("/slowpost",
  4875. [&](const Request & /*req*/, Response &res) {
  4876. std::this_thread::sleep_for(std::chrono::seconds(2));
  4877. res.set_content("slow", "text/plain");
  4878. })
  4879. #endif
  4880. .Get("/remote_addr",
  4881. [&](const Request &req, Response &res) {
  4882. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4883. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4884. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4885. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4886. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4887. #endif
  4888. res.set_content(req.remote_addr, "text/plain");
  4889. })
  4890. .Get("/local_addr",
  4891. [&](const Request &req, Response &res) {
  4892. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4893. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4894. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4895. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4896. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4897. #endif
  4898. auto local_addr = req.local_addr;
  4899. auto local_port = std::to_string(req.local_port);
  4900. res.set_content(local_addr.append(":").append(local_port),
  4901. "text/plain");
  4902. })
  4903. .Get("/endwith%",
  4904. [&](const Request & /*req*/, Response &res) {
  4905. res.set_content("Hello World!", "text/plain");
  4906. })
  4907. .Get("/a\\+\\+b",
  4908. [&](const Request &req, Response &res) {
  4909. ASSERT_TRUE(req.has_param("a +b"));
  4910. auto val = req.get_param_value("a +b");
  4911. res.set_content(val, "text/plain");
  4912. })
  4913. .Get("/", [&](const Request & /*req*/,
  4914. Response &res) { res.set_redirect("/hi"); })
  4915. .Post("/1",
  4916. [](const Request & /*req*/, Response &res) {
  4917. res.set_redirect("/2", StatusCode::SeeOther_303);
  4918. })
  4919. .Get("/2",
  4920. [](const Request & /*req*/, Response &res) {
  4921. res.set_content("redirected.", "text/plain");
  4922. res.status = StatusCode::OK_200;
  4923. })
  4924. .Post("/person",
  4925. [&](const Request &req, Response &res) {
  4926. if (req.has_param("name") && req.has_param("note")) {
  4927. persons_[req.get_param_value("name")] =
  4928. req.get_param_value("note");
  4929. } else {
  4930. res.status = StatusCode::BadRequest_400;
  4931. }
  4932. })
  4933. .Put("/person",
  4934. [&](const Request &req, Response &res) {
  4935. if (req.has_param("name") && req.has_param("note")) {
  4936. persons_[req.get_param_value("name")] =
  4937. req.get_param_value("note");
  4938. } else {
  4939. res.status = StatusCode::BadRequest_400;
  4940. }
  4941. })
  4942. .Get("/person/(.*)",
  4943. [&](const Request &req, Response &res) {
  4944. string name = req.matches[1];
  4945. if (persons_.find(name) != persons_.end()) {
  4946. auto note = persons_[name];
  4947. res.set_content(note, "text/plain");
  4948. } else {
  4949. res.status = StatusCode::NotFound_404;
  4950. }
  4951. })
  4952. .Delete("/person",
  4953. [&](const Request &req, Response &res) {
  4954. if (req.has_param("name")) {
  4955. string name = req.get_param_value("name");
  4956. if (persons_.find(name) != persons_.end()) {
  4957. persons_.erase(name);
  4958. res.set_content("DELETED", "text/plain");
  4959. } else {
  4960. res.status = StatusCode::NotFound_404;
  4961. }
  4962. } else {
  4963. res.status = StatusCode::BadRequest_400;
  4964. }
  4965. })
  4966. .Post("/x-www-form-urlencoded-json",
  4967. [&](const Request &req, Response &res) {
  4968. auto json = req.get_param_value("json");
  4969. ASSERT_EQ(JSON_DATA, json);
  4970. res.set_content(json, "appliation/json");
  4971. res.status = StatusCode::OK_200;
  4972. })
  4973. .Get("/streamed-chunked",
  4974. [&](const Request & /*req*/, Response &res) {
  4975. res.set_chunked_content_provider(
  4976. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4977. sink.os << "123";
  4978. sink.os << "456";
  4979. sink.os << "789";
  4980. sink.done();
  4981. return true;
  4982. });
  4983. })
  4984. .Get("/streamed-chunked-with-prohibited-trailer",
  4985. [&](const Request & /*req*/, Response &res) {
  4986. auto i = new int(0);
  4987. // Declare both a prohibited trailer (Content-Length) and an
  4988. // allowed one
  4989. res.set_header("Trailer", "Content-Length, X-Allowed");
  4990. res.set_chunked_content_provider(
  4991. "text/plain",
  4992. [i](size_t /*offset*/, DataSink &sink) {
  4993. switch (*i) {
  4994. case 0: sink.os << "123"; break;
  4995. case 1: sink.os << "456"; break;
  4996. case 2: sink.os << "789"; break;
  4997. case 3: {
  4998. sink.done_with_trailer(
  4999. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5000. } break;
  5001. }
  5002. (*i)++;
  5003. return true;
  5004. },
  5005. [i](bool success) {
  5006. EXPECT_TRUE(success);
  5007. delete i;
  5008. });
  5009. })
  5010. .Get("/streamed-chunked2",
  5011. [&](const Request & /*req*/, Response &res) {
  5012. auto i = new int(0);
  5013. res.set_chunked_content_provider(
  5014. "text/plain",
  5015. [i](size_t /*offset*/, DataSink &sink) {
  5016. switch (*i) {
  5017. case 0: sink.os << "123"; break;
  5018. case 1: sink.os << "456"; break;
  5019. case 2: sink.os << "789"; break;
  5020. case 3: sink.done(); break;
  5021. }
  5022. (*i)++;
  5023. return true;
  5024. },
  5025. [i](bool success) {
  5026. EXPECT_TRUE(success);
  5027. delete i;
  5028. });
  5029. })
  5030. .Get("/streamed-chunked-with-trailer",
  5031. [&](const Request & /*req*/, Response &res) {
  5032. auto i = new int(0);
  5033. res.set_header("Trailer", "Dummy1, Dummy2");
  5034. res.set_chunked_content_provider(
  5035. "text/plain",
  5036. [i](size_t /*offset*/, DataSink &sink) {
  5037. switch (*i) {
  5038. case 0: sink.os << "123"; break;
  5039. case 1: sink.os << "456"; break;
  5040. case 2: sink.os << "789"; break;
  5041. case 3: {
  5042. sink.done_with_trailer(
  5043. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5044. } break;
  5045. }
  5046. (*i)++;
  5047. return true;
  5048. },
  5049. [i](bool success) {
  5050. EXPECT_TRUE(success);
  5051. delete i;
  5052. });
  5053. })
  5054. .Get("/streamed",
  5055. [&](const Request & /*req*/, Response &res) {
  5056. res.set_content_provider(
  5057. 6, "text/plain",
  5058. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5059. sink.os << (offset < 3 ? "a" : "b");
  5060. return true;
  5061. });
  5062. })
  5063. .Get("/streamed-without-length",
  5064. [&](const Request & /*req*/, Response &res) {
  5065. auto data = new std::string("abcdefg");
  5066. res.set_content_provider(
  5067. "text/plain",
  5068. [data](size_t offset, DataSink &sink) {
  5069. if (offset < data->size()) {
  5070. sink.os << data->substr(offset);
  5071. }
  5072. sink.done();
  5073. return true;
  5074. },
  5075. [data](bool success) {
  5076. EXPECT_TRUE(success);
  5077. delete data;
  5078. });
  5079. })
  5080. .Get("/streamed-with-range",
  5081. [&](const Request &req, Response &res) {
  5082. auto data = new std::string("abcdefg");
  5083. // An explicit status keeps the server from picking the 206 it
  5084. // would otherwise choose for a ranged request, so the response
  5085. // is not a partial representation.
  5086. auto status = req.get_param_value("status");
  5087. if (status == "200") {
  5088. res.status = StatusCode::OK_200;
  5089. } else if (status == "403") {
  5090. res.status = StatusCode::Forbidden_403;
  5091. }
  5092. res.set_content_provider(
  5093. data->size(), "text/plain",
  5094. [data](size_t offset, size_t length, DataSink &sink) {
  5095. size_t DATA_CHUNK_SIZE = 4;
  5096. const auto &d = *data;
  5097. auto out_len =
  5098. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5099. auto ret =
  5100. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5101. EXPECT_TRUE(ret);
  5102. return true;
  5103. },
  5104. [data, &req](bool success) {
  5105. EXPECT_EQ(success, !req.has_param("error"));
  5106. delete data;
  5107. });
  5108. })
  5109. .Get("/streamed-cancel",
  5110. [&](const Request & /*req*/, Response &res) {
  5111. res.set_content_provider(
  5112. size_t(-1), "text/plain",
  5113. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5114. sink.os << "data_chunk";
  5115. return true;
  5116. });
  5117. })
  5118. .Get("/regex-with-delimiter",
  5119. [&](const Request &req, Response & /*res*/) {
  5120. ASSERT_TRUE(req.has_param("key"));
  5121. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5122. })
  5123. .Get("/with-range",
  5124. [&](const Request & /*req*/, Response &res) {
  5125. res.set_content("abcdefg", "text/plain");
  5126. })
  5127. .Get("/test-start-time",
  5128. [&](const Request &req, Response & /*res*/) {
  5129. EXPECT_NE(req.start_time_,
  5130. std::chrono::steady_clock::time_point::min());
  5131. })
  5132. .Get("/with-range-customized-response",
  5133. [&](const Request & /*req*/, Response &res) {
  5134. res.status = StatusCode::BadRequest_400;
  5135. res.set_content(JSON_DATA, "application/json");
  5136. })
  5137. .Post("/chunked",
  5138. [&](const Request &req, Response & /*res*/) {
  5139. EXPECT_EQ(req.body, "dechunked post body");
  5140. })
  5141. .Post("/large-chunked",
  5142. [&](const Request &req, Response & /*res*/) {
  5143. std::string expected(6 * 30 * 1024u, 'a');
  5144. EXPECT_EQ(req.body, expected);
  5145. })
  5146. .Post("/multipart",
  5147. [&](const Request &req, Response & /*res*/) {
  5148. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5149. req.form.get_field_count("text2") +
  5150. req.form.get_field_count("file3") +
  5151. req.form.get_field_count("file4"));
  5152. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5153. req.form.get_file_count("file2"));
  5154. ASSERT_TRUE(!req.form.has_file("???"));
  5155. ASSERT_TRUE(!req.form.has_field("???"));
  5156. ASSERT_TRUE(req.body.empty());
  5157. {
  5158. const auto &text = req.form.get_field("text1");
  5159. EXPECT_EQ("text default", text);
  5160. }
  5161. {
  5162. const auto &text = req.form.get_field("text2");
  5163. EXPECT_EQ("aωb", text);
  5164. }
  5165. {
  5166. const auto &file = req.form.get_file("file1");
  5167. EXPECT_EQ("hello.txt", file.filename);
  5168. EXPECT_EQ("text/plain", file.content_type);
  5169. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5170. }
  5171. {
  5172. const auto &file = req.form.get_file("file2");
  5173. EXPECT_EQ("world.json", file.filename);
  5174. EXPECT_EQ("application/json", file.content_type);
  5175. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5176. }
  5177. {
  5178. const auto &text = req.form.get_field("file3");
  5179. EXPECT_EQ(0u, text.size());
  5180. }
  5181. {
  5182. const auto &text = req.form.get_field("file4");
  5183. EXPECT_EQ(0u, text.size());
  5184. }
  5185. })
  5186. .Post("/multipart/multi_file_values",
  5187. [&](const Request &req, Response & /*res*/) {
  5188. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5189. req.form.get_field_count("multi_text1"));
  5190. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5191. ASSERT_TRUE(!req.form.has_file("???"));
  5192. ASSERT_TRUE(!req.form.has_field("???"));
  5193. ASSERT_TRUE(req.body.empty());
  5194. {
  5195. const auto &text = req.form.get_field("text");
  5196. EXPECT_EQ("default text", text);
  5197. }
  5198. {
  5199. const auto &text1_values = req.form.get_fields("multi_text1");
  5200. EXPECT_EQ(2u, text1_values.size());
  5201. EXPECT_EQ("aaaaa", text1_values[0]);
  5202. EXPECT_EQ("bbbbb", text1_values[1]);
  5203. }
  5204. {
  5205. const auto &file1_values = req.form.get_files("multi_file1");
  5206. EXPECT_EQ(2u, file1_values.size());
  5207. auto file1 = file1_values[0];
  5208. EXPECT_EQ(file1.filename, "hello.txt");
  5209. EXPECT_EQ(file1.content_type, "text/plain");
  5210. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5211. auto file2 = file1_values[1];
  5212. EXPECT_EQ(file2.filename, "world.json");
  5213. EXPECT_EQ(file2.content_type, "application/json");
  5214. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5215. }
  5216. })
  5217. .Post("/empty",
  5218. [&](const Request &req, Response &res) {
  5219. EXPECT_EQ(req.body, "");
  5220. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5221. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5222. res.set_content("empty", "text/plain");
  5223. })
  5224. .Post("/empty-no-content-type",
  5225. [&](const Request &req, Response &res) {
  5226. EXPECT_EQ(req.body, "");
  5227. EXPECT_FALSE(req.has_header("Content-Type"));
  5228. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5229. res.set_content("empty-no-content-type", "text/plain");
  5230. })
  5231. .Post("/path-only",
  5232. [&](const Request &req, Response &res) {
  5233. EXPECT_EQ(req.body, "");
  5234. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5235. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5236. res.set_content("path-only", "text/plain");
  5237. })
  5238. .Post("/path-headers-only",
  5239. [&](const Request &req, Response &res) {
  5240. EXPECT_EQ(req.body, "");
  5241. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5242. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5243. EXPECT_EQ("world", req.get_header_value("hello"));
  5244. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5245. res.set_content("path-headers-only", "text/plain");
  5246. })
  5247. .Post("/post-large",
  5248. [&](const Request &req, Response &res) {
  5249. EXPECT_EQ(req.body, LARGE_DATA);
  5250. res.set_content(req.body, "text/plain");
  5251. })
  5252. .Post("/post-loopback",
  5253. [&](const Request &, Response &res,
  5254. ContentReader const &content_reader) {
  5255. std::string body;
  5256. content_reader([&](const char *data, size_t data_length) {
  5257. body.append(data, data_length);
  5258. return true;
  5259. });
  5260. res.set_content(body, "text/plain");
  5261. })
  5262. .Put("/put-loopback",
  5263. [&](const Request &, Response &res,
  5264. ContentReader const &content_reader) {
  5265. std::string body;
  5266. content_reader([&](const char *data, size_t data_length) {
  5267. body.append(data, data_length);
  5268. return true;
  5269. });
  5270. res.set_content(body, "text/plain");
  5271. })
  5272. .Patch("/patch-loopback",
  5273. [&](const Request &, Response &res,
  5274. ContentReader const &content_reader) {
  5275. std::string body;
  5276. content_reader([&](const char *data, size_t data_length) {
  5277. body.append(data, data_length);
  5278. return true;
  5279. });
  5280. res.set_content(body, "text/plain");
  5281. })
  5282. .Put("/empty-no-content-type",
  5283. [&](const Request &req, Response &res) {
  5284. EXPECT_EQ(req.body, "");
  5285. EXPECT_FALSE(req.has_header("Content-Type"));
  5286. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5287. res.set_content("empty-no-content-type", "text/plain");
  5288. })
  5289. .Put("/put",
  5290. [&](const Request &req, Response &res) {
  5291. EXPECT_EQ(req.body, "PUT");
  5292. res.set_content(req.body, "text/plain");
  5293. })
  5294. .Put("/put-large",
  5295. [&](const Request &req, Response &res) {
  5296. EXPECT_EQ(req.body, LARGE_DATA);
  5297. res.set_content(req.body, "text/plain");
  5298. })
  5299. .Patch("/patch",
  5300. [&](const Request &req, Response &res) {
  5301. EXPECT_EQ(req.body, "PATCH");
  5302. res.set_content(req.body, "text/plain");
  5303. })
  5304. .Delete("/delete",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. res.set_content("DELETE", "text/plain");
  5307. })
  5308. .Delete("/delete-body",
  5309. [&](const Request &req, Response &res) {
  5310. EXPECT_EQ(req.body, "content");
  5311. res.set_content(req.body, "text/plain");
  5312. })
  5313. .Options(R"(\*)",
  5314. [&](const Request & /*req*/, Response &res) {
  5315. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5316. })
  5317. .CustomRoute("PROPFIND", "/dav/:id",
  5318. [&](const Request &req, Response &res) {
  5319. res.set_header("x-body-size",
  5320. std::to_string(req.body.size()));
  5321. res.set_header("x-matched-route", req.matched_route);
  5322. res.set_header("x-dav-id", req.path_params.at("id"));
  5323. res.status = StatusCode::MultiStatus_207;
  5324. res.set_content(req.body, "application/xml");
  5325. })
  5326. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5327. [&](const Request &req, Response &res) {
  5328. res.set_header("x-dav-match", req.matches[1]);
  5329. res.status = StatusCode::MultiStatus_207;
  5330. })
  5331. .CustomRoute("MKCOL", "/dav-mkcol",
  5332. [&](const Request &req, Response &res) {
  5333. EXPECT_TRUE(req.body.empty());
  5334. res.status = StatusCode::Created_201;
  5335. })
  5336. .CustomRoute(
  5337. "REPORT", "/dav-report",
  5338. [&](const Request & /*req*/, Response &res,
  5339. const ContentReader &content_reader) {
  5340. std::string body;
  5341. content_reader([&](const char *data, size_t data_length) {
  5342. body.append(data, data_length);
  5343. return true;
  5344. });
  5345. res.set_header("x-body-size", std::to_string(body.size()));
  5346. res.status = StatusCode::MultiStatus_207;
  5347. res.set_content(body, "application/xml");
  5348. })
  5349. .Get("/request-target",
  5350. [&](const Request &req, Response & /*res*/) {
  5351. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5352. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5353. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5354. })
  5355. .Get("/long-query-value",
  5356. [&](const Request &req, Response & /*res*/) {
  5357. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5358. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5359. })
  5360. .Get("/too-long-query-value",
  5361. [&](const Request &req, Response & /*res*/) {
  5362. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5363. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5364. })
  5365. .Get("/array-param",
  5366. [&](const Request &req, Response & /*res*/) {
  5367. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5368. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5369. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5370. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5371. })
  5372. .Get("/array-param-values",
  5373. [&](const Request &req, Response & /*res*/) {
  5374. auto values = req.get_param_values("array");
  5375. EXPECT_EQ(3u, values.size());
  5376. EXPECT_EQ("value1", values[0]);
  5377. EXPECT_EQ("value2", values[1]);
  5378. EXPECT_EQ("value3", values[2]);
  5379. auto empty = req.get_param_values("nonexistent");
  5380. EXPECT_TRUE(empty.empty());
  5381. })
  5382. .Post("/validate-no-multiple-headers",
  5383. [&](const Request &req, Response & /*res*/) {
  5384. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5385. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5386. })
  5387. .Post("/content_receiver",
  5388. [&](const Request &req, Response &res,
  5389. const ContentReader &content_reader) {
  5390. if (req.is_multipart_form_data()) {
  5391. std::vector<FormData> items;
  5392. content_reader(
  5393. [&](const FormData &file) {
  5394. items.push_back(file);
  5395. return true;
  5396. },
  5397. [&](const char *data, size_t data_length) {
  5398. items.back().content.append(data, data_length);
  5399. return true;
  5400. });
  5401. EXPECT_EQ(5u, items.size());
  5402. {
  5403. const auto &file = get_file_value(items, "text1");
  5404. EXPECT_TRUE(file.filename.empty());
  5405. EXPECT_EQ("text default", file.content);
  5406. }
  5407. {
  5408. const auto &file = get_file_value(items, "text2");
  5409. EXPECT_TRUE(file.filename.empty());
  5410. EXPECT_EQ("aωb", file.content);
  5411. }
  5412. {
  5413. const auto &file = get_file_value(items, "file1");
  5414. EXPECT_EQ("hello.txt", file.filename);
  5415. EXPECT_EQ("text/plain", file.content_type);
  5416. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5417. }
  5418. {
  5419. const auto &file = get_file_value(items, "file2");
  5420. EXPECT_EQ("world.json", file.filename);
  5421. EXPECT_EQ("application/json", file.content_type);
  5422. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5423. }
  5424. {
  5425. const auto &file = get_file_value(items, "file3");
  5426. EXPECT_TRUE(file.filename.empty());
  5427. EXPECT_EQ("application/octet-stream", file.content_type);
  5428. EXPECT_EQ(0u, file.content.size());
  5429. }
  5430. } else {
  5431. std::string body;
  5432. content_reader([&](const char *data, size_t data_length) {
  5433. EXPECT_EQ(7U, data_length);
  5434. body.append(data, data_length);
  5435. return true;
  5436. });
  5437. EXPECT_EQ(body, "content");
  5438. res.set_content(body, "text/plain");
  5439. }
  5440. })
  5441. .Put("/content_receiver",
  5442. [&](const Request & /*req*/, Response &res,
  5443. const ContentReader &content_reader) {
  5444. std::string body;
  5445. content_reader([&](const char *data, size_t data_length) {
  5446. body.append(data, data_length);
  5447. return true;
  5448. });
  5449. EXPECT_EQ(body, "content");
  5450. res.set_content(body, "text/plain");
  5451. })
  5452. .Patch("/content_receiver",
  5453. [&](const Request & /*req*/, Response &res,
  5454. const ContentReader &content_reader) {
  5455. std::string body;
  5456. content_reader([&](const char *data, size_t data_length) {
  5457. body.append(data, data_length);
  5458. return true;
  5459. });
  5460. EXPECT_EQ(body, "content");
  5461. res.set_content(body, "text/plain");
  5462. })
  5463. .Post("/query-string-and-body",
  5464. [&](const Request &req, Response & /*res*/) {
  5465. ASSERT_TRUE(req.has_param("key"));
  5466. EXPECT_EQ(req.get_param_value("key"), "value");
  5467. EXPECT_EQ(req.body, "content");
  5468. })
  5469. .Get("/last-request",
  5470. [&](const Request &req, Response & /*res*/) {
  5471. EXPECT_EQ("close", req.get_header_value("Connection"));
  5472. })
  5473. .Get(R"(/redirect/(\d+))",
  5474. [&](const Request &req, Response &res) {
  5475. auto num = std::stoi(req.matches[1]) + 1;
  5476. std::string url = "/redirect/" + std::to_string(num);
  5477. res.set_redirect(url);
  5478. })
  5479. .Post("/binary",
  5480. [&](const Request &req, Response &res) {
  5481. EXPECT_EQ(4U, req.body.size());
  5482. EXPECT_EQ("application/octet-stream",
  5483. req.get_header_value("Content-Type"));
  5484. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5485. res.set_content(req.body, "application/octet-stream");
  5486. })
  5487. .Put("/binary",
  5488. [&](const Request &req, Response &res) {
  5489. EXPECT_EQ(4U, req.body.size());
  5490. EXPECT_EQ("application/octet-stream",
  5491. req.get_header_value("Content-Type"));
  5492. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5493. res.set_content(req.body, "application/octet-stream");
  5494. })
  5495. .Patch("/binary",
  5496. [&](const Request &req, Response &res) {
  5497. EXPECT_EQ(4U, req.body.size());
  5498. EXPECT_EQ("application/octet-stream",
  5499. req.get_header_value("Content-Type"));
  5500. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5501. res.set_content(req.body, "application/octet-stream");
  5502. })
  5503. .Delete("/binary",
  5504. [&](const Request &req, Response &res) {
  5505. EXPECT_EQ(4U, req.body.size());
  5506. EXPECT_EQ("application/octet-stream",
  5507. req.get_header_value("Content-Type"));
  5508. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5509. res.set_content(req.body, "application/octet-stream");
  5510. })
  5511. .Get("/issue1772",
  5512. [&](const Request & /*req*/, Response &res) {
  5513. res.status = 401;
  5514. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5515. })
  5516. .Delete("/issue609",
  5517. [](const httplib::Request &, httplib::Response &res,
  5518. const httplib::ContentReader &) {
  5519. res.set_content("ok", "text/plain");
  5520. })
  5521. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5522. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5523. .Get("/compress",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_content(
  5526. "12345678901234567890123456789012345678901234567890123456789"
  5527. "01234567890123456789012345678901234567890",
  5528. "text/plain");
  5529. })
  5530. .Get("/compress-with-charset",
  5531. [&](const Request & /*req*/, Response &res) {
  5532. res.set_content(
  5533. "12345678901234567890123456789012345678901234567890123456789"
  5534. "01234567890123456789012345678901234567890",
  5535. "application/json; charset=utf-8");
  5536. })
  5537. .Get("/nocompress",
  5538. [&](const Request & /*req*/, Response &res) {
  5539. res.set_content(
  5540. "12345678901234567890123456789012345678901234567890123456789"
  5541. "01234567890123456789012345678901234567890",
  5542. "application/octet-stream");
  5543. })
  5544. .Post("/compress-multipart",
  5545. [&](const Request &req, Response & /*res*/) {
  5546. EXPECT_EQ(2u, req.form.fields.size());
  5547. ASSERT_TRUE(!req.form.has_field("???"));
  5548. {
  5549. const auto &text = req.form.get_field("key1");
  5550. EXPECT_EQ("test", text);
  5551. }
  5552. {
  5553. const auto &text = req.form.get_field("key2");
  5554. EXPECT_EQ("--abcdefg123", text);
  5555. }
  5556. })
  5557. #endif
  5558. ;
  5559. persons_["john"] = "programmer";
  5560. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5561. svr_.wait_until_ready();
  5562. }
  5563. virtual void TearDown() {
  5564. svr_.stop();
  5565. if (!request_threads_.empty()) {
  5566. std::this_thread::sleep_for(std::chrono::seconds(1));
  5567. for (auto &t : request_threads_) {
  5568. t.join();
  5569. }
  5570. }
  5571. t_.join();
  5572. }
  5573. map<string, string> persons_;
  5574. #ifdef CPPHTTPLIB_SSL_ENABLED
  5575. SSLClient cli_;
  5576. SSLServer svr_;
  5577. #else
  5578. Client cli_;
  5579. Server svr_;
  5580. #endif
  5581. thread t_;
  5582. std::vector<thread> request_threads_;
  5583. };
  5584. TEST_F(ServerTest, GetMethod200) {
  5585. auto res = cli_.Get("/hi");
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ("HTTP/1.1", res->version);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. EXPECT_EQ("OK", res->reason);
  5590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5592. EXPECT_EQ("Hello World!", res->body);
  5593. }
  5594. TEST_F(ServerTest, GetEmptyFile) {
  5595. auto res = cli_.Get("/empty_file");
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5599. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5600. EXPECT_EQ("", res->body);
  5601. }
  5602. TEST_F(ServerTest, GetFileContent) {
  5603. auto res = cli_.Get("/file_content");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5607. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5608. EXPECT_EQ("test.html", res->body);
  5609. }
  5610. TEST_F(ServerTest, GetFileContentWithRange) {
  5611. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5614. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5615. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5616. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5617. EXPECT_EQ("est", res->body);
  5618. }
  5619. TEST_F(ServerTest, GetFileContentWithContentType) {
  5620. auto res = cli_.Get("/file_content_with_content_type");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5625. EXPECT_EQ("file\n", res->body);
  5626. }
  5627. TEST_F(ServerTest, GetInvalidFileContent) {
  5628. auto res = cli_.Get("/invalid_file_content");
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5631. }
  5632. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5633. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5635. EXPECT_EQ("HTTP/1.1", res->version);
  5636. EXPECT_EQ(StatusCode::OK_200, res->status);
  5637. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5638. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5639. EXPECT_EQ("Hello World!", res->body);
  5640. }
  5641. TEST_F(ServerTest, GetMethod302) {
  5642. auto res = cli_.Get("/");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. EXPECT_EQ(StatusCode::Found_302, res->status);
  5645. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5646. }
  5647. TEST_F(ServerTest, GetMethod302Redirect) {
  5648. cli_.set_follow_location(true);
  5649. auto res = cli_.Get("/");
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. EXPECT_EQ(StatusCode::OK_200, res->status);
  5652. EXPECT_EQ("Hello World!", res->body);
  5653. EXPECT_EQ("/hi", res->location);
  5654. }
  5655. TEST_F(ServerTest, GetMethod404) {
  5656. auto res = cli_.Get("/invalid");
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5659. }
  5660. TEST_F(ServerTest, HeadMethod200) {
  5661. auto res = cli_.Head("/hi");
  5662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5663. EXPECT_EQ(StatusCode::OK_200, res->status);
  5664. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5665. EXPECT_TRUE(res->body.empty());
  5666. }
  5667. TEST_F(ServerTest, HeadMethod200Static) {
  5668. auto res = cli_.Head("/mount/dir/index.html");
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5672. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5673. EXPECT_TRUE(res->body.empty());
  5674. }
  5675. TEST_F(ServerTest, HeadMethod404) {
  5676. auto res = cli_.Head("/invalid");
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5679. EXPECT_TRUE(res->body.empty());
  5680. }
  5681. TEST_F(ServerTest, GetMethodPersonJohn) {
  5682. auto res = cli_.Get("/person/john");
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. EXPECT_EQ(StatusCode::OK_200, res->status);
  5685. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5686. EXPECT_EQ("programmer", res->body);
  5687. }
  5688. TEST_F(ServerTest, PostMethod1) {
  5689. auto res = cli_.Get("/person/john1");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5692. res = cli_.Post("/person", "name=john1&note=coder",
  5693. "application/x-www-form-urlencoded");
  5694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5695. ASSERT_EQ(StatusCode::OK_200, res->status);
  5696. res = cli_.Get("/person/john1");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5700. ASSERT_EQ("coder", res->body);
  5701. }
  5702. TEST_F(ServerTest, PostMethod2) {
  5703. auto res = cli_.Get("/person/john2");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5706. Params params;
  5707. params.emplace("name", "john2");
  5708. params.emplace("note", "coder");
  5709. res = cli_.Post("/person", params);
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. ASSERT_EQ(StatusCode::OK_200, res->status);
  5712. res = cli_.Get("/person/john2");
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. ASSERT_EQ(StatusCode::OK_200, res->status);
  5715. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5716. ASSERT_EQ("coder", res->body);
  5717. }
  5718. TEST_F(ServerTest, PutMethod3) {
  5719. auto res = cli_.Get("/person/john3");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5722. Params params;
  5723. params.emplace("name", "john3");
  5724. params.emplace("note", "coder");
  5725. res = cli_.Put("/person", params);
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. ASSERT_EQ(StatusCode::OK_200, res->status);
  5728. res = cli_.Get("/person/john3");
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. ASSERT_EQ(StatusCode::OK_200, res->status);
  5731. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5732. ASSERT_EQ("coder", res->body);
  5733. }
  5734. TEST_F(ServerTest, DeleteMethod1) {
  5735. auto res = cli_.Get("/person/john4");
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5738. Params params;
  5739. params.emplace("name", "john4");
  5740. params.emplace("note", "coder");
  5741. res = cli_.Post("/person", params);
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. ASSERT_EQ(StatusCode::OK_200, res->status);
  5744. res = cli_.Get("/person/john4");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5748. ASSERT_EQ("coder", res->body);
  5749. Params delete_params;
  5750. delete_params.emplace("name", "john4");
  5751. res = cli_.Delete("/person", delete_params);
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. ASSERT_EQ(StatusCode::OK_200, res->status);
  5754. ASSERT_EQ("DELETED", res->body);
  5755. res = cli_.Get("/person/john4");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5758. }
  5759. TEST_F(ServerTest, DeleteMethod2) {
  5760. auto res = cli_.Get("/person/john5");
  5761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5762. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5763. Params params;
  5764. params.emplace("name", "john5");
  5765. params.emplace("note", "developer");
  5766. res = cli_.Post("/person", params);
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. ASSERT_EQ(StatusCode::OK_200, res->status);
  5769. res = cli_.Get("/person/john5");
  5770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5771. ASSERT_EQ(StatusCode::OK_200, res->status);
  5772. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5773. ASSERT_EQ("developer", res->body);
  5774. Params delete_params;
  5775. delete_params.emplace("name", "john5");
  5776. Headers headers;
  5777. headers.emplace("Custom-Header", "test-value");
  5778. res = cli_.Delete("/person", headers, delete_params);
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::OK_200, res->status);
  5781. ASSERT_EQ("DELETED", res->body);
  5782. res = cli_.Get("/person/john5");
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5785. }
  5786. TEST_F(ServerTest, DeleteMethod3) {
  5787. auto res = cli_.Get("/person/john6");
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5790. Params params;
  5791. params.emplace("name", "john6");
  5792. params.emplace("note", "tester");
  5793. res = cli_.Post("/person", params);
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. ASSERT_EQ(StatusCode::OK_200, res->status);
  5796. res = cli_.Get("/person/john6");
  5797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5798. ASSERT_EQ(StatusCode::OK_200, res->status);
  5799. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5800. ASSERT_EQ("tester", res->body);
  5801. Params delete_params;
  5802. delete_params.emplace("name", "john6");
  5803. Headers headers;
  5804. headers.emplace("Custom-Header", "test-value");
  5805. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. ASSERT_EQ(StatusCode::OK_200, res->status);
  5808. ASSERT_EQ("DELETED", res->body);
  5809. res = cli_.Get("/person/john6");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5814. Params params;
  5815. params.emplace("json", JSON_DATA);
  5816. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5818. ASSERT_EQ(StatusCode::OK_200, res->status);
  5819. ASSERT_EQ(JSON_DATA, res->body);
  5820. }
  5821. TEST_F(ServerTest, PostEmptyContent) {
  5822. auto res = cli_.Post("/empty", "", "text/plain");
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. ASSERT_EQ(StatusCode::OK_200, res->status);
  5825. ASSERT_EQ("empty", res->body);
  5826. }
  5827. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5828. auto res = cli_.Post("/empty-no-content-type");
  5829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5830. ASSERT_EQ(StatusCode::OK_200, res->status);
  5831. ASSERT_EQ("empty-no-content-type", res->body);
  5832. }
  5833. TEST_F(ServerTest, PostPathOnly) {
  5834. auto res = cli_.Post("/path-only");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. ASSERT_EQ(StatusCode::OK_200, res->status);
  5837. ASSERT_EQ("path-only", res->body);
  5838. }
  5839. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5840. auto res = cli_.Post("/path-headers-only",
  5841. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. ASSERT_EQ(StatusCode::OK_200, res->status);
  5844. ASSERT_EQ("path-headers-only", res->body);
  5845. }
  5846. TEST_F(ServerTest, PostLarge) {
  5847. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5849. ASSERT_EQ(StatusCode::OK_200, res->status);
  5850. EXPECT_EQ(LARGE_DATA, res->body);
  5851. }
  5852. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5853. auto res = cli_.Put("/empty-no-content-type");
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. ASSERT_EQ(StatusCode::OK_200, res->status);
  5856. ASSERT_EQ("empty-no-content-type", res->body);
  5857. }
  5858. TEST_F(ServerTest, GetMethodDir) {
  5859. auto res = cli_.Get("/dir/");
  5860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5861. EXPECT_EQ(StatusCode::OK_200, res->status);
  5862. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5863. auto body = R"(<html>
  5864. <head>
  5865. </head>
  5866. <body>
  5867. <a href="/dir/test.html">Test</a>
  5868. <a href="/hi">hi</a>
  5869. </body>
  5870. </html>
  5871. )";
  5872. EXPECT_EQ(body, res->body);
  5873. }
  5874. TEST_F(ServerTest, GetMethodDirTest) {
  5875. auto res = cli_.Get("/dir/test.html");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::OK_200, res->status);
  5878. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5879. EXPECT_EQ("test.html", res->body);
  5880. }
  5881. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5882. auto res = cli_.Get("/dir/../dir/test.html");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::OK_200, res->status);
  5885. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5886. EXPECT_EQ("test.html", res->body);
  5887. }
  5888. TEST_F(ServerTest, GetMethodInvalidPath) {
  5889. auto res = cli_.Get("/dir/../test.html");
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5892. }
  5893. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5894. auto res = cli_.Get("/../www/dir/test.html");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5897. }
  5898. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5899. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5902. }
  5903. TEST_F(ServerTest, GetMethodDirMountTest) {
  5904. auto res = cli_.Get("/mount/dir/test.html");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::OK_200, res->status);
  5907. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5908. EXPECT_EQ("test.html", res->body);
  5909. }
  5910. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5911. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5915. EXPECT_EQ("test.html", res->body);
  5916. }
  5917. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5918. auto res = cli_.Get("/mount/dir/../test.html");
  5919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5921. }
  5922. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5923. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5926. }
  5927. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5928. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5931. }
  5932. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5933. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5936. }
  5937. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5938. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5941. }
  5942. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5943. auto res = cli_.Get("/mount/dir");
  5944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5945. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5946. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5947. }
  5948. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5949. auto res = cli_.Get("//dir");
  5950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5951. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5952. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5953. }
  5954. TEST_F(ServerTest, PostMethod303) {
  5955. auto res = cli_.Post("/1", "body", "text/plain");
  5956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5957. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5958. EXPECT_EQ("/2", res->get_header_value("Location"));
  5959. }
  5960. TEST_F(ServerTest, PostMethod303Redirect) {
  5961. cli_.set_follow_location(true);
  5962. auto res = cli_.Post("/1", "body", "text/plain");
  5963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5964. EXPECT_EQ(StatusCode::OK_200, res->status);
  5965. EXPECT_EQ("redirected.", res->body);
  5966. EXPECT_EQ("/2", res->location);
  5967. }
  5968. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5969. auto res = cli_.Get("/dir/test.abcde");
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. EXPECT_EQ(StatusCode::OK_200, res->status);
  5972. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5973. EXPECT_EQ("abcde", res->body);
  5974. }
  5975. TEST_F(ServerTest, StaticFileRange) {
  5976. auto res =
  5977. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5979. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5980. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5981. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5982. EXPECT_EQ(true, res->has_header("Content-Range"));
  5983. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5984. EXPECT_EQ(std::string("cd"), res->body);
  5985. }
  5986. TEST_F(ServerTest, StaticFileRanges) {
  5987. auto res = cli_.Get("/dir/test.abcde",
  5988. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5991. EXPECT_TRUE(
  5992. res->get_header_value("Content-Type")
  5993. .find(
  5994. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5995. 0);
  5996. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5997. }
  5998. TEST_F(ServerTest, StaticFileRangeHead) {
  5999. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6002. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6003. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(true, res->has_header("Content-Range"));
  6005. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6006. }
  6007. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6008. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6012. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6013. EXPECT_EQ(true, res->has_header("Content-Range"));
  6014. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6015. res->get_header_value("Content-Range"));
  6016. EXPECT_EQ("LAST\n", res->body);
  6017. }
  6018. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6019. auto res =
  6020. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6022. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6024. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6025. EXPECT_EQ(true, res->has_header("Content-Range"));
  6026. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6027. }
  6028. TEST_F(ServerTest, StaticFileBigFile) {
  6029. auto res = cli_.Get("/dir/1MB.txt");
  6030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6031. EXPECT_EQ(StatusCode::OK_200, res->status);
  6032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6033. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6034. }
  6035. TEST_F(ServerTest, InvalidBaseDirMount) {
  6036. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6037. }
  6038. TEST_F(ServerTest, Binary) {
  6039. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6040. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6041. "application/octet-stream");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. ASSERT_EQ(StatusCode::OK_200, res->status);
  6044. ASSERT_EQ(4U, res->body.size());
  6045. res = cli_.Put("/binary", binary.data(), binary.size(),
  6046. "application/octet-stream");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. ASSERT_EQ(StatusCode::OK_200, res->status);
  6049. ASSERT_EQ(4U, res->body.size());
  6050. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6051. "application/octet-stream");
  6052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6053. ASSERT_EQ(StatusCode::OK_200, res->status);
  6054. ASSERT_EQ(4U, res->body.size());
  6055. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6056. "application/octet-stream");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. ASSERT_EQ(StatusCode::OK_200, res->status);
  6059. ASSERT_EQ(4U, res->body.size());
  6060. }
  6061. TEST_F(ServerTest, BinaryString) {
  6062. auto binary = std::string("\x00\x01\x02\x03", 4);
  6063. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. ASSERT_EQ(StatusCode::OK_200, res->status);
  6066. ASSERT_EQ(4U, res->body.size());
  6067. res = cli_.Put("/binary", binary, "application/octet-stream");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. ASSERT_EQ(StatusCode::OK_200, res->status);
  6070. ASSERT_EQ(4U, res->body.size());
  6071. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. ASSERT_EQ(StatusCode::OK_200, res->status);
  6074. ASSERT_EQ(4U, res->body.size());
  6075. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. ASSERT_EQ(StatusCode::OK_200, res->status);
  6078. ASSERT_EQ(4U, res->body.size());
  6079. }
  6080. TEST_F(ServerTest, EmptyRequest) {
  6081. auto res = cli_.Get("");
  6082. ASSERT_TRUE(!res);
  6083. EXPECT_EQ(Error::Connection, res.error());
  6084. }
  6085. TEST_F(ServerTest, LongRequest) {
  6086. std::string request;
  6087. for (size_t i = 0; i < 545; i++) {
  6088. request += "/TooLongRequest";
  6089. }
  6090. request += "OK";
  6091. auto res = cli_.Get(request.c_str());
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6094. }
  6095. TEST_F(ServerTest, TooLongRequest) {
  6096. std::string request;
  6097. for (size_t i = 0; i < 546; i++) {
  6098. request += "/TooLongRequest";
  6099. }
  6100. request += "_NG";
  6101. auto start = std::chrono::high_resolution_clock::now();
  6102. cli_.set_keep_alive(true);
  6103. auto res = cli_.Get(request.c_str());
  6104. auto end = std::chrono::high_resolution_clock::now();
  6105. auto elapsed =
  6106. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6107. .count();
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6110. EXPECT_LE(elapsed, 1000);
  6111. EXPECT_EQ("close", res->get_header_value("Connection"));
  6112. EXPECT_FALSE(cli_.is_socket_open());
  6113. }
  6114. TEST_F(ServerTest, AlmostTooLongRequest) {
  6115. // test for #2046 - URI length check shouldn't include other content on req
  6116. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6117. // leading /, space, HTTP/1.1)
  6118. std::string request =
  6119. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6120. auto res = cli_.Get(request.c_str());
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6123. }
  6124. TEST_F(ServerTest, LongHeader) {
  6125. Request req;
  6126. req.method = "GET";
  6127. req.path = "/hi";
  6128. std::string host_and_port;
  6129. host_and_port += HOST;
  6130. host_and_port += ":";
  6131. host_and_port += std::to_string(PORT);
  6132. req.headers.emplace("Host", host_and_port.c_str());
  6133. req.headers.emplace("Accept", "*/*");
  6134. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6135. req.headers.emplace(
  6136. "Header-Name",
  6137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@");
  6166. auto res = std::make_shared<Response>();
  6167. auto error = Error::Success;
  6168. auto ret = cli_.send(req, *res, error);
  6169. ASSERT_TRUE(ret);
  6170. EXPECT_EQ(StatusCode::OK_200, res->status);
  6171. }
  6172. TEST_F(ServerTest, LongQueryValue) {
  6173. auto start = std::chrono::high_resolution_clock::now();
  6174. cli_.set_keep_alive(true);
  6175. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6176. auto end = std::chrono::high_resolution_clock::now();
  6177. auto elapsed =
  6178. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6179. .count();
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6182. EXPECT_LE(elapsed, 1000);
  6183. EXPECT_EQ("close", res->get_header_value("Connection"));
  6184. EXPECT_FALSE(cli_.is_socket_open());
  6185. }
  6186. TEST_F(ServerTest, TooLongQueryValue) {
  6187. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6188. ASSERT_FALSE(res);
  6189. EXPECT_EQ(Error::Read, res.error());
  6190. }
  6191. TEST_F(ServerTest, TooLongHeader) {
  6192. Request req;
  6193. req.method = "GET";
  6194. req.path = "/hi";
  6195. std::string host_and_port;
  6196. host_and_port += HOST;
  6197. host_and_port += ":";
  6198. host_and_port += std::to_string(PORT);
  6199. req.headers.emplace("Host", host_and_port.c_str());
  6200. req.headers.emplace("Accept", "*/*");
  6201. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6202. req.headers.emplace(
  6203. "Header-Name",
  6204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6228. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6229. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6230. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6231. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6232. "@@@@@@@@@@@@@@@@@");
  6233. auto res = std::make_shared<Response>();
  6234. auto error = Error::Success;
  6235. auto ret = cli_.send(req, *res, error);
  6236. ASSERT_TRUE(ret);
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. }
  6239. TEST_F(ServerTest, HeaderCountAtLimit) {
  6240. // Test with headers just under the 100 limit
  6241. httplib::Headers headers;
  6242. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6243. // This should keep us just under the 100 header limit
  6244. for (int i = 0; i < 95; i++) {
  6245. std::string name = "X-Test-Header-" + std::to_string(i);
  6246. std::string value = "value" + std::to_string(i);
  6247. headers.emplace(name, value);
  6248. }
  6249. // This should work fine as we're under the limit
  6250. auto res = cli_.Get("/hi", headers);
  6251. EXPECT_TRUE(res);
  6252. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6253. }
  6254. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6255. // Test with many headers to exceed the 100 limit
  6256. httplib::Headers headers;
  6257. // Add 150 headers to definitely exceed the 100 limit
  6258. for (int i = 0; i < 150; i++) {
  6259. std::string name = "X-Test-Header-" + std::to_string(i);
  6260. std::string value = "value" + std::to_string(i);
  6261. headers.emplace(name, value);
  6262. }
  6263. // This should fail due to exceeding header count limit
  6264. cli_.set_keep_alive(true);
  6265. auto res = cli_.Get("/hi", headers);
  6266. // The server should respond with 400 Bad Request
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6269. EXPECT_EQ("close", res->get_header_value("Connection"));
  6270. EXPECT_FALSE(cli_.is_socket_open());
  6271. }
  6272. TEST_F(ServerTest, PercentEncoding) {
  6273. auto res = cli_.Get("/e%6edwith%");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::OK_200, res->status);
  6276. }
  6277. TEST_F(ServerTest, PercentEncodingUnicode) {
  6278. auto res = cli_.Get("/e%u006edwith%");
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. }
  6282. TEST_F(ServerTest, InvalidPercentEncoding) {
  6283. auto res = cli_.Get("/%endwith%");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6286. }
  6287. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6288. auto res = cli_.Get("/%uendwith%");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6291. }
  6292. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6293. auto res = cli_.Get("/hello?aaa=bbb%");
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6296. }
  6297. TEST_F(ServerTest, PlusSignEncoding) {
  6298. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. EXPECT_EQ(StatusCode::OK_200, res->status);
  6301. EXPECT_EQ("a +b", res->body);
  6302. }
  6303. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6304. // This test simulates a potential DoS attack using many headers
  6305. // to verify our security fix prevents memory exhaustion
  6306. httplib::Headers attack_headers;
  6307. // Attempt to add many headers like an attacker would (200 headers to far
  6308. // exceed limit)
  6309. for (int i = 0; i < 200; i++) {
  6310. std::string name = "X-Attack-Header-" + std::to_string(i);
  6311. std::string value = "attack_payload_" + std::to_string(i);
  6312. attack_headers.emplace(name, value);
  6313. }
  6314. // Try to POST with excessive headers
  6315. cli_.set_keep_alive(true);
  6316. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6317. // Should either fail or return 400 Bad Request due to security limit
  6318. if (res) {
  6319. // If we get a response, it should be 400 Bad Request
  6320. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6321. EXPECT_EQ("close", res->get_header_value("Connection"));
  6322. }
  6323. EXPECT_FALSE(cli_.is_socket_open());
  6324. }
  6325. TEST_F(ServerTest, MultipartFormData) {
  6326. UploadFormDataItems items = {
  6327. {"text1", "text default", "", ""},
  6328. {"text2", "aωb", "", ""},
  6329. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6330. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6331. {"file3", "", "", "application/octet-stream"},
  6332. {"file4", "", "", " application/json tmp-string "}};
  6333. auto res = cli_.Post("/multipart", items);
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::OK_200, res->status);
  6336. }
  6337. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6338. UploadFormDataItems items = {
  6339. {"text", "default text", "", ""},
  6340. {"multi_text1", "aaaaa", "", ""},
  6341. {"multi_text1", "bbbbb", "", ""},
  6342. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6343. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6344. "application/json"},
  6345. };
  6346. auto res = cli_.Post("/multipart/multi_file_values", items);
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::OK_200, res->status);
  6349. }
  6350. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6351. auto res = cli_.Get("/hi");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::OK_200, res->status);
  6354. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6355. EXPECT_EQ("Hello World!", res->body);
  6356. }
  6357. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6358. Request req;
  6359. req.method = "POST";
  6360. req.path = "/chunked";
  6361. std::string host_and_port;
  6362. host_and_port += HOST;
  6363. host_and_port += ":";
  6364. host_and_port += std::to_string(PORT);
  6365. req.headers.emplace("Host", host_and_port.c_str());
  6366. req.headers.emplace("Accept", "*/*");
  6367. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6368. req.headers.emplace("Content-Type", "text/plain");
  6369. req.headers.emplace("Content-Length", "0");
  6370. req.headers.emplace(
  6371. "Transfer-Encoding",
  6372. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6373. // Client does not chunk, so make a chunked body manually.
  6374. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6375. auto res = std::make_shared<Response>();
  6376. auto error = Error::Success;
  6377. auto ret = cli_.send(req, *res, error);
  6378. ASSERT_TRUE(ret);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. }
  6381. template <typename ClientT>
  6382. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6383. int expected_status) {
  6384. Request req;
  6385. req.method = "POST";
  6386. req.path = "/chunked";
  6387. std::string host_and_port;
  6388. host_and_port += HOST;
  6389. host_and_port += ":";
  6390. host_and_port += std::to_string(PORT);
  6391. req.headers.emplace("Host", host_and_port.c_str());
  6392. req.headers.emplace("Content-Length", "0");
  6393. req.headers.emplace("Transfer-Encoding", "chunked");
  6394. req.body = body;
  6395. auto res = std::make_shared<Response>();
  6396. auto error = Error::Success;
  6397. ASSERT_TRUE(cli.send(req, *res, error));
  6398. EXPECT_EQ(expected_status, res->status);
  6399. }
  6400. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6401. // rather than treat them as valid lengths.
  6402. template <typename ClientT>
  6403. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6404. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6405. }
  6406. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6407. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6408. }
  6409. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6410. expect_chunked_body_rejected(
  6411. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6412. }
  6413. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6414. // chunk-size line carries no CR, LF or other control character ahead of its
  6415. // terminator. Such a line must be refused rather than read as extension text.
  6416. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6417. expect_chunked_body_rejected(
  6418. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6419. }
  6420. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6421. expect_chunked_body_rejected(
  6422. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6423. }
  6424. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6425. expect_chunked_body_rejected(
  6426. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6427. }
  6428. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6429. // The literal stays split: a hex escape consumes every hex digit that
  6430. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6431. expect_chunked_body_rejected(
  6432. cli_, "4;a\x01"
  6433. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6434. }
  6435. TEST_F(ServerTest, AcceptsChunkExtension) {
  6436. expect_chunked_body_status(cli_,
  6437. "4;name=value\r\ndech\r\n"
  6438. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6439. "0;last\r\n\r\n",
  6440. StatusCode::OK_200);
  6441. }
  6442. TEST_F(ServerTest, GetStreamed2) {
  6443. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6445. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6446. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6447. EXPECT_EQ(true, res->has_header("Content-Range"));
  6448. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6449. EXPECT_EQ(std::string("ab"), res->body);
  6450. }
  6451. TEST_F(ServerTest, GetStreamed) {
  6452. auto res = cli_.Get("/streamed");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6456. EXPECT_EQ(std::string("aaabbb"), res->body);
  6457. }
  6458. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6459. auto res = cli_.Get("/streamed-without-length",
  6460. Headers{make_range_header({{0, -1}})});
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::OK_200, res->status);
  6463. EXPECT_EQ(false, res->has_header("Content-Length"));
  6464. EXPECT_EQ(false, res->has_header("Content-Range"));
  6465. EXPECT_EQ(std::string("abcdefg"), res->body);
  6466. }
  6467. TEST_F(ServerTest, GetStreamedWithRange1) {
  6468. auto res =
  6469. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6472. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6473. EXPECT_EQ(true, res->has_header("Content-Range"));
  6474. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6475. EXPECT_EQ(std::string("def"), res->body);
  6476. }
  6477. TEST_F(ServerTest, GetStreamedWithRange2) {
  6478. auto res =
  6479. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6482. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6483. EXPECT_EQ(true, res->has_header("Content-Range"));
  6484. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6485. EXPECT_EQ(std::string("bcdefg"), res->body);
  6486. }
  6487. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6488. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6491. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6492. EXPECT_EQ(true, res->has_header("Content-Range"));
  6493. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6494. EXPECT_EQ(std::string("efg"), res->body);
  6495. }
  6496. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6497. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6498. // the entire representation.
  6499. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6500. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6503. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6504. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6505. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6506. }
  6507. }
  6508. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6509. auto res =
  6510. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6512. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6513. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6514. EXPECT_EQ(false, res->has_header("Content-Range"));
  6515. EXPECT_EQ(0U, res->body.size());
  6516. }
  6517. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6518. // Only a 206 is served as a partial representation. Under any other status
  6519. // `apply_ranges()` reported the full content length, so the body must match
  6520. // that header, and the content provider must never be asked for an offset
  6521. // outside the representation.
  6522. auto check = [&](int status, const char *range) {
  6523. auto path =
  6524. std::string("/streamed-with-range?status=") + std::to_string(status);
  6525. auto ctx = path + " Range: " + range;
  6526. auto res = cli_.Get(path, Headers{{"Range", range}});
  6527. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6528. EXPECT_EQ(status, res->status) << ctx;
  6529. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6531. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6532. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6533. };
  6534. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6535. check(403, "bytes=3-5");
  6536. // The offset is far past the representation.
  6537. check(403, "bytes=100000-100200");
  6538. // `first_pos` is still -1 here, and the bounds asserts in
  6539. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6540. check(403, "bytes=-3");
  6541. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6542. // multipart branch would have written one that is empty.
  6543. check(403, "bytes=1-2, 4-5");
  6544. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6545. // covers the whole representation.
  6546. check(200, "bytes=3-5");
  6547. check(200, "bytes=1-2, 4-5");
  6548. }
  6549. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6550. auto res =
  6551. cli_.Get("/streamed-with-range",
  6552. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6553. "92233720368547758079223372036854775807"}});
  6554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6555. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6556. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6557. EXPECT_EQ(false, res->has_header("Content-Range"));
  6558. EXPECT_EQ(0U, res->body.size());
  6559. }
  6560. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6561. auto res = cli_.Get(
  6562. "/with-range",
  6563. Headers{{"Range",
  6564. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6565. {"Accept-Encoding", ""}});
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6568. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6569. EXPECT_EQ(true, res->has_header("Content-Range"));
  6570. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6571. EXPECT_EQ(std::string("abcdefg"), res->body);
  6572. }
  6573. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6574. auto res = cli_.Get("/with-range", Headers{
  6575. {"Range", "bytes=0-"},
  6576. {"Accept-Encoding", ""},
  6577. });
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6580. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6581. EXPECT_EQ(true, res->has_header("Content-Range"));
  6582. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6583. EXPECT_EQ(std::string("abcdefg"), res->body);
  6584. }
  6585. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6586. auto res = cli_.Get("/streamed-with-range",
  6587. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6590. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6591. EXPECT_EQ(false, res->has_header("Content-Range"));
  6592. EXPECT_EQ(267U, res->body.size());
  6593. // Check that both range contents are present
  6594. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6595. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6596. // Check that Content-Range headers are present for both ranges
  6597. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6598. std::string::npos);
  6599. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6600. std::string::npos);
  6601. }
  6602. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6603. Ranges ranges;
  6604. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6605. ranges.emplace_back(0, -1);
  6606. }
  6607. auto res = cli_.Get("/streamed-with-range?error",
  6608. Headers{{make_range_header(ranges)}});
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6611. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6612. EXPECT_EQ(false, res->has_header("Content-Range"));
  6613. EXPECT_EQ(0U, res->body.size());
  6614. }
  6615. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6616. auto res = cli_.Get("/streamed-with-range",
  6617. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6620. EXPECT_EQ(5U, res->body.size());
  6621. // Check that overlapping ranges are coalesced into a single range
  6622. EXPECT_EQ("bcdef", res->body);
  6623. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6624. // Should be single range, not multipart
  6625. EXPECT_TRUE(res->has_header("Content-Range"));
  6626. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6627. }
  6628. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6629. auto res = cli_.Get("/streamed-with-range",
  6630. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. EXPECT_EQ(268U, res->body.size());
  6634. // Check that both range contents are present
  6635. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6636. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6637. // Check that Content-Range headers are present for both ranges
  6638. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6639. std::string::npos);
  6640. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6641. std::string::npos);
  6642. }
  6643. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6644. auto res = cli_.Get("/streamed-with-range",
  6645. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6648. EXPECT_EQ(269U, res->body.size());
  6649. // Check that both duplicate range contents are present
  6650. size_t first_abc = res->body.find("abc\r\n");
  6651. EXPECT_TRUE(first_abc != std::string::npos);
  6652. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6653. EXPECT_TRUE(second_abc != std::string::npos);
  6654. // Check that Content-Range headers are present for both ranges
  6655. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6656. EXPECT_TRUE(first_range != std::string::npos);
  6657. size_t second_range =
  6658. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6659. EXPECT_TRUE(second_range != std::string::npos);
  6660. }
  6661. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6662. auto res =
  6663. cli_.Get("/streamed-with-range?error",
  6664. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6667. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6668. EXPECT_EQ(false, res->has_header("Content-Range"));
  6669. EXPECT_EQ(0U, res->body.size());
  6670. }
  6671. TEST_F(ServerTest, GetStreamedEndless) {
  6672. uint64_t offset = 0;
  6673. auto res = cli_.Get("/streamed-cancel",
  6674. [&](const char * /*data*/, uint64_t data_length) {
  6675. if (offset < 100) {
  6676. offset += data_length;
  6677. return true;
  6678. }
  6679. return false;
  6680. });
  6681. ASSERT_TRUE(!res);
  6682. EXPECT_EQ(Error::Canceled, res.error());
  6683. }
  6684. TEST_F(ServerTest, ClientStop) {
  6685. std::atomic_size_t count{4};
  6686. std::vector<std::thread> threads;
  6687. for (auto i = count.load(); i != 0; --i) {
  6688. threads.emplace_back([&]() {
  6689. auto res = cli_.Get("/streamed-cancel",
  6690. [&](const char *, uint64_t) { return true; });
  6691. --count;
  6692. ASSERT_TRUE(!res);
  6693. EXPECT_TRUE(res.error() == Error::Canceled ||
  6694. res.error() == Error::Read || res.error() == Error::Write);
  6695. });
  6696. }
  6697. std::this_thread::sleep_for(std::chrono::seconds(2));
  6698. while (count != 0) {
  6699. cli_.stop();
  6700. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6701. }
  6702. for (auto &t : threads) {
  6703. t.join();
  6704. }
  6705. }
  6706. TEST_F(ServerTest, GetWithRange1) {
  6707. auto res = cli_.Get("/with-range", Headers{
  6708. make_range_header({{3, 5}}),
  6709. {"Accept-Encoding", ""},
  6710. });
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6713. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6714. EXPECT_EQ(true, res->has_header("Content-Range"));
  6715. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6716. EXPECT_EQ(std::string("def"), res->body);
  6717. }
  6718. TEST_F(ServerTest, GetWithRange2) {
  6719. auto res = cli_.Get("/with-range", Headers{
  6720. make_range_header({{1, -1}}),
  6721. {"Accept-Encoding", ""},
  6722. });
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6725. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6726. EXPECT_EQ(true, res->has_header("Content-Range"));
  6727. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6728. EXPECT_EQ(std::string("bcdefg"), res->body);
  6729. }
  6730. TEST_F(ServerTest, GetWithRange3) {
  6731. auto res = cli_.Get("/with-range", Headers{
  6732. make_range_header({{0, 0}}),
  6733. {"Accept-Encoding", ""},
  6734. });
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6737. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6738. EXPECT_EQ(true, res->has_header("Content-Range"));
  6739. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6740. EXPECT_EQ(std::string("a"), res->body);
  6741. }
  6742. TEST_F(ServerTest, GetWithRange4) {
  6743. auto res = cli_.Get("/with-range", Headers{
  6744. make_range_header({{-1, 2}}),
  6745. {"Accept-Encoding", ""},
  6746. });
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6749. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6750. EXPECT_EQ(true, res->has_header("Content-Range"));
  6751. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6752. EXPECT_EQ(std::string("fg"), res->body);
  6753. }
  6754. TEST_F(ServerTest, GetWithRange5) {
  6755. auto res = cli_.Get("/with-range", Headers{
  6756. make_range_header({{0, 5}}),
  6757. {"Accept-Encoding", ""},
  6758. });
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6761. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6762. EXPECT_EQ(true, res->has_header("Content-Range"));
  6763. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6764. EXPECT_EQ(std::string("abcdef"), res->body);
  6765. }
  6766. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6767. auto res =
  6768. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6771. }
  6772. TEST_F(ServerTest, GetWithRangeMultipart) {
  6773. auto res =
  6774. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6777. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6778. EXPECT_EQ(false, res->has_header("Content-Range"));
  6779. EXPECT_EQ(267U, res->body.size());
  6780. }
  6781. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6782. auto res = cli_.Get("/with-range",
  6783. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6786. }
  6787. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6788. auto res = cli_.Get("/with-range-customized-response",
  6789. Headers{{make_range_header({{1, 2}})}});
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6792. EXPECT_EQ(true, res->has_header("Content-Length"));
  6793. EXPECT_EQ(false, res->has_header("Content-Range"));
  6794. EXPECT_EQ(JSON_DATA, res->body);
  6795. }
  6796. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6797. auto res = cli_.Get("/with-range-customized-response",
  6798. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6800. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6801. EXPECT_EQ(true, res->has_header("Content-Length"));
  6802. EXPECT_EQ(false, res->has_header("Content-Range"));
  6803. EXPECT_EQ(JSON_DATA, res->body);
  6804. }
  6805. TEST_F(ServerTest, Issue1772) {
  6806. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6809. }
  6810. TEST_F(ServerTest, Issue609) {
  6811. auto res = cli_.Delete("/issue609");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ(std::string("ok"), res->body);
  6815. }
  6816. TEST_F(ServerTest, GetStreamedChunked) {
  6817. auto res = cli_.Get("/streamed-chunked");
  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, GetStreamedChunked2) {
  6823. auto res = cli_.Get("/streamed-chunked2");
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. EXPECT_EQ(StatusCode::OK_200, res->status);
  6826. EXPECT_EQ(std::string("123456789"), res->body);
  6827. }
  6828. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6829. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6831. EXPECT_EQ(StatusCode::OK_200, res->status);
  6832. EXPECT_EQ(std::string("123456789"), res->body);
  6833. EXPECT_TRUE(res->has_header("Trailer"));
  6834. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6835. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6836. // Trailers are now stored separately from headers (security fix)
  6837. EXPECT_EQ(2U, res->trailers.size());
  6838. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6839. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6840. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6841. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6842. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6843. // Verify trailers are NOT in headers (security verification)
  6844. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6845. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6846. }
  6847. TEST_F(ServerTest, LargeChunkedPost) {
  6848. Request req;
  6849. req.method = "POST";
  6850. req.path = "/large-chunked";
  6851. std::string host_and_port;
  6852. host_and_port += HOST;
  6853. host_and_port += ":";
  6854. host_and_port += std::to_string(PORT);
  6855. req.headers.emplace("Host", host_and_port.c_str());
  6856. req.headers.emplace("Accept", "*/*");
  6857. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6858. req.headers.emplace("Content-Type", "text/plain");
  6859. req.headers.emplace("Content-Length", "0");
  6860. req.headers.emplace("Transfer-Encoding", "chunked");
  6861. std::string long_string(30 * 1024u, 'a');
  6862. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6863. // Attempt to make a large enough post to exceed OS buffers, to test that
  6864. // the server handles short reads if the full chunk data isn't available.
  6865. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6866. auto res = std::make_shared<Response>();
  6867. auto error = Error::Success;
  6868. auto ret = cli_.send(req, *res, error);
  6869. ASSERT_TRUE(ret);
  6870. EXPECT_EQ(StatusCode::OK_200, res->status);
  6871. }
  6872. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6873. auto res = cli_.Get("/remote_addr");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6877. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6878. }
  6879. TEST_F(ServerTest, GetMethodLocalAddr) {
  6880. auto res = cli_.Get("/local_addr");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6884. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6885. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6886. }
  6887. TEST_F(ServerTest, HTTPResponseSplitting) {
  6888. auto res = cli_.Get("/http_response_splitting");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::OK_200, res->status);
  6891. }
  6892. TEST_F(ServerTest, SlowRequest) {
  6893. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6894. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6895. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6896. }
  6897. #if 0
  6898. TEST_F(ServerTest, SlowPost) {
  6899. char buffer[64 * 1024];
  6900. memset(buffer, 0x42, sizeof(buffer));
  6901. auto res = cli_.Post(
  6902. "/slowpost", 64 * 1024 * 1024,
  6903. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6904. auto ret = sink.write(buffer, sizeof(buffer));
  6905. EXPECT_TRUE(ret);
  6906. return true;
  6907. },
  6908. "text/plain");
  6909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. TEST_F(ServerTest, SlowPostFail) {
  6913. char buffer[64 * 1024];
  6914. memset(buffer, 0x42, sizeof(buffer));
  6915. cli_.set_write_timeout(std::chrono::seconds(0));
  6916. auto res = cli_.Post(
  6917. "/slowpost", 64 * 1024 * 1024,
  6918. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6919. sink.write(buffer, sizeof(buffer));
  6920. return true;
  6921. },
  6922. "text/plain");
  6923. ASSERT_TRUE(!res);
  6924. EXPECT_EQ(Error::Write, res.error());
  6925. }
  6926. #endif
  6927. TEST_F(ServerTest, Put) {
  6928. auto res = cli_.Put("/put", "PUT", "text/plain");
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ(StatusCode::OK_200, res->status);
  6931. EXPECT_EQ("PUT", res->body);
  6932. }
  6933. TEST_F(ServerTest, PutWithContentProvider) {
  6934. auto res = cli_.Put(
  6935. "/put", 3,
  6936. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6937. sink.os << "PUT";
  6938. return true;
  6939. },
  6940. "text/plain");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. EXPECT_EQ("PUT", res->body);
  6944. }
  6945. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6946. auto res = cli_.Post(
  6947. "/post", 42,
  6948. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6949. return false;
  6950. },
  6951. "text/plain");
  6952. ASSERT_TRUE(!res);
  6953. EXPECT_EQ(Error::Canceled, res.error());
  6954. }
  6955. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6956. auto res = cli_.Put(
  6957. "/put",
  6958. [](size_t /*offset*/, DataSink &sink) {
  6959. sink.os << "PUT";
  6960. sink.done();
  6961. return true;
  6962. },
  6963. "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. EXPECT_EQ("PUT", res->body);
  6967. }
  6968. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6969. auto res = cli_.Post(
  6970. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6971. "text/plain");
  6972. ASSERT_TRUE(!res);
  6973. EXPECT_EQ(Error::Canceled, res.error());
  6974. }
  6975. TEST_F(ServerTest, PostLoopBack) {
  6976. std::string body;
  6977. auto res = cli_.Post(
  6978. "/post-loopback", 9,
  6979. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6980. EXPECT_EQ(9u, length);
  6981. sink.write("123", 3);
  6982. sink.write("456", 3);
  6983. sink.write("789", 3);
  6984. return true;
  6985. },
  6986. "text/plain",
  6987. [&body](const char *data, size_t data_length) {
  6988. body.append(data, data_length);
  6989. return true;
  6990. });
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. EXPECT_EQ("123456789", body);
  6994. }
  6995. TEST_F(ServerTest, PutLoopBack) {
  6996. std::string body;
  6997. auto res = cli_.Put(
  6998. "/put-loopback", 9,
  6999. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7000. EXPECT_EQ(9u, length);
  7001. sink.write("123", 3);
  7002. sink.write("456", 3);
  7003. sink.write("789", 3);
  7004. return true;
  7005. },
  7006. "text/plain",
  7007. [&body](const char *data, size_t data_length) {
  7008. body.append(data, data_length);
  7009. return true;
  7010. });
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ("123456789", body);
  7014. }
  7015. TEST_F(ServerTest, PatchLoopBack) {
  7016. std::string body;
  7017. auto res = cli_.Patch(
  7018. "/patch-loopback", 9,
  7019. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7020. EXPECT_EQ(9u, length);
  7021. sink.write("123", 3);
  7022. sink.write("456", 3);
  7023. sink.write("789", 3);
  7024. return true;
  7025. },
  7026. "text/plain",
  7027. [&body](const char *data, size_t data_length) {
  7028. body.append(data, data_length);
  7029. return true;
  7030. });
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. EXPECT_EQ("123456789", body);
  7034. }
  7035. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7036. std::string body;
  7037. auto res = cli_.Post(
  7038. "/post-loopback",
  7039. [](size_t /*offset*/, DataSink &sink) {
  7040. sink.write("123", 3);
  7041. sink.write("456", 3);
  7042. sink.write("789", 3);
  7043. sink.done();
  7044. return true;
  7045. },
  7046. "text/plain",
  7047. [&body](const char *data, size_t data_length) {
  7048. body.append(data, data_length);
  7049. return true;
  7050. });
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("123456789", body);
  7054. }
  7055. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7056. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7057. cli_.set_compress(true);
  7058. auto res = cli_.Put(
  7059. "/put", 3,
  7060. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7061. sink.os << "PUT";
  7062. return true;
  7063. },
  7064. "text/plain");
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. EXPECT_EQ(StatusCode::OK_200, res->status);
  7067. EXPECT_EQ("PUT", res->body);
  7068. }
  7069. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7070. cli_.set_compress(true);
  7071. auto res = cli_.Post(
  7072. "/post", 42,
  7073. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7074. return false;
  7075. },
  7076. "text/plain");
  7077. ASSERT_TRUE(!res);
  7078. EXPECT_EQ(Error::Canceled, res.error());
  7079. }
  7080. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7081. cli_.set_compress(true);
  7082. auto res = cli_.Put(
  7083. "/put",
  7084. [](size_t /*offset*/, DataSink &sink) {
  7085. sink.os << "PUT";
  7086. sink.done();
  7087. return true;
  7088. },
  7089. "text/plain");
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::OK_200, res->status);
  7092. EXPECT_EQ("PUT", res->body);
  7093. }
  7094. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7095. cli_.set_compress(true);
  7096. auto res = cli_.Post(
  7097. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7098. "text/plain");
  7099. ASSERT_TRUE(!res);
  7100. EXPECT_EQ(Error::Canceled, res.error());
  7101. }
  7102. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7103. cli_.set_compress(true);
  7104. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7106. EXPECT_EQ(StatusCode::OK_200, res->status);
  7107. EXPECT_EQ(LARGE_DATA, res->body);
  7108. }
  7109. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7110. #ifdef CPPHTTPLIB_SSL_ENABLED
  7111. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7112. Client cli(s.c_str());
  7113. cli.enable_server_certificate_verification(false);
  7114. #else
  7115. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7116. Client cli(s.c_str());
  7117. #endif
  7118. cli.set_compress(true);
  7119. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. EXPECT_EQ(LARGE_DATA, res->body);
  7123. // The compressed size should be less than a 10th of the original. May vary
  7124. // depending on the zlib library.
  7125. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7126. static_cast<uint64_t>(10 * 1024 * 1024));
  7127. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7128. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7129. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7130. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7131. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7132. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7133. #endif
  7134. }
  7135. TEST_F(ServerTest, PutContentWithDeflate) {
  7136. cli_.set_compress(false);
  7137. Headers headers;
  7138. headers.emplace("Content-Encoding", "deflate");
  7139. // PUT in deflate format:
  7140. auto res = cli_.Put("/put", headers,
  7141. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7143. EXPECT_EQ(StatusCode::OK_200, res->status);
  7144. EXPECT_EQ("PUT", res->body);
  7145. }
  7146. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7147. Headers headers;
  7148. headers.emplace("Accept-Encoding", "gzip, deflate");
  7149. auto res = cli_.Get("/streamed-chunked", headers);
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::OK_200, res->status);
  7152. EXPECT_EQ(std::string("123456789"), res->body);
  7153. }
  7154. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7155. Headers headers;
  7156. headers.emplace("Accept-Encoding", "gzip, deflate");
  7157. auto res = cli_.Get("/streamed-chunked2", headers);
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. EXPECT_EQ(StatusCode::OK_200, res->status);
  7160. EXPECT_EQ(std::string("123456789"), res->body);
  7161. }
  7162. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7163. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ(StatusCode::OK_200, res->status);
  7166. }
  7167. TEST(GzipDecompressor, ChunkedDecompression) {
  7168. std::string data;
  7169. for (size_t i = 0; i < 32 * 1024; ++i) {
  7170. data.push_back(static_cast<char>('a' + i % 26));
  7171. }
  7172. std::string compressed_data;
  7173. {
  7174. httplib::detail::gzip_compressor compressor;
  7175. bool result = compressor.compress(
  7176. data.data(), data.size(),
  7177. /*last=*/true,
  7178. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7179. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7180. compressed_data_size);
  7181. return true;
  7182. });
  7183. ASSERT_TRUE(result);
  7184. }
  7185. std::string decompressed_data;
  7186. {
  7187. httplib::detail::gzip_decompressor decompressor;
  7188. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7189. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7190. size_t chunk_size = 130;
  7191. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7192. chunk_begin += chunk_size) {
  7193. size_t current_chunk_size =
  7194. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7195. bool result = decompressor.decompress(
  7196. compressed_data.data() + chunk_begin, current_chunk_size,
  7197. [&](const char *decompressed_data_chunk,
  7198. size_t decompressed_data_chunk_size) {
  7199. decompressed_data.insert(decompressed_data.size(),
  7200. decompressed_data_chunk,
  7201. decompressed_data_chunk_size);
  7202. return true;
  7203. });
  7204. ASSERT_TRUE(result);
  7205. }
  7206. }
  7207. ASSERT_EQ(data, decompressed_data);
  7208. }
  7209. TEST(GzipDecompressor, DeflateDecompression) {
  7210. std::string original_text = "Raw deflate without gzip";
  7211. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7212. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7213. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7214. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7215. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7216. std::string decompressed_data;
  7217. {
  7218. httplib::detail::gzip_decompressor decompressor;
  7219. bool result = decompressor.decompress(
  7220. compressed_data.data(), compressed_data.size(),
  7221. [&](const char *decompressed_data_chunk,
  7222. size_t decompressed_data_chunk_size) {
  7223. decompressed_data.insert(decompressed_data.size(),
  7224. decompressed_data_chunk,
  7225. decompressed_data_chunk_size);
  7226. return true;
  7227. });
  7228. ASSERT_TRUE(result);
  7229. }
  7230. ASSERT_EQ(original_text, decompressed_data);
  7231. }
  7232. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7233. std::string original_text = "Raw deflate without gzip";
  7234. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7235. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7236. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7237. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7238. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7239. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7240. std::string decompressed_data;
  7241. {
  7242. httplib::detail::gzip_decompressor decompressor;
  7243. bool result = decompressor.decompress(
  7244. compressed_data.data(), compressed_data.size(),
  7245. [&](const char *decompressed_data_chunk,
  7246. size_t decompressed_data_chunk_size) {
  7247. decompressed_data.insert(decompressed_data.size(),
  7248. decompressed_data_chunk,
  7249. decompressed_data_chunk_size);
  7250. return true;
  7251. });
  7252. ASSERT_TRUE(result);
  7253. }
  7254. ASSERT_EQ(original_text, decompressed_data);
  7255. }
  7256. #endif
  7257. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7258. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7259. Headers headers;
  7260. headers.emplace("Accept-Encoding", "br");
  7261. auto res = cli_.Get("/streamed-chunked", headers);
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ(std::string("123456789"), res->body);
  7265. }
  7266. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7267. Headers headers;
  7268. headers.emplace("Accept-Encoding", "br");
  7269. auto res = cli_.Get("/streamed-chunked2", headers);
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ(std::string("123456789"), res->body);
  7273. }
  7274. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7275. cli_.set_compress(true);
  7276. auto res = cli_.Put(
  7277. "/put", 3,
  7278. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7279. sink.os << "PUT";
  7280. return true;
  7281. },
  7282. "text/plain");
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::OK_200, res->status);
  7285. EXPECT_EQ("PUT", res->body);
  7286. }
  7287. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7288. cli_.set_compress(true);
  7289. auto res = cli_.Put(
  7290. "/put",
  7291. [](size_t /*offset*/, DataSink &sink) {
  7292. sink.os << "PUT";
  7293. sink.done();
  7294. return true;
  7295. },
  7296. "text/plain");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. EXPECT_EQ("PUT", res->body);
  7300. }
  7301. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7302. cli_.set_compress(true);
  7303. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7305. EXPECT_EQ(StatusCode::OK_200, res->status);
  7306. EXPECT_EQ(LARGE_DATA, res->body);
  7307. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7308. }
  7309. #endif
  7310. TEST_F(ServerTest, Patch) {
  7311. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7313. EXPECT_EQ(StatusCode::OK_200, res->status);
  7314. EXPECT_EQ("PATCH", res->body);
  7315. }
  7316. TEST_F(ServerTest, Delete) {
  7317. auto res = cli_.Delete("/delete");
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. EXPECT_EQ("DELETE", res->body);
  7321. }
  7322. TEST_F(ServerTest, DeleteContentReceiver) {
  7323. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. EXPECT_EQ("content", res->body);
  7327. }
  7328. TEST_F(ServerTest, Options) {
  7329. auto res = cli_.Options("*");
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::OK_200, res->status);
  7332. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7333. EXPECT_TRUE(res->body.empty());
  7334. }
  7335. TEST_F(ServerTest, URL) {
  7336. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. }
  7340. TEST_F(ServerTest, ArrayParam) {
  7341. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. }
  7345. TEST_F(ServerTest, ArrayParamValues) {
  7346. auto res =
  7347. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::OK_200, res->status);
  7350. }
  7351. TEST_F(ServerTest, NoMultipleHeaders) {
  7352. Headers headers = {{"Content-Length", "5"}};
  7353. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7354. "text/plain");
  7355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. }
  7358. TEST_F(ServerTest, PostContentReceiver) {
  7359. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7361. ASSERT_EQ(StatusCode::OK_200, res->status);
  7362. ASSERT_EQ("content", res->body);
  7363. }
  7364. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7365. UploadFormDataItems items = {
  7366. {"text1", "text default", "", ""},
  7367. {"text2", "aωb", "", ""},
  7368. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7369. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7370. {"file3", "", "", "application/octet-stream"},
  7371. };
  7372. auto res = cli_.Post("/content_receiver", items);
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::OK_200, res->status);
  7375. }
  7376. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7377. UploadFormDataItems items = {
  7378. {"text1", "text default", "", ""},
  7379. {"text2", "aωb", "", ""},
  7380. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7381. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7382. {"file3", "", "", "application/octet-stream"},
  7383. };
  7384. auto boundary = std::string("+++++");
  7385. std::string body;
  7386. for (const auto &item : items) {
  7387. body += "--" + boundary + "\r\n";
  7388. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7389. if (!item.filename.empty()) {
  7390. body += "; filename=\"" + item.filename + "\"";
  7391. }
  7392. body += "\r\n";
  7393. if (!item.content_type.empty()) {
  7394. body += "Content-Type: " + item.content_type + "\r\n";
  7395. }
  7396. body += "\r\n";
  7397. body += item.content + "\r\n";
  7398. }
  7399. body += "--" + boundary + "--\r\n";
  7400. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7401. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7403. EXPECT_EQ(StatusCode::OK_200, res->status);
  7404. }
  7405. TEST(MultipartFormDataTest, FieldEscaping) {
  7406. Server svr;
  7407. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7408. const ContentReader &content_reader) {
  7409. ASSERT_TRUE(req.is_multipart_form_data());
  7410. std::vector<FormData> received;
  7411. content_reader(
  7412. [&](const FormData &file) {
  7413. received.push_back(file);
  7414. return true;
  7415. },
  7416. [&](const char *data, size_t data_length) {
  7417. received.back().content.append(data, data_length);
  7418. return true;
  7419. });
  7420. // '"', CR and LF in names and filenames are escaped following the
  7421. // WHATWG HTML standard, so each part still parses as a single part
  7422. // with no injected headers. Content types get CR/LF escaped too,
  7423. // while '"' (legal there, e.g. quoted charset) is preserved.
  7424. ASSERT_EQ(4U, received.size());
  7425. EXPECT_EQ("na%22me", received[0].name);
  7426. EXPECT_EQ("quoted name", received[0].content);
  7427. EXPECT_EQ("file", received[1].name);
  7428. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7429. received[1].filename);
  7430. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7431. EXPECT_EQ("injected", received[1].content);
  7432. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7433. EXPECT_EQ("my%22file.txt", received[2].filename);
  7434. EXPECT_EQ("cr lf name", received[2].content);
  7435. EXPECT_EQ("typed", received[3].name);
  7436. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7437. received[3].content_type);
  7438. EXPECT_EQ("typed content", received[3].content);
  7439. });
  7440. auto port = svr.bind_to_any_port("localhost");
  7441. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7442. auto se = detail::scope_exit([&] {
  7443. svr.stop();
  7444. t.join();
  7445. ASSERT_FALSE(svr.is_running());
  7446. });
  7447. svr.wait_until_ready();
  7448. Client cli("localhost", port);
  7449. UploadFormDataItems items = {
  7450. {"na\"me", "quoted name", "", ""},
  7451. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7452. "application/octet-stream"},
  7453. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7454. {"typed", "typed content", "",
  7455. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7456. };
  7457. auto res = cli.Post("/post", items);
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::OK_200, res->status);
  7460. }
  7461. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7462. const UploadFormDataItems items = {
  7463. {"name1", "Content 1", "", ""},
  7464. {"name2", "Content 2", "file2.txt", "text/plain"},
  7465. };
  7466. Server svr;
  7467. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7468. const ContentReader &content_reader) {
  7469. ASSERT_TRUE(req.is_multipart_form_data());
  7470. std::vector<FormData> received;
  7471. content_reader(
  7472. [&](const FormData &file) {
  7473. received.push_back(file);
  7474. return true;
  7475. },
  7476. [&](const char *data, size_t data_length) {
  7477. received.back().content.append(data, data_length);
  7478. return true;
  7479. });
  7480. ASSERT_EQ(2U, received.size());
  7481. EXPECT_EQ("name1", received[0].name);
  7482. EXPECT_EQ("Content 1", received[0].content);
  7483. EXPECT_EQ("name2", received[1].name);
  7484. EXPECT_EQ("Content 2", received[1].content);
  7485. EXPECT_EQ("file2.txt", received[1].filename);
  7486. EXPECT_EQ("text/plain", received[1].content_type);
  7487. });
  7488. auto port = svr.bind_to_any_port("localhost");
  7489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7490. auto se = detail::scope_exit([&] {
  7491. svr.stop();
  7492. t.join();
  7493. ASSERT_FALSE(svr.is_running());
  7494. });
  7495. svr.wait_until_ready();
  7496. Client cli("localhost", port);
  7497. // Whole-body serialization with a generated boundary
  7498. {
  7499. MultipartFormDataWriter writer;
  7500. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7501. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7502. writer.content_type());
  7503. auto body = writer.serialize(items);
  7504. EXPECT_EQ(body.size(), writer.content_length(items));
  7505. auto res = cli.Post("/post", body, writer.content_type());
  7506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7507. EXPECT_EQ(StatusCode::OK_200, res->status);
  7508. }
  7509. // Per-part framing with a custom boundary via a content provider
  7510. {
  7511. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7512. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7513. MultipartFormDataWriter writer("custom-boundary_123");
  7514. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7515. std::string body;
  7516. for (const auto &item : items) {
  7517. body += writer.item_begin(item);
  7518. body += item.content;
  7519. body += MultipartFormDataWriter::item_end();
  7520. }
  7521. body += writer.finish();
  7522. EXPECT_EQ(body.size(), writer.content_length(items));
  7523. auto res = cli.Post(
  7524. "/post", body.size(),
  7525. [&](size_t offset, size_t length, DataSink &sink) {
  7526. sink.write(body.data() + offset, length);
  7527. return true;
  7528. },
  7529. writer.content_type());
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. }
  7533. }
  7534. TEST_F(ServerTest, PostContentReceiverGzip) {
  7535. cli_.set_compress(true);
  7536. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7538. ASSERT_EQ(StatusCode::OK_200, res->status);
  7539. ASSERT_EQ("content", res->body);
  7540. }
  7541. TEST_F(ServerTest, PutContentReceiver) {
  7542. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. ASSERT_EQ(StatusCode::OK_200, res->status);
  7545. ASSERT_EQ("content", res->body);
  7546. }
  7547. TEST_F(ServerTest, PatchContentReceiver) {
  7548. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7550. ASSERT_EQ(StatusCode::OK_200, res->status);
  7551. ASSERT_EQ("content", res->body);
  7552. }
  7553. template <typename ClientType>
  7554. void TestWithHeadersAndContentReceiver(
  7555. ClientType &cli,
  7556. std::function<Result(ClientType &, const std::string &, const Headers &,
  7557. const std::string &, const std::string &,
  7558. ContentReceiver, DownloadProgress)>
  7559. request_func) {
  7560. Headers headers;
  7561. headers.emplace("X-Custom-Header", "test-value");
  7562. std::string received_body;
  7563. auto res = request_func(
  7564. cli, "/content_receiver", headers, "content", "application/json",
  7565. [&](const char *data, size_t data_length) {
  7566. received_body.append(data, data_length);
  7567. return true;
  7568. },
  7569. nullptr);
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. EXPECT_EQ("content", received_body);
  7573. }
  7574. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7575. #ifdef CPPHTTPLIB_SSL_ENABLED
  7576. using ClientT = SSLClient;
  7577. #else
  7578. using ClientT = Client;
  7579. #endif
  7580. TestWithHeadersAndContentReceiver<ClientT>(
  7581. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7582. const std::string &body, const std::string &content_type,
  7583. ContentReceiver receiver, DownloadProgress progress) {
  7584. return cli.Post(path, headers, body, content_type, receiver, progress);
  7585. });
  7586. }
  7587. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7588. #ifdef CPPHTTPLIB_SSL_ENABLED
  7589. using ClientT = SSLClient;
  7590. #else
  7591. using ClientT = Client;
  7592. #endif
  7593. TestWithHeadersAndContentReceiver<ClientT>(
  7594. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7595. const std::string &body, const std::string &content_type,
  7596. ContentReceiver receiver, DownloadProgress progress) {
  7597. return cli.Put(path, headers, body, content_type, receiver, progress);
  7598. });
  7599. }
  7600. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7601. #ifdef CPPHTTPLIB_SSL_ENABLED
  7602. using ClientT = SSLClient;
  7603. #else
  7604. using ClientT = Client;
  7605. #endif
  7606. TestWithHeadersAndContentReceiver<ClientT>(
  7607. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7608. const std::string &body, const std::string &content_type,
  7609. ContentReceiver receiver, DownloadProgress progress) {
  7610. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7611. });
  7612. }
  7613. template <typename ClientType>
  7614. void TestWithHeadersAndContentReceiverWithProgress(
  7615. ClientType &cli,
  7616. std::function<Result(ClientType &, const std::string &, const Headers &,
  7617. const std::string &, const std::string &,
  7618. ContentReceiver, DownloadProgress)>
  7619. request_func) {
  7620. Headers headers;
  7621. headers.emplace("X-Test-Header", "progress-test");
  7622. std::string received_body;
  7623. auto progress_called = false;
  7624. auto res = request_func(
  7625. cli, "/content_receiver", headers, "content", "text/plain",
  7626. [&](const char *data, size_t data_length) {
  7627. received_body.append(data, data_length);
  7628. return true;
  7629. },
  7630. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7631. progress_called = true;
  7632. return true;
  7633. });
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ("content", received_body);
  7637. EXPECT_TRUE(progress_called);
  7638. }
  7639. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7640. #ifdef CPPHTTPLIB_SSL_ENABLED
  7641. using ClientT = SSLClient;
  7642. #else
  7643. using ClientT = Client;
  7644. #endif
  7645. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7646. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7647. const std::string &body, const std::string &content_type,
  7648. ContentReceiver receiver, DownloadProgress progress) {
  7649. return cli.Post(path, headers, body, content_type, receiver, progress);
  7650. });
  7651. }
  7652. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7653. #ifdef CPPHTTPLIB_SSL_ENABLED
  7654. using ClientT = SSLClient;
  7655. #else
  7656. using ClientT = Client;
  7657. #endif
  7658. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7659. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7660. const std::string &body, const std::string &content_type,
  7661. ContentReceiver receiver, DownloadProgress progress) {
  7662. return cli.Put(path, headers, body, content_type, receiver, progress);
  7663. });
  7664. }
  7665. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7666. #ifdef CPPHTTPLIB_SSL_ENABLED
  7667. using ClientT = SSLClient;
  7668. #else
  7669. using ClientT = Client;
  7670. #endif
  7671. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7672. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7673. const std::string &body, const std::string &content_type,
  7674. ContentReceiver receiver, DownloadProgress progress) {
  7675. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7676. });
  7677. }
  7678. template <typename ClientType>
  7679. void TestWithHeadersAndContentReceiverError(
  7680. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7681. const Headers &, const std::string &,
  7682. const std::string &, ContentReceiver)>
  7683. request_func) {
  7684. Headers headers;
  7685. headers.emplace("X-Error-Test", "true");
  7686. std::string received_body;
  7687. auto receiver_failed = false;
  7688. auto res =
  7689. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7690. [&](const char *data, size_t data_length) {
  7691. received_body.append(data, data_length);
  7692. receiver_failed = true;
  7693. return false;
  7694. });
  7695. ASSERT_FALSE(res);
  7696. EXPECT_TRUE(receiver_failed);
  7697. }
  7698. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7699. #ifdef CPPHTTPLIB_SSL_ENABLED
  7700. using ClientT = SSLClient;
  7701. #else
  7702. using ClientT = Client;
  7703. #endif
  7704. TestWithHeadersAndContentReceiverError<ClientT>(
  7705. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7706. const std::string &body, const std::string &content_type,
  7707. ContentReceiver receiver) {
  7708. return cli.Post(path, headers, body, content_type, receiver);
  7709. });
  7710. }
  7711. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7712. #ifdef CPPHTTPLIB_SSL_ENABLED
  7713. using ClientT = SSLClient;
  7714. #else
  7715. using ClientT = Client;
  7716. #endif
  7717. TestWithHeadersAndContentReceiverError<ClientT>(
  7718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7719. const std::string &body, const std::string &content_type,
  7720. ContentReceiver receiver) {
  7721. return cli.Put(path, headers, body, content_type, receiver);
  7722. });
  7723. }
  7724. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7725. #ifdef CPPHTTPLIB_SSL_ENABLED
  7726. using ClientT = SSLClient;
  7727. #else
  7728. using ClientT = Client;
  7729. #endif
  7730. TestWithHeadersAndContentReceiverError<ClientT>(
  7731. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7732. const std::string &body, const std::string &content_type,
  7733. ContentReceiver receiver) {
  7734. return cli.Patch(path, headers, body, content_type, receiver);
  7735. });
  7736. }
  7737. TEST_F(ServerTest, PostQueryStringAndBody) {
  7738. auto res =
  7739. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. ASSERT_EQ(StatusCode::OK_200, res->status);
  7742. }
  7743. TEST_F(ServerTest, HTTP2Magic) {
  7744. Request req;
  7745. req.method = "PRI";
  7746. req.path = "*";
  7747. req.body = "SM";
  7748. auto res = std::make_shared<Response>();
  7749. auto error = Error::Success;
  7750. auto ret = cli_.send(req, *res, error);
  7751. ASSERT_TRUE(ret);
  7752. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7753. }
  7754. TEST_F(ServerTest, KeepAlive) {
  7755. auto res = cli_.Get("/hi");
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7759. EXPECT_EQ("Hello World!", res->body);
  7760. res = cli_.Get("/hi");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7764. EXPECT_EQ("Hello World!", res->body);
  7765. res = cli_.Get("/hi");
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::OK_200, res->status);
  7768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7769. EXPECT_EQ("Hello World!", res->body);
  7770. res = cli_.Get("/not-exist");
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7773. res = cli_.Post("/empty", "", "text/plain");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7777. EXPECT_EQ("empty", res->body);
  7778. EXPECT_EQ("close", res->get_header_value("Connection"));
  7779. res = cli_.Post(
  7780. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7781. "text/plain");
  7782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7783. EXPECT_EQ(StatusCode::OK_200, res->status);
  7784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7785. EXPECT_EQ("empty", res->body);
  7786. cli_.set_keep_alive(false);
  7787. res = cli_.Get("/last-request");
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ("close", res->get_header_value("Connection"));
  7791. }
  7792. TEST_F(ServerTest, TooManyRedirect) {
  7793. cli_.set_follow_location(true);
  7794. auto res = cli_.Get("/redirect/0");
  7795. ASSERT_TRUE(!res);
  7796. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7797. }
  7798. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7799. Request req;
  7800. req.method = "FOOBAR";
  7801. req.path = "/hi";
  7802. cli_.set_keep_alive(true);
  7803. auto res = cli_.send(req);
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7806. EXPECT_EQ("close", res->get_header_value("Connection"));
  7807. EXPECT_FALSE(cli_.is_socket_open());
  7808. }
  7809. TEST_F(ServerTest, CustomRouteReadsBody) {
  7810. const std::string xml =
  7811. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7812. Request req;
  7813. req.method = "PROPFIND";
  7814. req.path = "/dav/dir";
  7815. req.set_header("Depth", "1");
  7816. req.body = xml;
  7817. auto res = cli_.send(req);
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7820. EXPECT_EQ(xml, res->body);
  7821. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7822. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7823. }
  7824. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7825. Request req;
  7826. req.method = "PROPFIND";
  7827. req.path = "/dav/42";
  7828. auto res = cli_.send(req);
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7831. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7832. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7833. }
  7834. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7835. Request req;
  7836. req.method = "PROPFIND";
  7837. req.path = "/dav-re/123";
  7838. auto res = cli_.send(req);
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7841. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7842. }
  7843. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7844. Request req;
  7845. req.method = "MKCOL";
  7846. req.path = "/dav-mkcol";
  7847. auto res = cli_.send(req);
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ(StatusCode::Created_201, res->status);
  7850. }
  7851. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7852. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7853. Request req;
  7854. req.method = "REPORT";
  7855. req.path = "/dav-report";
  7856. req.body = xml;
  7857. auto res = cli_.send(req);
  7858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7859. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7860. EXPECT_EQ(xml, res->body);
  7861. }
  7862. // A content reader route must fire even when the request carries no body,
  7863. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7864. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7865. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7866. Request req;
  7867. req.method = "REPORT";
  7868. req.path = "/dav-report";
  7869. auto res = cli_.send(req);
  7870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7871. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7872. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7873. }
  7874. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7875. Request req;
  7876. req.method = "PROPFIND";
  7877. req.path = "/not-dav";
  7878. auto res = cli_.send(req);
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7881. }
  7882. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7883. Request req;
  7884. req.method = "UNLOCK";
  7885. req.path = "/dav/dir";
  7886. cli_.set_keep_alive(true);
  7887. auto res = cli_.send(req);
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7890. EXPECT_EQ("close", res->get_header_value("Connection"));
  7891. EXPECT_FALSE(cli_.is_socket_open());
  7892. }
  7893. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7894. // The mount point serves this path, but only for GET and HEAD.
  7895. auto get_res = cli_.Get("/dir/index.html");
  7896. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7897. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7898. Request req;
  7899. req.method = "PROPFIND";
  7900. req.path = "/dir/index.html";
  7901. auto res = cli_.send(req);
  7902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7904. }
  7905. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7906. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7907. cli_.set_keep_alive(true);
  7908. for (auto i = 0; i < 2; i++) {
  7909. Request req;
  7910. req.method = "PROPFIND";
  7911. req.path = "/dav/dir";
  7912. req.body = xml;
  7913. auto res = cli_.send(req);
  7914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7915. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7916. EXPECT_EQ(xml, res->body);
  7917. EXPECT_TRUE(cli_.is_socket_open());
  7918. }
  7919. // A built-in method must still be served on the same connection.
  7920. cli_.set_keep_alive(false);
  7921. auto res = cli_.Get("/hi");
  7922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. EXPECT_EQ("close", res->get_header_value("Connection"));
  7925. }
  7926. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7927. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7928. Request req;
  7929. req.method = "PROPFIND";
  7930. req.path = "/dav/dir";
  7931. req.set_header("Expect", "100-continue");
  7932. req.body = xml;
  7933. auto res = cli_.send(req);
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7936. EXPECT_EQ(xml, res->body);
  7937. }
  7938. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7939. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7940. TEST_F(ServerTest, Gzip) {
  7941. Headers headers;
  7942. headers.emplace("Accept-Encoding", "gzip, deflate");
  7943. auto res = cli_.Get("/compress", headers);
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7947. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7948. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7949. "7890123456789012345678901234567890",
  7950. res->body);
  7951. EXPECT_EQ(StatusCode::OK_200, res->status);
  7952. }
  7953. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7954. Headers headers;
  7955. headers.emplace("Accept-Encoding", "gzip, deflate");
  7956. auto res = cli_.Get("/compress-with-charset", headers);
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7959. EXPECT_EQ("application/json; charset=utf-8",
  7960. res->get_header_value("Content-Type"));
  7961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7962. "7890123456789012345678901234567890",
  7963. res->body);
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. }
  7966. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7967. Headers headers;
  7968. headers.emplace("Accept-Encoding", "");
  7969. auto res = cli_.Get("/compress", headers);
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7973. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7974. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7975. "7890123456789012345678901234567890",
  7976. res->body);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. }
  7979. TEST_F(ServerTest, GzipWithContentReceiver) {
  7980. Headers headers;
  7981. headers.emplace("Accept-Encoding", "gzip, deflate");
  7982. std::string body;
  7983. auto res = cli_.Get("/compress", headers,
  7984. [&](const char *data, uint64_t data_length) {
  7985. EXPECT_EQ(100U, data_length);
  7986. body.append(data, data_length);
  7987. return true;
  7988. });
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7992. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7993. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7994. "7890123456789012345678901234567890",
  7995. body);
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. }
  7998. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7999. Headers headers;
  8000. headers.emplace("Accept-Encoding", "gzip, deflate");
  8001. cli_.set_decompress(false);
  8002. auto res = cli_.Get("/compress", headers);
  8003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8004. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8006. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8007. EXPECT_EQ(33U, res->body.size());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. }
  8010. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8011. Headers headers;
  8012. headers.emplace("Accept-Encoding", "");
  8013. std::string body;
  8014. auto res = cli_.Get("/compress", headers,
  8015. [&](const char *data, uint64_t data_length) {
  8016. EXPECT_EQ(100U, data_length);
  8017. body.append(data, data_length);
  8018. return true;
  8019. });
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8023. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8024. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8025. "7890123456789012345678901234567890",
  8026. body);
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. TEST_F(ServerTest, NoGzip) {
  8030. Headers headers;
  8031. headers.emplace("Accept-Encoding", "gzip, deflate");
  8032. auto res = cli_.Get("/nocompress", headers);
  8033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8034. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8035. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8036. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8037. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8038. "7890123456789012345678901234567890",
  8039. res->body);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. }
  8042. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8043. Headers headers;
  8044. headers.emplace("Accept-Encoding", "gzip, deflate");
  8045. std::string body;
  8046. auto res = cli_.Get("/nocompress", headers,
  8047. [&](const char *data, uint64_t data_length) {
  8048. EXPECT_EQ(100U, data_length);
  8049. body.append(data, data_length);
  8050. return true;
  8051. });
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8054. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8055. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8056. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8057. "7890123456789012345678901234567890",
  8058. body);
  8059. EXPECT_EQ(StatusCode::OK_200, res->status);
  8060. }
  8061. TEST_F(ServerTest, MultipartFormDataGzip) {
  8062. UploadFormDataItems items = {
  8063. {"key1", "test", "", ""},
  8064. {"key2", "--abcdefg123", "", ""},
  8065. };
  8066. cli_.set_compress(true);
  8067. auto res = cli_.Post("/compress-multipart", items);
  8068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8069. EXPECT_EQ(StatusCode::OK_200, res->status);
  8070. }
  8071. #endif
  8072. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8073. // Static file compression is opt-in, so these run their own server rather than
  8074. // flipping it on for the shared ServerTest fixture, which would silently
  8075. // rewrite what every other static file test is asserting.
  8076. class StaticFileCompressionTest : public ::testing::Test {
  8077. protected:
  8078. void TearDown() override {
  8079. if (t_.joinable()) {
  8080. svr_.stop();
  8081. t_.join();
  8082. }
  8083. }
  8084. int start(const std::function<void(Server &)> &configure = nullptr) {
  8085. // Serves the same tree as a directory of build-time compressed assets
  8086. // would be served: the mount point names the coding the files are already
  8087. // stored in. Registered before "/" so it is the one that matches.
  8088. svr_.set_mount_point("/pre-encoded", "./www",
  8089. {{"Content-Encoding", "gzip"}});
  8090. svr_.set_mount_point("/", "./www");
  8091. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8092. res.set_file_content("./www/dir/index.html", "text/html");
  8093. });
  8094. svr_.Get("/pre-encoded-file-content",
  8095. [](const Request & /*req*/, Response &res) {
  8096. res.set_header("Content-Encoding", "gzip");
  8097. res.set_file_content("./www/dir/index.html", "text/html");
  8098. });
  8099. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8100. res.set_content_provider(
  8101. 6, "text/plain",
  8102. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8103. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8104. return true;
  8105. });
  8106. });
  8107. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8108. res.set_content_provider(
  8109. 1000, "text/plain",
  8110. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8111. if (offset < 100) {
  8112. std::string data(100, 'A');
  8113. sink.write(data.data(), data.size());
  8114. return true;
  8115. }
  8116. std::this_thread::sleep_for(std::chrono::seconds(2));
  8117. std::string data(900, 'B');
  8118. sink.write(data.data(), data.size());
  8119. return true;
  8120. });
  8121. });
  8122. if (configure) { configure(svr_); }
  8123. auto port = svr_.bind_to_any_port(HOST);
  8124. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8125. svr_.wait_until_ready();
  8126. return port;
  8127. }
  8128. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8129. // Every file under ./www except 1MB.txt is smaller than the default
  8130. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8131. // it out of the way.
  8132. static void enable_without_floor(Server &svr) {
  8133. svr.set_static_file_compression(true);
  8134. svr.set_static_file_compression_min_length(0);
  8135. }
  8136. Server svr_;
  8137. std::thread t_;
  8138. };
  8139. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8140. auto port = start();
  8141. Client cli(HOST, port);
  8142. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8146. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8147. EXPECT_EQ(1048576U, res->body.size());
  8148. }
  8149. TEST_F(StaticFileCompressionTest, MountPoint) {
  8150. auto port = start(enable);
  8151. Client cli(HOST, port);
  8152. cli.set_decompress(false);
  8153. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8155. EXPECT_EQ(StatusCode::OK_200, res->status);
  8156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8157. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8158. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8159. // The response stays self-delimiting: a length, not a chunked body.
  8160. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8161. EXPECT_EQ(std::to_string(res->body.size()),
  8162. res->get_header_value("Content-Length"));
  8163. EXPECT_LT(res->body.size(), 1048576U);
  8164. EXPECT_FALSE(res->body.empty());
  8165. }
  8166. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8167. auto port = start(enable);
  8168. Client cli(HOST, port);
  8169. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8171. EXPECT_EQ(StatusCode::OK_200, res->status);
  8172. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8173. EXPECT_EQ(1048576U, res->body.size());
  8174. }
  8175. TEST_F(StaticFileCompressionTest, FileContent) {
  8176. auto port = start(enable_without_floor);
  8177. Client cli(HOST, port);
  8178. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8182. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8183. EXPECT_EQ(104U, res->body.size());
  8184. }
  8185. // A handler that serves an already-encoded file names the coding itself. The
  8186. // file-backed path decided its coding from Accept-Encoding and the content
  8187. // type alone, so it compressed the stored bytes a second time and appended a
  8188. // second Content-Encoding field line.
  8189. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8190. auto port = start(enable_without_floor);
  8191. Client cli(HOST, port);
  8192. cli.set_decompress(false);
  8193. auto res = cli.Get("/pre-encoded-file-content",
  8194. Headers{{"Accept-Encoding", "gzip"}});
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8198. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8199. // Vary belongs to a coding the server chose, and it chose none here.
  8200. EXPECT_FALSE(res->has_header("Vary"));
  8201. // The file travels exactly as it is stored on disk.
  8202. EXPECT_EQ(104U, res->body.size());
  8203. }
  8204. // The 1MB file clears the default floor, so this one runs the configuration a
  8205. // deployment would actually have.
  8206. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8207. auto port = start(enable);
  8208. Client cli(HOST, port);
  8209. cli.set_decompress(false);
  8210. auto res =
  8211. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ(StatusCode::OK_200, res->status);
  8214. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8215. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8216. EXPECT_FALSE(res->has_header("Vary"));
  8217. EXPECT_EQ(1048576U, res->body.size());
  8218. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8219. }
  8220. TEST_F(StaticFileCompressionTest, Head) {
  8221. auto port = start(enable);
  8222. Client cli(HOST, port);
  8223. cli.set_decompress(false);
  8224. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8225. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8226. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  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. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8231. // HEAD still reports the size a GET would return.
  8232. EXPECT_EQ(get->get_header_value("Content-Length"),
  8233. res->get_header_value("Content-Length"));
  8234. EXPECT_TRUE(res->body.empty());
  8235. }
  8236. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8237. auto port = start(enable);
  8238. Client cli(HOST, port);
  8239. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8240. {"Accept-Encoding", "gzip"}});
  8241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8243. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8244. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8245. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8246. EXPECT_EQ("cd", res->body);
  8247. }
  8248. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8249. auto port = start(enable);
  8250. Client cli(HOST, port);
  8251. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::OK_200, res->status);
  8254. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8255. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8256. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8257. }
  8258. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8259. auto port = start(enable);
  8260. Client cli(HOST, port);
  8261. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8263. EXPECT_EQ(StatusCode::OK_200, res->status);
  8264. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8265. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8266. EXPECT_TRUE(res->body.empty());
  8267. }
  8268. TEST_F(StaticFileCompressionTest, MinLength) {
  8269. auto port = start(enable);
  8270. Client cli(HOST, port);
  8271. // 104 bytes, well under the default floor. Compressing it would add the
  8272. // gzip header and trailer to a body that already fits in one packet.
  8273. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8275. EXPECT_EQ(StatusCode::OK_200, res->status);
  8276. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8277. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8278. }
  8279. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8280. auto port = start([](Server &svr) {
  8281. svr.set_static_file_compression(true);
  8282. svr.set_static_file_compression_min_length(1);
  8283. });
  8284. Client cli(HOST, port);
  8285. cli.set_decompress(false);
  8286. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8289. // A 9-byte file comes back larger than it went in, because gzip's header and
  8290. // trailer outweigh anything deflate can save. That is the end of the range
  8291. // the floor exists to keep out.
  8292. EXPECT_GT(res->body.size(), 9U);
  8293. }
  8294. TEST_F(StaticFileCompressionTest, MaxLength) {
  8295. auto port = start([](Server &svr) {
  8296. svr.set_static_file_compression(true);
  8297. svr.set_static_file_compression_min_length(0);
  8298. svr.set_static_file_compression_max_length(1024);
  8299. });
  8300. Client cli(HOST, port);
  8301. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8302. // defines `small` as a macro on Windows.
  8303. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8304. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8305. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8306. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8307. // Under it: compressed.
  8308. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8309. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8310. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8311. }
  8312. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8313. auto port = start(enable_without_floor);
  8314. Client cli(HOST, port);
  8315. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8316. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8317. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8318. auto identity_etag = identity->get_header_value("ETag");
  8319. ASSERT_FALSE(identity_etag.empty());
  8320. auto gzipped =
  8321. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8322. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8323. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8324. auto gzip_etag = gzipped->get_header_value("ETag");
  8325. ASSERT_FALSE(gzip_etag.empty());
  8326. // Two representations, two validators.
  8327. EXPECT_NE(identity_etag, gzip_etag);
  8328. // Each one revalidates against the request that would produce it...
  8329. auto fresh =
  8330. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8331. {"If-None-Match", gzip_etag}});
  8332. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8333. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8334. auto fresh_identity =
  8335. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8336. {"If-None-Match", identity_etag}});
  8337. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8338. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8339. // ...and not against the other representation.
  8340. auto crossed =
  8341. cli.Get("/dir/index.html",
  8342. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8343. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8344. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8345. }
  8346. // The opt-in covers responses the server reads off disk itself. A caller's own
  8347. // known-length provider keeps its Content-Length and, more importantly, keeps
  8348. // delivering incrementally: routing it through a compressor would hold every
  8349. // write back until zlib's window filled.
  8350. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8351. auto port = start(enable);
  8352. Client cli(HOST, port);
  8353. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::OK_200, res->status);
  8356. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8357. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8358. EXPECT_EQ("aaabbb", res->body);
  8359. }
  8360. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8361. auto port = start(enable);
  8362. Client cli(HOST, port);
  8363. cli.set_read_timeout(1, 0);
  8364. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8365. Headers{{"Accept-Encoding", "gzip"}});
  8366. ASSERT_TRUE(handle.is_valid());
  8367. // The provider writes 100 bytes and then stalls for longer than the read
  8368. // timeout. Those first bytes have to arrive anyway: run the response through
  8369. // a compressor and zlib holds them until its window fills, so the read would
  8370. // come back empty instead.
  8371. char buf[256];
  8372. auto n = handle.read(buf, sizeof(buf));
  8373. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8374. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8375. }
  8376. #endif
  8377. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8378. TEST_F(ServerTest, Brotli) {
  8379. Headers headers;
  8380. headers.emplace("Accept-Encoding", "br");
  8381. auto res = cli_.Get("/compress", headers);
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8385. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8386. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8387. "7890123456789012345678901234567890",
  8388. res->body);
  8389. EXPECT_EQ(StatusCode::OK_200, res->status);
  8390. }
  8391. #endif
  8392. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8393. TEST_F(ServerTest, Zstd) {
  8394. Headers headers;
  8395. headers.emplace("Accept-Encoding", "zstd");
  8396. auto res = cli_.Get("/compress", headers);
  8397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8398. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8400. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8401. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8402. "7890123456789012345678901234567890",
  8403. res->body);
  8404. EXPECT_EQ(StatusCode::OK_200, res->status);
  8405. }
  8406. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8407. Headers headers;
  8408. headers.emplace("Accept-Encoding", "");
  8409. auto res = cli_.Get("/compress", headers);
  8410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8411. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8413. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8414. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8415. "7890123456789012345678901234567890",
  8416. res->body);
  8417. EXPECT_EQ(StatusCode::OK_200, res->status);
  8418. }
  8419. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8420. Headers headers;
  8421. headers.emplace("Accept-Encoding", "zstd");
  8422. std::string body;
  8423. auto res = cli_.Get("/compress", headers,
  8424. [&](const char *data, uint64_t data_length) {
  8425. EXPECT_EQ(100U, data_length);
  8426. body.append(data, data_length);
  8427. return true;
  8428. });
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8431. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8432. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8433. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8434. "7890123456789012345678901234567890",
  8435. body);
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. }
  8438. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8439. Headers headers;
  8440. headers.emplace("Accept-Encoding", "zstd");
  8441. cli_.set_decompress(false);
  8442. auto res = cli_.Get("/compress", headers);
  8443. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8444. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8445. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8446. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8450. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8451. EXPECT_EQ(StatusCode::OK_200, res->status);
  8452. ASSERT_EQ(26U, res->body.size());
  8453. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8454. 0);
  8455. }
  8456. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8457. Headers headers;
  8458. headers.emplace("Accept-Encoding", "");
  8459. std::string body;
  8460. auto res = cli_.Get("/compress", headers,
  8461. [&](const char *data, uint64_t data_length) {
  8462. EXPECT_EQ(100U, data_length);
  8463. body.append(data, data_length);
  8464. return true;
  8465. });
  8466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8467. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8469. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8471. "7890123456789012345678901234567890",
  8472. body);
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. }
  8475. TEST_F(ServerTest, NoZstd) {
  8476. Headers headers;
  8477. headers.emplace("Accept-Encoding", "zstd");
  8478. auto res = cli_.Get("/nocompress", headers);
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8481. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8482. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8483. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8484. "7890123456789012345678901234567890",
  8485. res->body);
  8486. EXPECT_EQ(StatusCode::OK_200, res->status);
  8487. }
  8488. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8489. Headers headers;
  8490. headers.emplace("Accept-Encoding", "zstd");
  8491. std::string body;
  8492. auto res = cli_.Get("/nocompress", headers,
  8493. [&](const char *data, uint64_t data_length) {
  8494. EXPECT_EQ(100U, data_length);
  8495. body.append(data, data_length);
  8496. return true;
  8497. });
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8500. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8501. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8503. "7890123456789012345678901234567890",
  8504. body);
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. // TODO: How to enable zstd ??
  8508. TEST_F(ServerTest, MultipartFormDataZstd) {
  8509. UploadFormDataItems items = {
  8510. {"key1", "test", "", ""},
  8511. {"key2", "--abcdefg123", "", ""},
  8512. };
  8513. Headers headers;
  8514. headers.emplace("Accept-Encoding", "zstd");
  8515. cli_.set_compress(true);
  8516. auto res = cli_.Post("/compress-multipart", headers, items);
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::OK_200, res->status);
  8519. }
  8520. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8521. Headers headers;
  8522. headers.emplace("Accept-Encoding", "zstd");
  8523. cli_.set_compress(true);
  8524. auto res = cli_.Put(
  8525. "/put", headers, 3,
  8526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8527. sink.os << "PUT";
  8528. return true;
  8529. },
  8530. "text/plain");
  8531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8532. EXPECT_EQ(StatusCode::OK_200, res->status);
  8533. EXPECT_EQ("PUT", res->body);
  8534. }
  8535. // Pre-compression logging tests
  8536. TEST_F(ServerTest, PreCompressionLogging) {
  8537. // Test data for compression (matches the actual /compress endpoint content)
  8538. const std::string test_content =
  8539. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8540. "3456789012345678901234567890";
  8541. // Variables to capture logging data
  8542. std::string pre_compression_body;
  8543. std::string pre_compression_content_type;
  8544. std::string pre_compression_content_encoding;
  8545. std::string post_compression_body;
  8546. std::string post_compression_content_type;
  8547. std::string post_compression_content_encoding;
  8548. // Set up pre-compression logger
  8549. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8550. const Response &res) {
  8551. pre_compression_body = res.body;
  8552. pre_compression_content_type = res.get_header_value("Content-Type");
  8553. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8554. });
  8555. // Set up post-compression logger
  8556. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8557. post_compression_body = res.body;
  8558. post_compression_content_type = res.get_header_value("Content-Type");
  8559. post_compression_content_encoding =
  8560. res.get_header_value("Content-Encoding");
  8561. });
  8562. // Test with gzip compression
  8563. Headers headers;
  8564. headers.emplace("Accept-Encoding", "gzip");
  8565. auto res = cli_.Get("/compress", headers);
  8566. // Verify response was compressed
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8570. // Verify pre-compression logger captured uncompressed content
  8571. EXPECT_EQ(test_content, pre_compression_body);
  8572. EXPECT_EQ("text/plain", pre_compression_content_type);
  8573. EXPECT_TRUE(pre_compression_content_encoding
  8574. .empty()); // No encoding header before compression
  8575. // Verify post-compression logger captured compressed content
  8576. EXPECT_NE(test_content,
  8577. post_compression_body); // Should be different after compression
  8578. EXPECT_EQ("text/plain", post_compression_content_type);
  8579. EXPECT_EQ("gzip", post_compression_content_encoding);
  8580. // Verify compressed content is smaller
  8581. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8582. }
  8583. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8584. const std::string test_content =
  8585. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8586. "3456789012345678901234567890";
  8587. std::string pre_compression_body;
  8588. std::string post_compression_body;
  8589. svr_.set_pre_compression_logger(
  8590. [&](const Request & /*req*/, const Response &res) {
  8591. pre_compression_body = res.body;
  8592. });
  8593. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8594. post_compression_body = res.body;
  8595. });
  8596. Headers headers;
  8597. headers.emplace("Accept-Encoding", "br");
  8598. auto res = cli_.Get("/compress", headers);
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::OK_200, res->status);
  8601. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8602. // Verify pre-compression content is uncompressed
  8603. EXPECT_EQ(test_content, pre_compression_body);
  8604. // Verify post-compression content is compressed
  8605. EXPECT_NE(test_content, post_compression_body);
  8606. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8607. }
  8608. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8609. const std::string test_content =
  8610. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8611. "3456789012345678901234567890";
  8612. std::string pre_compression_body;
  8613. std::string post_compression_body;
  8614. svr_.set_pre_compression_logger(
  8615. [&](const Request & /*req*/, const Response &res) {
  8616. pre_compression_body = res.body;
  8617. });
  8618. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8619. post_compression_body = res.body;
  8620. });
  8621. // Request without compression (use /nocompress endpoint)
  8622. Headers headers;
  8623. auto res = cli_.Get("/nocompress", headers);
  8624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8625. EXPECT_EQ(StatusCode::OK_200, res->status);
  8626. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8627. // Pre-compression logger should not be called when no compression is applied
  8628. EXPECT_TRUE(
  8629. pre_compression_body.empty()); // Pre-compression logger not called
  8630. EXPECT_EQ(
  8631. test_content,
  8632. post_compression_body); // Post-compression logger captures final content
  8633. }
  8634. TEST_F(ServerTest, LoggerSeesContentLength) {
  8635. size_t logged_content_length = 0;
  8636. std::string logged_content_length_header;
  8637. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8638. logged_content_length = res.content_length_;
  8639. logged_content_length_header = res.get_header_value("Content-Length");
  8640. });
  8641. auto res = cli_.Get("/nocompress");
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. EXPECT_EQ(res->body.size(), logged_content_length);
  8645. EXPECT_EQ(std::to_string(logged_content_length),
  8646. logged_content_length_header);
  8647. }
  8648. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8649. const std::string test_content =
  8650. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8651. "3456789012345678901234567890";
  8652. std::string pre_compression_body;
  8653. bool pre_logger_called = false;
  8654. // Set only pre-compression logger
  8655. svr_.set_pre_compression_logger(
  8656. [&](const Request & /*req*/, const Response &res) {
  8657. pre_compression_body = res.body;
  8658. pre_logger_called = true;
  8659. });
  8660. Headers headers;
  8661. headers.emplace("Accept-Encoding", "gzip");
  8662. auto res = cli_.Get("/compress", headers);
  8663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8664. EXPECT_EQ(StatusCode::OK_200, res->status);
  8665. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8666. // Verify pre-compression logger was called
  8667. EXPECT_TRUE(pre_logger_called);
  8668. EXPECT_EQ(test_content, pre_compression_body);
  8669. }
  8670. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8671. {
  8672. // Test with Expect: 100-continue header - success case
  8673. // Server returns 100 Continue, client sends body, server returns 200 OK
  8674. Request req;
  8675. req.method = "POST";
  8676. req.path = "/post-large";
  8677. req.set_header("Expect", "100-continue");
  8678. req.body = LARGE_DATA;
  8679. Response res;
  8680. auto error = Error::Success;
  8681. cli_.set_keep_alive(true);
  8682. auto ret = cli_.send(req, res, error);
  8683. EXPECT_TRUE(ret);
  8684. EXPECT_EQ(StatusCode::OK_200, res.status);
  8685. EXPECT_EQ(LARGE_DATA, res.body);
  8686. }
  8687. {
  8688. // Test with Expect: 100-continue header - error case
  8689. // Client should not send the body when server returns an error
  8690. Request req;
  8691. req.method = "POST";
  8692. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8693. req.set_header("Expect", "100-continue");
  8694. req.body = LARGE_DATA;
  8695. Response res;
  8696. auto error = Error::Success;
  8697. auto start = std::chrono::high_resolution_clock::now();
  8698. cli_.set_keep_alive(true);
  8699. auto ret = cli_.send(req, res, error);
  8700. auto end = std::chrono::high_resolution_clock::now();
  8701. auto elapsed =
  8702. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8703. .count();
  8704. // With Expect: 100-continue, request completes successfully but with error
  8705. EXPECT_TRUE(ret);
  8706. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8707. EXPECT_EQ("close", res.get_header_value("Connection"));
  8708. EXPECT_FALSE(cli_.is_socket_open());
  8709. EXPECT_LE(elapsed, 2000);
  8710. }
  8711. {
  8712. // Send an extra GET request to ensure error recovery without hanging
  8713. Request req;
  8714. req.method = "GET";
  8715. req.path = "/hi";
  8716. auto start = std::chrono::high_resolution_clock::now();
  8717. auto res = cli_.send(req);
  8718. auto end = std::chrono::high_resolution_clock::now();
  8719. auto elapsed =
  8720. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8721. .count();
  8722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8723. EXPECT_EQ(StatusCode::OK_200, res->status);
  8724. EXPECT_EQ("Hello World!", res->body);
  8725. EXPECT_LE(elapsed, 500);
  8726. }
  8727. }
  8728. TEST(ZstdDecompressor, ChunkedDecompression) {
  8729. std::string data;
  8730. for (size_t i = 0; i < 32 * 1024; ++i) {
  8731. data.push_back(static_cast<char>('a' + i % 26));
  8732. }
  8733. std::string compressed_data;
  8734. {
  8735. httplib::detail::zstd_compressor compressor;
  8736. bool result = compressor.compress(
  8737. data.data(), data.size(),
  8738. /*last=*/true,
  8739. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8740. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8741. compressed_data_size);
  8742. return true;
  8743. });
  8744. ASSERT_TRUE(result);
  8745. }
  8746. std::string decompressed_data;
  8747. {
  8748. httplib::detail::zstd_decompressor decompressor;
  8749. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8750. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8751. size_t chunk_size = 130;
  8752. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8753. chunk_begin += chunk_size) {
  8754. size_t current_chunk_size =
  8755. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8756. bool result = decompressor.decompress(
  8757. compressed_data.data() + chunk_begin, current_chunk_size,
  8758. [&](const char *decompressed_data_chunk,
  8759. size_t decompressed_data_chunk_size) {
  8760. decompressed_data.insert(decompressed_data.size(),
  8761. decompressed_data_chunk,
  8762. decompressed_data_chunk_size);
  8763. return true;
  8764. });
  8765. ASSERT_TRUE(result);
  8766. }
  8767. }
  8768. ASSERT_EQ(data, decompressed_data);
  8769. }
  8770. TEST(ZstdDecompressor, Decompress) {
  8771. std::string original_text = "Compressed with ZSTD";
  8772. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8773. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8774. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8775. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8776. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8777. std::string decompressed_data;
  8778. {
  8779. httplib::detail::zstd_decompressor decompressor;
  8780. bool result = decompressor.decompress(
  8781. compressed_data.data(), compressed_data.size(),
  8782. [&](const char *decompressed_data_chunk,
  8783. size_t decompressed_data_chunk_size) {
  8784. decompressed_data.insert(decompressed_data.size(),
  8785. decompressed_data_chunk,
  8786. decompressed_data_chunk_size);
  8787. return true;
  8788. });
  8789. ASSERT_TRUE(result);
  8790. }
  8791. ASSERT_EQ(original_text, decompressed_data);
  8792. }
  8793. #endif
  8794. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8795. // separate chunks so that the server sees each part in its own read(). Used to
  8796. // place a read boundary at a specific offset of a request body.
  8797. static bool send_request_in_parts(time_t read_timeout_sec,
  8798. const std::vector<std::string> &parts,
  8799. std::string *resp = nullptr,
  8800. int port = PORT) {
  8801. auto error = Error::Success;
  8802. auto client_sock = detail::create_client_socket(
  8803. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8804. /*connection_timeout_sec=*/5, 0,
  8805. /*read_timeout_sec=*/5, 0,
  8806. /*write_timeout_sec=*/5, 0, std::string(), error);
  8807. if (client_sock == INVALID_SOCKET) { return false; }
  8808. auto ret = detail::process_client_socket(
  8809. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8810. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8811. for (size_t i = 0; i < parts.size(); i++) {
  8812. const auto &part = parts[i];
  8813. if (part.size() !=
  8814. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8815. return false;
  8816. }
  8817. if (i + 1 < parts.size()) {
  8818. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8819. }
  8820. }
  8821. char buf[512];
  8822. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8823. while (line_reader.getline()) {
  8824. if (resp) { *resp += line_reader.ptr(); }
  8825. }
  8826. return true;
  8827. });
  8828. detail::close_socket(client_sock);
  8829. return ret;
  8830. }
  8831. // Sends a raw request to a server listening at HOST:PORT.
  8832. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8833. std::string *resp = nullptr, int port = PORT) {
  8834. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8835. }
  8836. #ifdef CPPHTTPLIB_SSL_ENABLED
  8837. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8839. ASSERT_TRUE(svr.is_valid());
  8840. svr.set_read_timeout(1, 0);
  8841. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. t.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8849. // keeps each wait well within the read timeout. The server gives up a
  8850. // second in, so the bytes sent after that fail.
  8851. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8852. parts.resize(26, std::string(1, '\0'));
  8853. EXPECT_FALSE(send_request_in_parts(5, parts));
  8854. }
  8855. #endif
  8856. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8857. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  8858. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  8859. const std::vector<std::string> &parts,
  8860. std::string *resp = nullptr,
  8861. int port = PORT) {
  8862. auto error = Error::Success;
  8863. auto sock = detail::create_client_socket(
  8864. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8865. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  8866. /*write_timeout_sec=*/5, 0, std::string(), error);
  8867. if (sock == INVALID_SOCKET) { return false; }
  8868. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  8869. auto ctx = SSL_CTX_new(TLS_client_method());
  8870. auto ssl = SSL_new(ctx);
  8871. auto ssl_se = detail::scope_exit([&] {
  8872. SSL_free(ssl);
  8873. SSL_CTX_free(ctx);
  8874. });
  8875. SSL_set_fd(ssl, static_cast<int>(sock));
  8876. if (SSL_connect(ssl) != 1) { return false; }
  8877. for (size_t i = 0; i < parts.size(); i++) {
  8878. const auto &part = parts[i];
  8879. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  8880. static_cast<int>(part.size())) {
  8881. return false;
  8882. }
  8883. if (i + 1 < parts.size()) {
  8884. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8885. }
  8886. }
  8887. char buf[512];
  8888. int n;
  8889. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  8890. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  8891. }
  8892. return true;
  8893. }
  8894. #endif
  8895. // The request line, then a header value a byte at a time.
  8896. static std::vector<std::string> slow_request_head_parts() {
  8897. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  8898. parts.resize(26, "a");
  8899. parts.emplace_back("\r\n\r\n");
  8900. return parts;
  8901. }
  8902. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  8903. // within the one-second read timeout. The server gives up a second in, before
  8904. // the head is complete.
  8905. static void
  8906. expect_slow_request_head_dropped(Server &svr,
  8907. const std::function<std::string()> &send) {
  8908. std::atomic<bool> handled(false);
  8909. svr.Get("/", [&](const Request &, Response &res) {
  8910. handled = true;
  8911. res.set_content("ok", "text/plain");
  8912. });
  8913. svr.set_read_timeout(1, 0);
  8914. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8915. auto se = detail::scope_exit([&] {
  8916. svr.stop();
  8917. t.join();
  8918. ASSERT_FALSE(svr.is_running());
  8919. });
  8920. svr.wait_until_ready();
  8921. auto resp = send();
  8922. EXPECT_FALSE(handled);
  8923. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  8924. }
  8925. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  8926. Server svr;
  8927. expect_slow_request_head_dropped(svr, [] {
  8928. std::string resp;
  8929. send_request_in_parts(5, slow_request_head_parts(), &resp);
  8930. return resp;
  8931. });
  8932. }
  8933. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8934. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  8935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8936. ASSERT_TRUE(svr.is_valid());
  8937. expect_slow_request_head_dropped(svr, [] {
  8938. std::string resp;
  8939. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  8940. return resp;
  8941. });
  8942. }
  8943. #endif
  8944. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8945. Server svr;
  8946. std::string header_value;
  8947. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8948. header_value = req.get_header_value("foo");
  8949. res.set_content("ok", "text/plain");
  8950. });
  8951. thread t = thread([&] { svr.listen(HOST, PORT); });
  8952. auto se = detail::scope_exit([&] {
  8953. svr.stop();
  8954. t.join();
  8955. ASSERT_FALSE(svr.is_running());
  8956. });
  8957. svr.wait_until_ready();
  8958. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8959. // like characters are not treated the same - use vertical tab and escape.
  8960. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8961. "foo: \t \v bar \x1B\t \r\n"
  8962. "Connection: close\r\n"
  8963. "\r\n";
  8964. std::string res;
  8965. ASSERT_TRUE(send_request(5, req, &res));
  8966. EXPECT_EQ(header_value, "");
  8967. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8968. }
  8969. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8970. Server svr;
  8971. std::string received;
  8972. svr.Get("/order", [&](const Request &req, Response &res) {
  8973. received = entries_to_string(req.headers);
  8974. res.set_content("ok", "text/plain");
  8975. });
  8976. auto port = svr.bind_to_any_port(HOST);
  8977. thread t = thread([&] { svr.listen_after_bind(); });
  8978. auto se = detail::scope_exit([&] {
  8979. svr.stop();
  8980. t.join();
  8981. ASSERT_FALSE(svr.is_running());
  8982. });
  8983. svr.wait_until_ready();
  8984. const std::string req = "GET /order HTTP/1.1\r\n"
  8985. "Host: localhost\r\n"
  8986. "X-First: 1\r\n"
  8987. "X-Dup: a\r\n"
  8988. "X-Second: 2\r\n"
  8989. "X-Dup: b\r\n"
  8990. "Connection: close\r\n"
  8991. "\r\n";
  8992. std::string res;
  8993. ASSERT_TRUE(send_request(5, req, &res, port));
  8994. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8995. EXPECT_EQ(
  8996. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8997. received);
  8998. }
  8999. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9000. Server svr;
  9001. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9002. res.set_header("Set-Cookie", "first=1");
  9003. res.set_header("X-Between", "y");
  9004. res.set_header("Set-Cookie", "second=2");
  9005. res.set_content("ok", "text/plain");
  9006. });
  9007. auto port = svr.bind_to_any_port(HOST);
  9008. thread t = thread([&] { svr.listen_after_bind(); });
  9009. auto se = detail::scope_exit([&] {
  9010. svr.stop();
  9011. t.join();
  9012. ASSERT_FALSE(svr.is_running());
  9013. });
  9014. svr.wait_until_ready();
  9015. Client cli(HOST, port);
  9016. auto res = cli.Get("/cookies");
  9017. ASSERT_TRUE(res);
  9018. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9019. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9020. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9021. }
  9022. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9023. Server svr;
  9024. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9025. auto i = new int(0);
  9026. res.set_header("Trailer", "X-Safe, X-Reflected");
  9027. res.set_chunked_content_provider(
  9028. "text/plain",
  9029. [i](size_t /*offset*/, DataSink &sink) {
  9030. if (*i == 0) {
  9031. sink.os << "body";
  9032. } else {
  9033. Headers trailer;
  9034. // A valid trailer that must survive.
  9035. trailer.emplace("X-Safe", "safe");
  9036. // Attacker-controlled value carrying CR/LF (response splitting).
  9037. trailer.emplace("X-Reflected",
  9038. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9039. // Attacker-controlled name carrying CR/LF.
  9040. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9041. sink.done_with_trailer(trailer);
  9042. }
  9043. (*i)++;
  9044. return true;
  9045. },
  9046. [i](bool /*success*/) { delete i; });
  9047. });
  9048. thread t = thread([&] { svr.listen(HOST, PORT); });
  9049. auto se = detail::scope_exit([&] {
  9050. svr.stop();
  9051. t.join();
  9052. ASSERT_FALSE(svr.is_running());
  9053. });
  9054. svr.wait_until_ready();
  9055. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9056. "Host: " + HOST +
  9057. "\r\n"
  9058. "Connection: close\r\n"
  9059. "\r\n";
  9060. std::string res;
  9061. ASSERT_TRUE(send_request(5, req, &res));
  9062. // The injected fields must not appear anywhere in the raw response.
  9063. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9064. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9065. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9066. // Invalid trailers are dropped entirely, matching set_header().
  9067. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9068. // The valid trailer still passes through.
  9069. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9070. }
  9071. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9072. Server svr;
  9073. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9074. // res.headers is a public field an application can populate directly,
  9075. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9076. // A valid header that must survive.
  9077. res.headers.emplace("X-Safe", "safe");
  9078. // Attacker-controlled value carrying CR/LF (response splitting).
  9079. res.headers.emplace("X-Reflected",
  9080. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9081. // Attacker-controlled name carrying CR/LF.
  9082. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9083. res.set_content("body", "text/plain");
  9084. });
  9085. thread t = thread([&] { svr.listen(HOST, PORT); });
  9086. auto se = detail::scope_exit([&] {
  9087. svr.stop();
  9088. t.join();
  9089. ASSERT_FALSE(svr.is_running());
  9090. });
  9091. svr.wait_until_ready();
  9092. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9093. "Host: " + HOST +
  9094. "\r\n"
  9095. "Connection: close\r\n"
  9096. "\r\n";
  9097. std::string res;
  9098. ASSERT_TRUE(send_request(5, req, &res));
  9099. // The injected fields must not appear anywhere in the raw response.
  9100. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9101. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9102. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9103. // Invalid headers are dropped entirely, matching set_header().
  9104. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9105. // The valid header still passes through.
  9106. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9107. }
  9108. // Forward declaration: in split builds split.py strips `inline` and moves the
  9109. // definition into httplib.cc, so detail::write_request_line is not visible from
  9110. // the public httplib.h. Re-declaring it here lets the tests link against the
  9111. // symbol in both header-only and split builds.
  9112. namespace httplib {
  9113. namespace detail {
  9114. ssize_t write_request_line(Stream &strm, const std::string &method,
  9115. const std::string &path);
  9116. } // namespace detail
  9117. } // namespace httplib
  9118. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9119. // A well-formed target is written verbatim.
  9120. {
  9121. detail::BufferStream strm;
  9122. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9123. EXPECT_GT(n, 0);
  9124. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9125. }
  9126. // A target carrying CR/LF, SP or other control octets must be rejected
  9127. // before anything reaches the wire, otherwise it splits the request line and
  9128. // injects a header or a whole request.
  9129. const std::string evil_targets[] = {
  9130. "/a\r\nInjected: pwned",
  9131. "/a\rInjected",
  9132. "/a\nInjected",
  9133. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9134. "/a b",
  9135. "/a\tb",
  9136. "/a\x7f",
  9137. };
  9138. for (const auto &evil : evil_targets) {
  9139. detail::BufferStream strm;
  9140. auto n = detail::write_request_line(strm, "GET", evil);
  9141. EXPECT_LT(n, 0);
  9142. EXPECT_TRUE(strm.get_buffer().empty());
  9143. }
  9144. }
  9145. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9146. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9147. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9148. // target reaches write_request. The client must fail cleanly with
  9149. // Error::Write instead of putting a request-line-less, header-injecting
  9150. // request on the wire.
  9151. Server svr;
  9152. svr.Get("/a", [](const Request &, Response &res) {
  9153. res.set_content("ok", "text/plain");
  9154. });
  9155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9156. auto se = detail::scope_exit([&] {
  9157. svr.stop();
  9158. thread.join();
  9159. ASSERT_FALSE(svr.is_running());
  9160. });
  9161. svr.wait_until_ready();
  9162. {
  9163. Client cli(HOST, PORT);
  9164. cli.set_path_encode(false);
  9165. // The request is rejected before anything is written, so the connection
  9166. // stays silent and the subsequent response read would otherwise block for
  9167. // the full default read timeout. Shorten it -- the assertion is on the
  9168. // error, not the timeout.
  9169. cli.set_read_timeout(1, 0);
  9170. auto res = cli.Get("/a\r\nInjected: pwned");
  9171. EXPECT_FALSE(res);
  9172. EXPECT_EQ(Error::Write, res.error());
  9173. }
  9174. }
  9175. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9176. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9177. // including extension methods.
  9178. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9179. for (const auto &method : good_methods) {
  9180. detail::BufferStream strm;
  9181. auto n = detail::write_request_line(strm, method, "/");
  9182. EXPECT_GT(n, 0);
  9183. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9184. }
  9185. // A method carrying CR/LF would split the request line and smuggle a whole
  9186. // request ahead of the real one. A space or an empty method corrupts the
  9187. // request line. All must be rejected before anything reaches the wire.
  9188. const std::string evil_methods[] = {
  9189. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9190. "GET\r\nInjected: pwned",
  9191. "GET\r",
  9192. "GET\n",
  9193. "GE T",
  9194. "",
  9195. };
  9196. for (const auto &evil : evil_methods) {
  9197. detail::BufferStream strm;
  9198. auto n = detail::write_request_line(strm, evil, "/");
  9199. EXPECT_LT(n, 0);
  9200. EXPECT_TRUE(strm.get_buffer().empty());
  9201. }
  9202. }
  9203. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9204. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9205. // through Client::send must fail with Error::Write and no request, neither
  9206. // the smuggled one nor the real one, may reach the server.
  9207. Server svr;
  9208. std::atomic<int> request_count(0);
  9209. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9210. request_count++;
  9211. res.status = StatusCode::OK_200;
  9212. return Server::HandlerResponse::Handled;
  9213. });
  9214. auto port = svr.bind_to_any_port(HOST);
  9215. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9216. auto se = detail::scope_exit([&] {
  9217. svr.stop();
  9218. thread.join();
  9219. ASSERT_FALSE(svr.is_running());
  9220. });
  9221. svr.wait_until_ready();
  9222. {
  9223. Client cli(HOST, port);
  9224. const std::string evil_methods[] = {
  9225. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9226. "GE T",
  9227. "",
  9228. };
  9229. for (const auto &evil : evil_methods) {
  9230. Request req;
  9231. req.method = evil;
  9232. req.path = "/";
  9233. auto res = cli.send(req);
  9234. EXPECT_FALSE(res);
  9235. EXPECT_EQ(Error::Write, res.error());
  9236. }
  9237. auto handle =
  9238. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9239. EXPECT_FALSE(handle.is_valid());
  9240. EXPECT_EQ(Error::Write, handle.error);
  9241. // A valid request on the same client still goes through.
  9242. auto res = cli.Get("/");
  9243. ASSERT_TRUE(res);
  9244. EXPECT_EQ(StatusCode::OK_200, res->status);
  9245. }
  9246. EXPECT_EQ(1, request_count.load());
  9247. }
  9248. // Sends a raw request and verifies that there isn't a crash or exception.
  9249. static void test_raw_request(const std::string &req,
  9250. std::string *out = nullptr) {
  9251. Server svr;
  9252. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9253. res.set_content("ok", "text/plain");
  9254. });
  9255. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9256. res.set_content("ok", "text/plain");
  9257. });
  9258. svr.Get("/header_field_value_check",
  9259. [&](const Request & /*req*/, Response &res) {
  9260. res.set_content("ok", "text/plain");
  9261. });
  9262. svr.CustomRoute("PROPFIND", "/dav",
  9263. [&](const Request & /*req*/, Response &res) {
  9264. res.status = StatusCode::MultiStatus_207;
  9265. });
  9266. // Server read timeout must be longer than the client read timeout for the
  9267. // bug to reproduce, probably to force the server to process a request
  9268. // without a trailing blank line.
  9269. const time_t client_read_timeout_sec = 1;
  9270. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9271. bool listen_thread_ok = false;
  9272. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9273. auto se = detail::scope_exit([&] {
  9274. svr.stop();
  9275. t.join();
  9276. ASSERT_FALSE(svr.is_running());
  9277. EXPECT_TRUE(listen_thread_ok);
  9278. });
  9279. svr.wait_until_ready();
  9280. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9281. }
  9282. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9283. // A certain header line causes an exception if the header property is parsed
  9284. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9285. test_raw_request(
  9286. "GET /hi HTTP/1.1\r\n"
  9287. " : "
  9288. " "
  9289. " ");
  9290. }
  9291. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9292. // A certain header line causes an exception if the header property *name* is
  9293. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9294. // greedy matcher and requires backtracking when there are a lot of ":"
  9295. // characters.
  9296. // This occurs with libc++ but not libstdc++.
  9297. test_raw_request(
  9298. "GET /hi HTTP/1.1\r\n"
  9299. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9300. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9301. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9302. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9303. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9304. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9305. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9306. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9307. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9308. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9309. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9310. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9311. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9312. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9313. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9314. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9315. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9316. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9317. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9318. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9319. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9320. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9321. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9322. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9323. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9324. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9325. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9326. "&&&%%%");
  9327. }
  9328. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9329. // Make sure this doesn't crash the server.
  9330. // In a previous version of the header line regex, the "\r" rendered the line
  9331. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9332. // a new position where the leading white space ended and the field value
  9333. // began.
  9334. // The crash occurs with libc++ but not libstdc++.
  9335. test_raw_request("GET /hi HTTP/1.1\r\n"
  9336. "a:" +
  9337. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9338. "\r\n"
  9339. "\r\n");
  9340. }
  9341. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9342. const char *rejected[] = {
  9343. // RFC 9112 §3: one SP between the parts, and nothing else
  9344. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9345. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9346. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9347. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9348. // A request-target has no fragment
  9349. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9350. // An HTTP/1.1 request needs a Host
  9351. "GET /hi HTTP/1.1\r\n\r\n",
  9352. };
  9353. for (auto request : rejected) {
  9354. std::string out;
  9355. test_raw_request(request, &out);
  9356. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9357. }
  9358. std::string out;
  9359. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9360. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9361. }
  9362. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9363. // RFC 9112 §6.1
  9364. const char *requests[] = {
  9365. "PUT /put_hi HTTP/1.1\r\n"
  9366. "Host: localhost\r\n"
  9367. "Content-Length: 0\r\n"
  9368. "Transfer-Encoding: chunked\r\n"
  9369. "\r\n"
  9370. "0\r\n\r\n",
  9371. "PUT /put_hi HTTP/1.0\r\n"
  9372. "Connection: keep-alive\r\n"
  9373. "Transfer-Encoding: chunked\r\n"
  9374. "\r\n"
  9375. "0\r\n\r\n",
  9376. };
  9377. for (auto request : requests) {
  9378. std::string out;
  9379. test_raw_request(request, &out);
  9380. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9381. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9382. }
  9383. }
  9384. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9385. std::string out;
  9386. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9387. "Content-Type: text/plain\r\n"
  9388. "Transfer-Encoding: chunked\r\n"
  9389. "\r\n"
  9390. "nothex\r\n",
  9391. &out);
  9392. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9393. }
  9394. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9395. std::string out;
  9396. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9397. "Content-Type: text/plain\r\n"
  9398. "Transfer-Encoding: chunked\r\n"
  9399. "\r\n"
  9400. "3\r\n"
  9401. "xyz\r\n"
  9402. "NaN\r\n",
  9403. &out);
  9404. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9405. }
  9406. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9407. std::string out;
  9408. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9409. "Content-Type: text/plain\r\n"
  9410. "Transfer-Encoding: chunked\r\n"
  9411. "\r\n"
  9412. // Length is too large for 64 bits.
  9413. "1ffffffffffffffff\r\n"
  9414. "xyz\r\n",
  9415. &out);
  9416. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9417. }
  9418. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9419. test_raw_request("GET /hi HTTP/1.1\r\n"
  9420. "Content-Type: text/plain\r\n\r");
  9421. }
  9422. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9423. std::string out;
  9424. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9425. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9426. }
  9427. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9428. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9429. std::string out;
  9430. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9431. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9432. }
  9433. }
  9434. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9435. std::string out;
  9436. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9437. "Host: localhost\r\n"
  9438. "Connection: close\r\n\r\n",
  9439. &out);
  9440. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9441. }
  9442. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9443. Server svr;
  9444. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9445. EXPECT_TRUE(!req.remote_addr.empty());
  9446. });
  9447. thread t = thread([&] { svr.listen(HOST, PORT); });
  9448. auto se = detail::scope_exit([&] {
  9449. svr.stop();
  9450. t.join();
  9451. ASSERT_FALSE(svr.is_running());
  9452. });
  9453. svr.wait_until_ready();
  9454. // Send an invalid request line to trigger Bad Request
  9455. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9456. std::string out;
  9457. ASSERT_TRUE(send_request(5, bad_req, &out));
  9458. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9459. }
  9460. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9461. // answered right away rather than blocking on a read that waits for EOF.
  9462. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9463. std::string out;
  9464. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9465. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9466. }
  9467. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9468. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9469. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9470. for (const auto *method : methods) {
  9471. Server svr;
  9472. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9473. EXPECT_FALSE(svr.is_valid()) << method;
  9474. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9475. }
  9476. }
  9477. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9478. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9479. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9480. for (const auto *method : methods) {
  9481. Server svr;
  9482. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9483. EXPECT_FALSE(svr.is_valid()) << method;
  9484. }
  9485. }
  9486. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9487. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9488. "COPY", "MOVE", "LOCK",
  9489. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9490. Server svr;
  9491. for (const auto *method : methods) {
  9492. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9493. }
  9494. EXPECT_TRUE(svr.is_valid());
  9495. }
  9496. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9497. Server svr;
  9498. svr.CustomRoute("POST", "/x",
  9499. [](const Request &, Response &, const ContentReader &) {});
  9500. EXPECT_FALSE(svr.is_valid());
  9501. }
  9502. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9503. Server svr;
  9504. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9505. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9506. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9507. EXPECT_FALSE(svr.is_valid());
  9508. }
  9509. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9510. Server svr;
  9511. auto captured = Error::Success;
  9512. svr.set_error_logger(
  9513. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9514. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9515. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9516. }
  9517. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9518. std::string out;
  9519. std::string request(
  9520. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9521. test_raw_request(request, &out);
  9522. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9523. }
  9524. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9525. std::string out;
  9526. std::string request(
  9527. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9528. test_raw_request(request, &out);
  9529. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9530. }
  9531. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9532. std::string out;
  9533. std::string request(
  9534. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9535. test_raw_request(request, &out);
  9536. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9537. }
  9538. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9539. std::string out;
  9540. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9541. "Host: localhost\r\n"
  9542. "Test: \r\n\r\n",
  9543. &out);
  9544. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9545. }
  9546. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9547. Server svr;
  9548. std::string x_custom;
  9549. std::string cookie;
  9550. std::string xff;
  9551. std::string x_unicode;
  9552. std::string x_iis;
  9553. svr.Get("/check", [&](const Request &req, Response &res) {
  9554. x_custom = req.get_header_value("X-Custom");
  9555. cookie = req.get_header_value("Cookie");
  9556. xff = req.get_header_value("X-Forwarded-For");
  9557. x_unicode = req.get_header_value("X-Unicode");
  9558. x_iis = req.get_header_value("X-IIS");
  9559. res.set_content("ok", "text/plain");
  9560. });
  9561. thread t = thread([&] { svr.listen(HOST, PORT); });
  9562. auto se = detail::scope_exit([&] {
  9563. svr.stop();
  9564. t.join();
  9565. ASSERT_FALSE(svr.is_running());
  9566. });
  9567. svr.wait_until_ready();
  9568. const std::string req = "GET /check HTTP/1.1\r\n"
  9569. "Host: localhost\r\n"
  9570. "X-Custom: a%0D%0AInjected: b\r\n"
  9571. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9572. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9573. "X-Unicode: %E3%81%82\r\n"
  9574. "X-IIS: %u00E9\r\n"
  9575. "Connection: close\r\n"
  9576. "\r\n";
  9577. std::string res;
  9578. ASSERT_TRUE(send_request(5, req, &res));
  9579. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9580. // Every value must be returned verbatim (wire form), with no decoding.
  9581. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9582. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9583. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9584. EXPECT_EQ("%E3%81%82", x_unicode);
  9585. EXPECT_EQ("%u00E9", x_iis);
  9586. }
  9587. // Applications that previously relied on automatic percent-decoding can
  9588. // reproduce the old behavior by explicitly calling decode_path_component()
  9589. // or, for RFC 3986 conformance, decode_uri_component().
  9590. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9591. Server svr;
  9592. std::string decoded;
  9593. svr.Get("/check", [&](const Request &req, Response &res) {
  9594. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9595. res.set_content("ok", "text/plain");
  9596. });
  9597. thread t = thread([&] { svr.listen(HOST, PORT); });
  9598. auto se = detail::scope_exit([&] {
  9599. svr.stop();
  9600. t.join();
  9601. ASSERT_FALSE(svr.is_running());
  9602. });
  9603. svr.wait_until_ready();
  9604. const std::string req = "GET /check HTTP/1.1\r\n"
  9605. "Host: localhost\r\n"
  9606. "X-Custom: hello%20world\r\n"
  9607. "Connection: close\r\n"
  9608. "\r\n";
  9609. std::string res;
  9610. ASSERT_TRUE(send_request(5, req, &res));
  9611. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9612. EXPECT_EQ("hello world", decoded);
  9613. }
  9614. // Regression test for #2033. Browsers send Referer values that include
  9615. // percent-encoded characters such as %0A inside the URL. Decoding the
  9616. // header value would either trip the post-decode CR/LF/NUL guard (the
  9617. // original bug, returning 400) or, after that guard was relaxed, silently
  9618. // store a literal LF — both unacceptable. The wire form must round-trip.
  9619. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9620. Server svr;
  9621. std::string referer;
  9622. svr.Get("/check", [&](const Request &req, Response &res) {
  9623. referer = req.get_header_value("Referer");
  9624. res.set_content("ok", "text/plain");
  9625. });
  9626. thread t = thread([&] { svr.listen(HOST, PORT); });
  9627. auto se = detail::scope_exit([&] {
  9628. svr.stop();
  9629. t.join();
  9630. ASSERT_FALSE(svr.is_running());
  9631. });
  9632. svr.wait_until_ready();
  9633. const std::string req = "GET /check HTTP/1.1\r\n"
  9634. "Host: localhost\r\n"
  9635. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9636. "Connection: close\r\n"
  9637. "\r\n";
  9638. std::string res;
  9639. ASSERT_TRUE(send_request(5, req, &res));
  9640. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9641. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9642. }
  9643. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9644. Server svr;
  9645. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9646. res.set_header("Cache-Control", "no-cache");
  9647. res.set_chunked_content_provider(
  9648. "text/event-stream", [](size_t offset, DataSink &sink) {
  9649. std::string s = "data:";
  9650. s += std::to_string(offset);
  9651. s += "\n\n";
  9652. auto ret = sink.write(s.data(), s.size());
  9653. EXPECT_TRUE(ret);
  9654. std::this_thread::sleep_for(std::chrono::seconds(1));
  9655. return true;
  9656. });
  9657. });
  9658. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9659. svr.wait_until_ready();
  9660. Client client(HOST, PORT);
  9661. const Headers headers = {{"Accept", "text/event-stream"}};
  9662. auto get_thread = std::thread([&client, &headers]() {
  9663. auto res = client.Get(
  9664. "/events", headers,
  9665. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9666. });
  9667. auto se = detail::scope_exit([&] {
  9668. svr.stop();
  9669. get_thread.join();
  9670. listen_thread.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. // Give GET time to get a few messages.
  9674. std::this_thread::sleep_for(std::chrono::seconds(2));
  9675. }
  9676. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9677. httplib::Server svr;
  9678. svr.Post("/hi",
  9679. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9680. res.status = StatusCode::OK_200;
  9681. });
  9682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9683. svr.wait_until_ready();
  9684. Client cli(HOST, PORT);
  9685. auto res = cli.Post("/hi", "data", "text/plain");
  9686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9687. EXPECT_EQ(StatusCode::OK_200, res->status);
  9688. svr.stop();
  9689. thread.join();
  9690. ASSERT_FALSE(svr.is_running());
  9691. res = cli.Post("/hi", "data", "text/plain");
  9692. ASSERT_FALSE(res);
  9693. }
  9694. TEST(ServerStopTest, ListenFailure) {
  9695. Server svr;
  9696. auto t = thread([&]() {
  9697. auto ret = svr.listen("????", PORT);
  9698. EXPECT_FALSE(ret);
  9699. });
  9700. svr.wait_until_ready();
  9701. svr.stop();
  9702. t.join();
  9703. }
  9704. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9705. TEST(ServerStopTest, Decommision) {
  9706. Server svr;
  9707. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9708. for (int i = 0; i < 4; i++) {
  9709. auto is_even = !(i % 2);
  9710. std::thread t{[&] {
  9711. try {
  9712. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9713. if (is_even) {
  9714. throw std::runtime_error("Some thing that happens to go wrong.");
  9715. }
  9716. svr.listen(HOST, PORT);
  9717. } catch (...) { svr.decommission(); }
  9718. }};
  9719. svr.wait_until_ready();
  9720. // Server is up
  9721. {
  9722. Client cli(HOST, PORT);
  9723. auto res = cli.Get("/hi");
  9724. if (is_even) {
  9725. EXPECT_FALSE(res);
  9726. } else {
  9727. EXPECT_TRUE(res);
  9728. EXPECT_EQ("hi...", res->body);
  9729. }
  9730. }
  9731. svr.stop();
  9732. t.join();
  9733. // Server is down...
  9734. {
  9735. Client cli(HOST, PORT);
  9736. auto res = cli.Get("/hi");
  9737. EXPECT_FALSE(res);
  9738. }
  9739. }
  9740. }
  9741. #endif
  9742. // Helper function for string body upload progress tests
  9743. template <typename SetupHandler, typename ClientCall>
  9744. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9745. ClientCall &&client_call,
  9746. const string &body) {
  9747. Server svr;
  9748. setup_handler(svr);
  9749. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9750. auto se = detail::scope_exit([&] {
  9751. svr.stop();
  9752. t.join();
  9753. });
  9754. svr.wait_until_ready();
  9755. Client cli(HOST, PORT);
  9756. vector<uint64_t> progress_values;
  9757. bool progress_called = false;
  9758. auto res =
  9759. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9760. progress_values.push_back(current);
  9761. progress_called = true;
  9762. return true;
  9763. });
  9764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9765. EXPECT_EQ(200, res->status);
  9766. EXPECT_TRUE(progress_called);
  9767. }
  9768. TEST(UploadProgressTest, PostStringBodyBasic) {
  9769. TestStringBodyUploadProgress(
  9770. [](Server &svr) {
  9771. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9772. res.set_content("received", "text/plain");
  9773. });
  9774. },
  9775. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9776. return cli.Post("/test", body, "text/plain", progress_callback);
  9777. },
  9778. "test data for upload progress");
  9779. }
  9780. TEST(UploadProgressTest, PutStringBodyBasic) {
  9781. TestStringBodyUploadProgress(
  9782. [](Server &svr) {
  9783. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9784. res.set_content("put received", "text/plain");
  9785. });
  9786. },
  9787. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9788. return cli.Put("/test", body, "text/plain", progress_callback);
  9789. },
  9790. "put test data for upload progress");
  9791. }
  9792. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9793. TestStringBodyUploadProgress(
  9794. [](Server &svr) {
  9795. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9796. res.set_content("patch received", "text/plain");
  9797. });
  9798. },
  9799. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9800. return cli.Patch("/test", body, "text/plain", progress_callback);
  9801. },
  9802. "patch test data for upload progress");
  9803. }
  9804. // Helper function for content provider upload progress tests
  9805. template <typename SetupHandler, typename ClientCall>
  9806. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9807. ClientCall &&client_call) {
  9808. Server svr;
  9809. setup_handler(svr);
  9810. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9811. auto se = detail::scope_exit([&] {
  9812. svr.stop();
  9813. t.join();
  9814. });
  9815. svr.wait_until_ready();
  9816. Client cli(HOST, PORT);
  9817. vector<uint64_t> progress_values;
  9818. auto res =
  9819. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9820. progress_values.push_back(current);
  9821. return true;
  9822. });
  9823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9824. EXPECT_EQ(200, res->status);
  9825. EXPECT_FALSE(progress_values.empty());
  9826. }
  9827. TEST(UploadProgressTest, PostContentProviderProgress) {
  9828. TestContentProviderUploadProgress(
  9829. [](Server &svr) {
  9830. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9831. res.set_content("provider received", "text/plain");
  9832. });
  9833. },
  9834. [](Client &cli, UploadProgress progress_callback) {
  9835. return cli.Post(
  9836. "/test", 10,
  9837. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9838. sink.os << "test data";
  9839. return true;
  9840. },
  9841. "text/plain", progress_callback);
  9842. });
  9843. }
  9844. // Helper function for multipart upload progress tests
  9845. template <typename SetupHandler, typename ClientCall>
  9846. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9847. ClientCall &&client_call,
  9848. const string &endpoint) {
  9849. Server svr;
  9850. setup_handler(svr);
  9851. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9852. auto se = detail::scope_exit([&] {
  9853. svr.stop();
  9854. t.join();
  9855. });
  9856. svr.wait_until_ready();
  9857. Client cli(HOST, PORT);
  9858. vector<uint64_t> progress_values;
  9859. UploadFormDataItems items = {
  9860. {"field1", "value1", "", ""},
  9861. {"field2", "longer value for progress tracking test", "", ""},
  9862. {"file1", "file content data for upload progress", "test.txt",
  9863. "text/plain"}};
  9864. auto res = client_call(cli, endpoint, items,
  9865. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9866. progress_values.push_back(current);
  9867. return true;
  9868. });
  9869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9870. EXPECT_EQ(200, res->status);
  9871. EXPECT_FALSE(progress_values.empty());
  9872. }
  9873. TEST(UploadProgressTest, PostMultipartProgress) {
  9874. TestMultipartUploadProgress(
  9875. [](Server &svr) {
  9876. svr.Post("/multipart", [](const Request &req, Response &res) {
  9877. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9878. res.set_content("multipart received", "text/plain");
  9879. });
  9880. },
  9881. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9882. UploadProgress progress_callback) {
  9883. return cli.Post(endpoint, items, progress_callback);
  9884. },
  9885. "/multipart");
  9886. }
  9887. // Helper function for basic download progress tests
  9888. template <typename SetupHandler, typename ClientCall>
  9889. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9890. ClientCall &&client_call, const string &endpoint,
  9891. size_t expected_content_size) {
  9892. Server svr;
  9893. setup_handler(svr);
  9894. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9895. auto se = detail::scope_exit([&] {
  9896. svr.stop();
  9897. t.join();
  9898. });
  9899. svr.wait_until_ready();
  9900. Client cli(HOST, PORT);
  9901. vector<uint64_t> progress_values;
  9902. auto res = client_call(cli, endpoint,
  9903. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9904. progress_values.push_back(current);
  9905. return true;
  9906. });
  9907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9908. EXPECT_EQ(200, res->status);
  9909. EXPECT_FALSE(progress_values.empty());
  9910. EXPECT_EQ(expected_content_size, res->body.size());
  9911. }
  9912. TEST(DownloadProgressTest, GetBasic) {
  9913. TestBasicDownloadProgress(
  9914. [](Server &svr) {
  9915. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9916. string content(1000, 'D');
  9917. res.set_content(content, "text/plain");
  9918. });
  9919. },
  9920. [](Client &cli, const string &endpoint,
  9921. DownloadProgress progress_callback) {
  9922. return cli.Get(endpoint, progress_callback);
  9923. },
  9924. "/download", 1000u);
  9925. }
  9926. // Helper function for content receiver download progress tests
  9927. template <typename SetupHandler, typename ClientCall>
  9928. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9929. ClientCall &&client_call,
  9930. const string &endpoint,
  9931. size_t expected_content_size) {
  9932. Server svr;
  9933. setup_handler(svr);
  9934. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9935. auto se = detail::scope_exit([&] {
  9936. svr.stop();
  9937. t.join();
  9938. });
  9939. svr.wait_until_ready();
  9940. Client cli(HOST, PORT);
  9941. vector<uint64_t> progress_values;
  9942. string received_body;
  9943. auto res = client_call(
  9944. cli, endpoint,
  9945. [&](const char *data, size_t data_length) -> bool {
  9946. received_body.append(data, data_length);
  9947. return true;
  9948. },
  9949. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9950. progress_values.push_back(current);
  9951. return true;
  9952. });
  9953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9954. EXPECT_EQ(200, res->status);
  9955. EXPECT_FALSE(progress_values.empty());
  9956. EXPECT_EQ(expected_content_size, received_body.size());
  9957. EXPECT_TRUE(res->body.empty());
  9958. }
  9959. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9960. TestContentReceiverDownloadProgress(
  9961. [](Server &svr) {
  9962. svr.Get("/download-receiver",
  9963. [](const Request & /*req*/, Response &res) {
  9964. string content(2000, 'R');
  9965. res.set_content(content, "text/plain");
  9966. });
  9967. },
  9968. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9969. DownloadProgress progress_callback) {
  9970. return cli.Get(endpoint, content_receiver, progress_callback);
  9971. },
  9972. "/download-receiver", 2000u);
  9973. }
  9974. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9975. // A provider reaching a pass with nothing to hand over - an empty buffer
  9976. // popped off a queue, say - must not be taken to mean the body is finished.
  9977. // It used to end the loop with the terminating chunk unwritten while the
  9978. // server still considered the response complete, so the peer waited for an
  9979. // end that never arrived.
  9980. Server svr;
  9981. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9982. auto step = std::make_shared<int>(0);
  9983. res.set_chunked_content_provider("text/plain",
  9984. [step](size_t /*offset*/, DataSink &sink) {
  9985. switch ((*step)++) {
  9986. case 0: sink.write("", 0); break;
  9987. case 1: sink.write("hello", 5); break;
  9988. default: sink.done(); break;
  9989. }
  9990. return true;
  9991. });
  9992. });
  9993. auto port = svr.bind_to_any_port(HOST);
  9994. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9995. auto listen_se = detail::scope_exit([&] {
  9996. svr.stop();
  9997. listen_thread.join();
  9998. ASSERT_FALSE(svr.is_running());
  9999. });
  10000. svr.wait_until_ready();
  10001. Client cli(HOST, port);
  10002. // Without the fix the body is never terminated, so bound the wait rather
  10003. // than letting the test hang on the default read timeout.
  10004. cli.set_read_timeout(5, 0);
  10005. auto res = cli.Get("/stream");
  10006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10007. EXPECT_EQ(StatusCode::OK_200, res->status);
  10008. EXPECT_EQ("hello", res->body);
  10009. }
  10010. TEST(StreamingTest, NoContentLengthStreaming) {
  10011. Server svr;
  10012. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10013. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10014. if (offset < 6) {
  10015. sink.os << (offset < 3 ? "a" : "b");
  10016. } else {
  10017. sink.done();
  10018. }
  10019. return true;
  10020. });
  10021. });
  10022. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10023. auto listen_se = detail::scope_exit([&] {
  10024. svr.stop();
  10025. listen_thread.join();
  10026. ASSERT_FALSE(svr.is_running());
  10027. });
  10028. svr.wait_until_ready();
  10029. Client client(HOST, PORT);
  10030. auto get_thread = std::thread([&client]() {
  10031. std::string s;
  10032. auto res =
  10033. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10034. s += std::string(data, len);
  10035. return true;
  10036. });
  10037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10038. EXPECT_EQ(StatusCode::OK_200, res->status);
  10039. EXPECT_EQ("aaabbb", s);
  10040. });
  10041. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10042. // Give GET time to get a few messages.
  10043. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10044. }
  10045. TEST(MountTest, Unmount) {
  10046. Server svr;
  10047. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10048. auto se = detail::scope_exit([&] {
  10049. svr.stop();
  10050. listen_thread.join();
  10051. ASSERT_FALSE(svr.is_running());
  10052. });
  10053. svr.wait_until_ready();
  10054. Client cli("localhost", PORT);
  10055. svr.set_mount_point("/mount2", "./www2");
  10056. auto res = cli.Get("/");
  10057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10058. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10059. res = cli.Get("/mount2/dir/test.html");
  10060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10061. EXPECT_EQ(StatusCode::OK_200, res->status);
  10062. svr.set_mount_point("/", "./www");
  10063. res = cli.Get("/dir/");
  10064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10065. EXPECT_EQ(StatusCode::OK_200, res->status);
  10066. svr.remove_mount_point("/");
  10067. res = cli.Get("/dir/");
  10068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10069. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10070. svr.remove_mount_point("/mount2");
  10071. res = cli.Get("/mount2/dir/test.html");
  10072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10073. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10074. }
  10075. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10076. Server svr;
  10077. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10078. svr.Get("/api/hello", [](const Request &, Response &res) {
  10079. res.set_content("api", "text/plain");
  10080. });
  10081. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10082. auto se = detail::scope_exit([&] {
  10083. svr.stop();
  10084. listen_thread.join();
  10085. ASSERT_FALSE(svr.is_running());
  10086. });
  10087. svr.wait_until_ready();
  10088. Client cli(HOST, PORT);
  10089. auto res = cli.Get("/dir/test.html");
  10090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10091. EXPECT_EQ(StatusCode::OK_200, res->status);
  10092. res = cli.Get("/api/hello");
  10093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10094. EXPECT_EQ(StatusCode::OK_200, res->status);
  10095. EXPECT_EQ("api", res->body);
  10096. }
  10097. TEST(MountTest, PathSegmentBoundary) {
  10098. Server svr;
  10099. svr.set_mount_point("/mount2", "./www2");
  10100. svr.set_mount_point("/", "./www");
  10101. auto port = svr.bind_to_any_port(HOST);
  10102. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10103. auto se = detail::scope_exit([&] {
  10104. svr.stop();
  10105. listen_thread.join();
  10106. ASSERT_FALSE(svr.is_running());
  10107. });
  10108. svr.wait_until_ready();
  10109. Client cli(HOST, port);
  10110. auto res = cli.Get("/mount2/dir/test.html");
  10111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10112. EXPECT_EQ(StatusCode::OK_200, res->status);
  10113. // "/mount2" must not match part-way through a path segment.
  10114. res = cli.Get("/mount2dir/test.html");
  10115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10117. // A mount point ending in '/' keeps matching every path below it.
  10118. res = cli.Get("/dir/test.html");
  10119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10120. EXPECT_EQ(StatusCode::OK_200, res->status);
  10121. }
  10122. TEST(MountTest, Redicect) {
  10123. Server svr;
  10124. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10125. auto se = detail::scope_exit([&] {
  10126. svr.stop();
  10127. listen_thread.join();
  10128. ASSERT_FALSE(svr.is_running());
  10129. });
  10130. svr.set_mount_point("/", "./www");
  10131. svr.wait_until_ready();
  10132. Client cli("localhost", PORT);
  10133. auto res = cli.Get("/dir/");
  10134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10135. EXPECT_EQ(StatusCode::OK_200, res->status);
  10136. res = cli.Get("/dir");
  10137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10138. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10139. res = cli.Get("/file");
  10140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10141. EXPECT_EQ(StatusCode::OK_200, res->status);
  10142. res = cli.Get("/file/");
  10143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10145. cli.set_follow_location(true);
  10146. res = cli.Get("/dir");
  10147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10148. EXPECT_EQ(StatusCode::OK_200, res->status);
  10149. }
  10150. TEST(MountTest, MultibytesPathName) {
  10151. Server svr;
  10152. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10153. auto se = detail::scope_exit([&] {
  10154. svr.stop();
  10155. listen_thread.join();
  10156. ASSERT_FALSE(svr.is_running());
  10157. });
  10158. svr.set_mount_point("/", "./www");
  10159. svr.wait_until_ready();
  10160. Client cli("localhost", PORT);
  10161. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10163. EXPECT_EQ(StatusCode::OK_200, res->status);
  10164. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10165. }
  10166. #ifdef _WIN32
  10167. // Issue #2435: mmap::open() must succeed even when another handle holds
  10168. // the file open for writing (e.g. an active log file).
  10169. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10170. const char *path = "mmap_concurrent_writer_test.txt";
  10171. const char *content = "hello";
  10172. {
  10173. std::ofstream f(path, std::ios::binary);
  10174. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10175. }
  10176. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10177. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10178. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10179. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10180. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10181. detail::mmap m(path);
  10182. ASSERT_TRUE(m.is_open());
  10183. EXPECT_EQ(strlen(content), m.size());
  10184. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10185. }
  10186. #endif
  10187. #ifndef _WIN32
  10188. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10189. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10190. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10191. TEST(MmapTest, FailedMappingIsNotOpen) {
  10192. const char *path = "./mmap_failed_mapping_test_dir";
  10193. ASSERT_EQ(0, ::mkdir(path, 0755));
  10194. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10195. detail::mmap m(path);
  10196. EXPECT_FALSE(m.is_open());
  10197. EXPECT_EQ(0U, m.size());
  10198. EXPECT_NE(static_cast<const void *>(m.data()),
  10199. static_cast<const void *>(MAP_FAILED));
  10200. }
  10201. #endif
  10202. TEST(KeepAliveTest, ReadTimeout) {
  10203. Server svr;
  10204. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10205. std::this_thread::sleep_for(std::chrono::seconds(2));
  10206. res.set_content("a", "text/plain");
  10207. });
  10208. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10209. res.set_content("b", "text/plain");
  10210. });
  10211. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10212. auto se = detail::scope_exit([&] {
  10213. svr.stop();
  10214. listen_thread.join();
  10215. ASSERT_FALSE(svr.is_running());
  10216. });
  10217. svr.wait_until_ready();
  10218. Client cli("localhost", PORT);
  10219. cli.set_keep_alive(true);
  10220. cli.set_read_timeout(std::chrono::seconds(1));
  10221. auto resa = cli.Get("/a");
  10222. ASSERT_FALSE(resa);
  10223. EXPECT_EQ(Error::Read, resa.error());
  10224. auto resb = cli.Get("/b");
  10225. ASSERT_TRUE(resb);
  10226. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10227. EXPECT_EQ("b", resb->body);
  10228. }
  10229. TEST(KeepAliveTest, MaxCount) {
  10230. size_t keep_alive_max_count = 3;
  10231. Server svr;
  10232. svr.set_keep_alive_max_count(keep_alive_max_count);
  10233. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10234. res.set_content("Hello World!", "text/plain");
  10235. });
  10236. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10237. auto se = detail::scope_exit([&] {
  10238. svr.stop();
  10239. listen_thread.join();
  10240. ASSERT_FALSE(svr.is_running());
  10241. });
  10242. svr.wait_until_ready();
  10243. Client cli(HOST, PORT);
  10244. cli.set_keep_alive(true);
  10245. for (size_t i = 0; i < 5; i++) {
  10246. auto result = cli.Get("/hi");
  10247. ASSERT_TRUE(result);
  10248. EXPECT_EQ(StatusCode::OK_200, result->status);
  10249. if (i == keep_alive_max_count - 1) {
  10250. EXPECT_EQ("close", result->get_header_value("Connection"));
  10251. } else {
  10252. EXPECT_FALSE(result->has_header("Connection"));
  10253. }
  10254. }
  10255. }
  10256. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10257. // can pull the next one into the server's buffer. The server must serve it
  10258. // without waiting for the socket to become readable again. The keep-alive
  10259. // timeout outlasts the client's read timeout, so a request left waiting for it
  10260. // shows up as a missing response.
  10261. static void serve_pipelining_routes(Server &svr,
  10262. const std::function<void(int)> &client) {
  10263. svr.set_keep_alive_timeout(5);
  10264. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10265. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10266. });
  10267. svr.Post("/echo", [](const Request &req, Response &res) {
  10268. res.set_content("echo " + req.body, "text/plain");
  10269. });
  10270. auto port = svr.bind_to_any_port(HOST);
  10271. thread t = thread([&] { svr.listen_after_bind(); });
  10272. auto se = detail::scope_exit([&] {
  10273. svr.stop();
  10274. t.join();
  10275. });
  10276. svr.wait_until_ready();
  10277. client(port);
  10278. }
  10279. static std::string
  10280. send_pipelined_requests(const std::vector<std::string> &parts) {
  10281. Server svr;
  10282. std::string res;
  10283. serve_pipelining_routes(svr, [&](int port) {
  10284. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10285. });
  10286. return res;
  10287. }
  10288. static void expect_in_order(const std::string &res,
  10289. const std::vector<std::string> &bodies) {
  10290. size_t pos = 0;
  10291. for (const auto &body : bodies) {
  10292. pos = res.find(body, pos);
  10293. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10294. pos += body.size();
  10295. }
  10296. }
  10297. TEST(KeepAliveTest, PipelinedRequests) {
  10298. auto res = send_pipelined_requests(
  10299. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10300. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10301. "Content-Length: 4\r\n\r\nbody"
  10302. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10303. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10304. }
  10305. // The second request starts in the server's buffer and ends on the socket.
  10306. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10307. auto res =
  10308. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10309. "GET /hi/2 HTTP/1.1\r\nHo",
  10310. "st: localhost\r\nConnection: close\r\n\r\n"});
  10311. expect_in_order(res, {"hi 1", "hi 2"});
  10312. }
  10313. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10314. // CRLF after a body does not turn into a 400 for the next request.
  10315. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10316. auto res = send_pipelined_requests(
  10317. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10318. "Content-Length: 4\r\n\r\nbody\r\n"
  10319. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10320. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10321. expect_in_order(res, {"echo body", "hi 2"});
  10322. }
  10323. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10324. // must not be served as the next request.
  10325. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10326. auto res = send_pipelined_requests(
  10327. {"INVALID REQUEST LINE\r\n\r\n"
  10328. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10329. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10330. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10331. }
  10332. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10333. // Over TLS, the next request is held by the TLS library as already decrypted
  10334. // data rather than on the socket.
  10335. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10337. std::string res;
  10338. serve_pipelining_routes(svr, [&](int port) {
  10339. // One part, so all three requests arrive in one TLS record
  10340. EXPECT_TRUE(send_ssl_request_in_parts(
  10341. 2,
  10342. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10343. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10344. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10345. &res, port));
  10346. });
  10347. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10348. }
  10349. #endif
  10350. TEST(KeepAliveTest, Issue1041) {
  10351. Server svr;
  10352. svr.set_keep_alive_timeout(3);
  10353. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10354. res.set_content("Hello World!", "text/plain");
  10355. });
  10356. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10357. auto se = detail::scope_exit([&] {
  10358. svr.stop();
  10359. listen_thread.join();
  10360. ASSERT_FALSE(svr.is_running());
  10361. });
  10362. svr.wait_until_ready();
  10363. Client cli(HOST, PORT);
  10364. cli.set_keep_alive(true);
  10365. auto result = cli.Get("/hi");
  10366. ASSERT_TRUE(result);
  10367. EXPECT_EQ(StatusCode::OK_200, result->status);
  10368. std::this_thread::sleep_for(std::chrono::seconds(5));
  10369. result = cli.Get("/hi");
  10370. ASSERT_TRUE(result);
  10371. EXPECT_EQ(StatusCode::OK_200, result->status);
  10372. }
  10373. TEST(KeepAliveTest, Issue1959) {
  10374. Server svr;
  10375. svr.set_keep_alive_timeout(5);
  10376. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10377. res.set_content("a", "text/plain");
  10378. });
  10379. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10380. auto se = detail::scope_exit([&] {
  10381. if (!svr.is_running()) return;
  10382. svr.stop();
  10383. listen_thread.join();
  10384. ASSERT_FALSE(svr.is_running());
  10385. });
  10386. svr.wait_until_ready();
  10387. Client cli("localhost", PORT);
  10388. cli.set_keep_alive(true);
  10389. using namespace std::chrono;
  10390. auto start = steady_clock::now();
  10391. cli.Get("/a");
  10392. svr.stop();
  10393. listen_thread.join();
  10394. auto end = steady_clock::now();
  10395. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10396. EXPECT_LT(elapsed, 5000);
  10397. }
  10398. #ifdef CPPHTTPLIB_SSL_ENABLED
  10399. TEST(KeepAliveTest, SSLClientReconnection) {
  10400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10401. ASSERT_TRUE(svr.is_valid());
  10402. svr.set_keep_alive_timeout(1);
  10403. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10404. res.set_content("Hello World!", "text/plain");
  10405. });
  10406. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10407. auto se = detail::scope_exit([&] {
  10408. svr.stop();
  10409. listen_thread.join();
  10410. ASSERT_FALSE(svr.is_running());
  10411. });
  10412. svr.wait_until_ready();
  10413. SSLClient cli(HOST, PORT);
  10414. cli.enable_server_certificate_verification(false);
  10415. cli.set_keep_alive(true);
  10416. auto result = cli.Get("/hi");
  10417. ASSERT_TRUE(result);
  10418. EXPECT_EQ(StatusCode::OK_200, result->status);
  10419. result = cli.Get("/hi");
  10420. ASSERT_TRUE(result);
  10421. EXPECT_EQ(StatusCode::OK_200, result->status);
  10422. std::this_thread::sleep_for(std::chrono::seconds(2));
  10423. // Recoonect
  10424. result = cli.Get("/hi");
  10425. ASSERT_TRUE(result);
  10426. EXPECT_EQ(StatusCode::OK_200, result->status);
  10427. result = cli.Get("/hi");
  10428. ASSERT_TRUE(result);
  10429. EXPECT_EQ(StatusCode::OK_200, result->status);
  10430. }
  10431. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10433. ASSERT_TRUE(svr.is_valid());
  10434. svr.set_keep_alive_timeout(1);
  10435. std::string content = "reconnect";
  10436. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10437. res.set_content("Hello World!", "text/plain");
  10438. });
  10439. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10440. auto se = detail::scope_exit([&] {
  10441. svr.stop();
  10442. listen_thread.join();
  10443. ASSERT_FALSE(svr.is_running());
  10444. });
  10445. svr.wait_until_ready();
  10446. SSLClient cli(HOST, PORT);
  10447. cli.enable_server_certificate_verification(false);
  10448. cli.set_keep_alive(true);
  10449. auto result = cli.Post(
  10450. "/hi", content.size(),
  10451. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10452. sink.write(content.c_str(), content.size());
  10453. return true;
  10454. },
  10455. "text/plain");
  10456. ASSERT_TRUE(result);
  10457. EXPECT_EQ(200, result->status);
  10458. std::this_thread::sleep_for(std::chrono::seconds(2));
  10459. // Recoonect
  10460. result = cli.Post(
  10461. "/hi", content.size(),
  10462. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10463. sink.write(content.c_str(), content.size());
  10464. return true;
  10465. },
  10466. "text/plain");
  10467. ASSERT_TRUE(result);
  10468. EXPECT_EQ(200, result->status);
  10469. result = cli.Post(
  10470. "/hi", content.size(),
  10471. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10472. sink.write(content.c_str(), content.size());
  10473. return true;
  10474. },
  10475. "text/plain");
  10476. ASSERT_TRUE(result);
  10477. EXPECT_EQ(200, result->status);
  10478. }
  10479. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10480. using namespace httplib::tls;
  10481. {
  10482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10483. ASSERT_TRUE(svr.is_valid());
  10484. svr.Get("/sni", [&](const Request &req, Response &res) {
  10485. std::string expected = req.sni();
  10486. EXPECT_EQ(expected, req.get_param_value("expected"));
  10487. res.set_content("ok", "text/plain");
  10488. });
  10489. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10490. auto se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. listen_thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. {
  10497. SSLClient cli("localhost", PORT);
  10498. cli.enable_server_certificate_verification(false);
  10499. auto res = cli.Get("/sni?expected=localhost");
  10500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10501. }
  10502. {
  10503. SSLClient cli("::1", PORT);
  10504. cli.enable_server_certificate_verification(false);
  10505. auto res = cli.Get("/sni?expected=");
  10506. // NOTE: This may fail if the server is listening on IPv4 only
  10507. // (e.g., when localhost resolves to 127.0.0.1 only)
  10508. if (res) {
  10509. EXPECT_EQ(StatusCode::OK_200, res->status);
  10510. } else {
  10511. EXPECT_EQ(Error::Connection, res.error());
  10512. }
  10513. }
  10514. }
  10515. }
  10516. #endif
  10517. TEST(ClientProblemDetectionTest, ContentProvider) {
  10518. Server svr;
  10519. size_t content_length = 1024 * 1024;
  10520. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10521. res.set_content_provider(
  10522. content_length, "text/plain",
  10523. [&](size_t offset, size_t length, DataSink &sink) {
  10524. auto out_len = std::min(length, static_cast<size_t>(1024));
  10525. std::string out(out_len, '@');
  10526. sink.write(out.data(), out_len);
  10527. return offset < 4096;
  10528. },
  10529. [](bool success) { ASSERT_FALSE(success); });
  10530. });
  10531. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10532. res.set_content_provider(
  10533. 0, "text/plain",
  10534. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10535. EXPECT_TRUE(false);
  10536. return true;
  10537. },
  10538. [](bool success) { ASSERT_FALSE(success); });
  10539. });
  10540. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10541. auto se = detail::scope_exit([&] {
  10542. svr.stop();
  10543. listen_thread.join();
  10544. ASSERT_FALSE(svr.is_running());
  10545. });
  10546. svr.wait_until_ready();
  10547. Client cli("localhost", PORT);
  10548. {
  10549. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10550. size_t /*data_length*/) { return false; });
  10551. ASSERT_FALSE(res);
  10552. }
  10553. {
  10554. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10555. size_t /*data_length*/) { return false; });
  10556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10557. }
  10558. }
  10559. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10560. // A provider that reports success without writing anything and without
  10561. // calling done() used to be handed the same offset and length again on every
  10562. // pass, so it spun for as long as the peer stayed connected.
  10563. Server svr;
  10564. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10565. res.set_content("ok", "text/plain");
  10566. });
  10567. auto port = svr.bind_to_any_port(HOST);
  10568. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10569. auto se = detail::scope_exit([&] {
  10570. svr.stop();
  10571. listen_thread.join();
  10572. ASSERT_FALSE(svr.is_running());
  10573. });
  10574. svr.wait_until_ready();
  10575. std::atomic<int> call_count{0};
  10576. Client cli(HOST, port);
  10577. auto res = cli.Post(
  10578. "/", 1024,
  10579. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10580. // Give up after enough passes to show the spin, so that losing the
  10581. // check below fails this test instead of hanging it.
  10582. return ++call_count < 100;
  10583. },
  10584. "text/plain");
  10585. ASSERT_FALSE(res);
  10586. EXPECT_EQ(Error::Write, res.error());
  10587. EXPECT_EQ(1, call_count.load());
  10588. }
  10589. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10590. // A writer only has to assign `write`. The other three used to be left as
  10591. // empty std::functions, so a provider calling one threw
  10592. // std::bad_function_call out of the thread running it and took the whole
  10593. // process down.
  10594. DataSink sink;
  10595. std::string written;
  10596. sink.write = [&](const char *data, size_t data_len) {
  10597. written.append(data, data_len);
  10598. return true;
  10599. };
  10600. EXPECT_TRUE(sink.is_writable());
  10601. sink.done();
  10602. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10603. EXPECT_TRUE(written.empty());
  10604. }
  10605. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10606. // A sink that cannot carry trailers still has to finish.
  10607. DataSink sink;
  10608. auto done_count = 0;
  10609. sink.done = [&]() { done_count++; };
  10610. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10611. EXPECT_EQ(1, done_count);
  10612. }
  10613. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10614. Server svr;
  10615. const std::string body(4096, 'x');
  10616. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10617. res.set_content_provider(body.size(), "text/plain",
  10618. [&](size_t offset, size_t length, DataSink &sink) {
  10619. sink.write(body.data() + offset, length);
  10620. sink.done();
  10621. return true;
  10622. });
  10623. });
  10624. auto port = svr.bind_to_any_port(HOST);
  10625. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10626. auto se = detail::scope_exit([&] {
  10627. svr.stop();
  10628. listen_thread.join();
  10629. ASSERT_FALSE(svr.is_running());
  10630. });
  10631. svr.wait_until_ready();
  10632. Client cli(HOST, port);
  10633. auto res = cli.Get("/");
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::OK_200, res->status);
  10636. EXPECT_EQ(body, res->body);
  10637. }
  10638. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10639. Server svr;
  10640. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10641. res.set_content_provider(
  10642. 1024, "text/plain",
  10643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10644. sink.write("hello", 5);
  10645. sink.done(); // short of the 1024 bytes the response promised
  10646. return true;
  10647. });
  10648. });
  10649. auto port = svr.bind_to_any_port(HOST);
  10650. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. listen_thread.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client cli(HOST, port);
  10658. cli.set_read_timeout(5, 0);
  10659. // The response is short of its Content-Length, so the client cannot read a
  10660. // complete body. What matters is that this returns at all: a no-op done()
  10661. // would leave the writer looping over a provider that never makes progress.
  10662. auto res = cli.Get("/");
  10663. EXPECT_FALSE(res);
  10664. }
  10665. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10666. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10667. // The compressed path builds the whole body before connecting, so this
  10668. // fails client-side and never reaches a server.
  10669. Client cli(HOST, PORT);
  10670. cli.set_compress(true);
  10671. auto res = cli.Post(
  10672. "/", 1024,
  10673. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10674. sink.write("hello", 5);
  10675. sink.done(); // short of the 1024 bytes the request announced
  10676. return true;
  10677. },
  10678. "text/plain");
  10679. ASSERT_FALSE(res);
  10680. EXPECT_EQ(Error::Write, res.error());
  10681. }
  10682. #endif
  10683. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10684. Server svr;
  10685. svr.set_error_handler([](Request const &, Response &res) -> void {
  10686. res.set_chunked_content_provider(
  10687. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10688. sink.os << "hello";
  10689. sink.os << "world";
  10690. sink.done();
  10691. return true;
  10692. });
  10693. });
  10694. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10695. auto se = detail::scope_exit([&] {
  10696. svr.stop();
  10697. listen_thread.join();
  10698. ASSERT_FALSE(svr.is_running());
  10699. });
  10700. svr.wait_until_ready();
  10701. Client cli("localhost", PORT);
  10702. auto res = cli.Get("/");
  10703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10705. EXPECT_EQ("helloworld", res->body);
  10706. }
  10707. // A body set after a content provider must replace it, not be sent through it.
  10708. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10709. Server svr;
  10710. svr.set_mount_point("/", "./www");
  10711. svr.set_file_request_handler([](const Request &req, Response &res) {
  10712. if (req.path == "/dir/test.html") {
  10713. res.status = StatusCode::Forbidden_403;
  10714. res.set_content(std::string(5000, 'D'), "text/plain");
  10715. } else if (req.path == "/file") {
  10716. res.status = StatusCode::Forbidden_403;
  10717. res.body = "Denied";
  10718. }
  10719. });
  10720. auto port = svr.bind_to_any_port(HOST);
  10721. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10722. auto se = detail::scope_exit([&] {
  10723. svr.stop();
  10724. t.join();
  10725. ASSERT_FALSE(svr.is_running());
  10726. });
  10727. svr.wait_until_ready();
  10728. Client cli(HOST, port);
  10729. {
  10730. auto res = cli.Get("/dir/test.html");
  10731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10732. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10733. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10734. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10735. }
  10736. {
  10737. auto res = cli.Get("/file");
  10738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10739. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10740. EXPECT_EQ("Denied", res->body);
  10741. }
  10742. {
  10743. auto res = cli.Get("/dir/index.html");
  10744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10745. EXPECT_EQ(StatusCode::OK_200, res->status);
  10746. EXPECT_EQ(0U, res->body.find("<html>"));
  10747. }
  10748. }
  10749. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10750. Server svr;
  10751. std::vector<bool> released;
  10752. std::mutex released_mutex;
  10753. auto releaser = [&](bool success) {
  10754. std::lock_guard<std::mutex> guard(released_mutex);
  10755. released.push_back(success);
  10756. };
  10757. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10758. return sink.write(&"hello"[offset], length);
  10759. };
  10760. svr.Get("/sized", [&](const Request &, Response &res) {
  10761. res.status = StatusCode::NotFound_404;
  10762. res.set_content_provider(5, "text/plain", provider, releaser);
  10763. });
  10764. svr.Get("/chunked", [&](const Request &, Response &res) {
  10765. res.status = StatusCode::ServiceUnavailable_503;
  10766. res.set_chunked_content_provider(
  10767. "text/plain",
  10768. [](size_t, DataSink &sink) {
  10769. sink.os << "chunk";
  10770. sink.done();
  10771. return true;
  10772. },
  10773. releaser);
  10774. });
  10775. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10776. res.set_content_provider(5, "text/plain", provider, releaser);
  10777. throw std::runtime_error("after the provider");
  10778. });
  10779. svr.set_error_handler([](const Request &req, Response &res) {
  10780. // Leave the exception handler's content to it.
  10781. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10782. res.set_content(std::string(1000, 'E'), "text/html");
  10783. return Server::HandlerResponse::Handled;
  10784. });
  10785. svr.set_exception_handler(
  10786. [](const Request &, Response &res, std::exception_ptr) {
  10787. res.status = StatusCode::InternalServerError_500;
  10788. res.set_content(std::string(1000, 'X'), "text/html");
  10789. });
  10790. auto port = svr.bind_to_any_port(HOST);
  10791. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10792. auto se = detail::scope_exit([&] {
  10793. svr.stop();
  10794. t.join();
  10795. ASSERT_FALSE(svr.is_running());
  10796. });
  10797. svr.wait_until_ready();
  10798. Client cli(HOST, port);
  10799. {
  10800. auto res = cli.Get("/sized");
  10801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10802. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10803. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10804. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10805. }
  10806. {
  10807. auto res = cli.Get("/chunked");
  10808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10809. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10810. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10811. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10812. }
  10813. {
  10814. auto res = cli.Get("/throw");
  10815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10816. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10817. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10818. }
  10819. std::lock_guard<std::mutex> guard(released_mutex);
  10820. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10821. }
  10822. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10823. Server svr;
  10824. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10825. return sink.write(&"abc"[offset], length);
  10826. };
  10827. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10828. res.set_file_content("./www/dir/test.html");
  10829. res.set_content("body", "text/plain");
  10830. });
  10831. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10832. res.set_content(std::string(100, 'B'), "text/plain");
  10833. res.set_file_content("./www/dir/test.html");
  10834. });
  10835. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10836. res.set_content(std::string(100, 'B'), "text/plain");
  10837. res.set_content_provider(3, "text/plain", abc);
  10838. });
  10839. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10840. res.set_content_provider(3, "text/plain", abc);
  10841. res.set_content(std::string(100, 'B'), "text/plain");
  10842. });
  10843. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10844. res.set_content_provider(3, "text/plain", abc);
  10845. res.body = "direct";
  10846. });
  10847. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10848. res.set_file_content("./www/dir/test.html");
  10849. res.body = "direct";
  10850. });
  10851. auto port = svr.bind_to_any_port(HOST);
  10852. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10853. auto se = detail::scope_exit([&] {
  10854. svr.stop();
  10855. t.join();
  10856. ASSERT_FALSE(svr.is_running());
  10857. });
  10858. svr.wait_until_ready();
  10859. Client cli(HOST, port);
  10860. auto expect_body = [&](const char *path, const std::string &body) {
  10861. // Uncompressed, so Content-Length can be compared with the body.
  10862. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10863. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10864. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10865. EXPECT_EQ(body, res->body) << path;
  10866. EXPECT_EQ(std::to_string(body.size()),
  10867. res->get_header_value("Content-Length"))
  10868. << path;
  10869. };
  10870. expect_body("/file-then-body", "body");
  10871. expect_body("/body-then-file", "test.html");
  10872. expect_body("/body-then-provider", "abc");
  10873. expect_body("/provider-then-body", std::string(100, 'B'));
  10874. expect_body("/provider-then-direct-body", "direct");
  10875. expect_body("/file-then-direct-body", "direct");
  10876. // Ranges are checked against the body, not the dropped provider.
  10877. {
  10878. auto res = cli.Get("/provider-then-direct-body",
  10879. Headers{{make_range_header({{1, 2}})}});
  10880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10881. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10882. EXPECT_EQ("ir", res->body);
  10883. }
  10884. {
  10885. auto res = cli.Get("/file-then-direct-body",
  10886. Headers{{make_range_header({{7, 8}})}});
  10887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10888. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10889. }
  10890. }
  10891. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  10892. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  10893. const char *path = "./truncated_while_served.txt";
  10894. const size_t size = 32 * 1024 * 1024;
  10895. {
  10896. std::ofstream f(path, std::ios::binary);
  10897. f << std::string(size, 'x');
  10898. }
  10899. auto se_file = detail::scope_exit([&] { std::remove(path); });
  10900. // Over TLS, where the bytes are encrypted in this process rather than
  10901. // copied by send().
  10902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10903. svr.Get("/file", [&](const Request &, Response &res) {
  10904. res.set_file_content(path, "text/plain");
  10905. });
  10906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop();
  10909. thread.join();
  10910. ASSERT_FALSE(svr.is_running());
  10911. });
  10912. svr.wait_until_ready();
  10913. // The file shrinks once the first bytes are in, as a rewrite in place
  10914. // would, and reading the mapping past its new end used to raise SIGBUS.
  10915. SSLClient cli(HOST, PORT);
  10916. cli.enable_server_certificate_verification(false);
  10917. size_t received = 0;
  10918. auto res = cli.Get("/file", [&](const char *, size_t len) {
  10919. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  10920. received += len;
  10921. return true;
  10922. });
  10923. EXPECT_FALSE(res);
  10924. EXPECT_LT(received, size);
  10925. }
  10926. #endif
  10927. // Forward declaration (see the base64_encode note).
  10928. namespace httplib {
  10929. namespace detail {
  10930. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10931. const std::string &content_type,
  10932. EncodingType encoding);
  10933. } // namespace detail
  10934. } // namespace httplib
  10935. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10936. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10937. ASSERT_TRUE(mm->is_open());
  10938. Response res;
  10939. detail::set_file_content_provider(res, mm, "text/html",
  10940. detail::EncodingType::None);
  10941. std::string out;
  10942. DataSink sink;
  10943. sink.write = [&](const char *d, size_t l) {
  10944. out.append(d, l);
  10945. return true;
  10946. };
  10947. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10948. EXPECT_EQ("test.html", out);
  10949. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10950. EXPECT_EQ("test.html", out);
  10951. }
  10952. TEST(LongPollingTest, ClientCloseDetection) {
  10953. Server svr;
  10954. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10955. res.set_chunked_content_provider(
  10956. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10957. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10958. sink.os << "hello";
  10959. auto count = 10;
  10960. while (count > 0 && sink.is_writable()) {
  10961. this_thread::sleep_for(chrono::milliseconds(10));
  10962. count--;
  10963. }
  10964. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10965. return true;
  10966. });
  10967. });
  10968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10969. auto se = detail::scope_exit([&] {
  10970. svr.stop();
  10971. listen_thread.join();
  10972. ASSERT_FALSE(svr.is_running());
  10973. });
  10974. svr.wait_until_ready();
  10975. Client cli("localhost", PORT);
  10976. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10977. EXPECT_EQ("hello", string(data, data_length));
  10978. return false; // close the socket immediately.
  10979. });
  10980. ASSERT_FALSE(res);
  10981. }
  10982. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10983. Server svr;
  10984. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10985. res.set_chunked_content_provider(
  10986. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10987. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10988. sink.os << "hello";
  10989. EXPECT_TRUE(sink.os.good());
  10990. // Wait for the client to close the connection
  10991. auto count = 10;
  10992. while (count > 0 && sink.is_writable()) {
  10993. this_thread::sleep_for(chrono::milliseconds(10));
  10994. count--;
  10995. }
  10996. // After client disconnect, write repeatedly until the socket
  10997. // write actually fails (small writes may be absorbed by the
  10998. // kernel buffer)
  10999. std::string chunk(1024, 'x');
  11000. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11001. sink.os << chunk;
  11002. }
  11003. EXPECT_TRUE(sink.os.fail());
  11004. return true;
  11005. });
  11006. });
  11007. auto port = svr.bind_to_any_port("localhost");
  11008. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11009. auto se = detail::scope_exit([&] {
  11010. svr.stop();
  11011. listen_thread.join();
  11012. ASSERT_FALSE(svr.is_running());
  11013. });
  11014. svr.wait_until_ready();
  11015. Client cli("localhost", port);
  11016. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11017. EXPECT_EQ("hello", string(data, data_length));
  11018. return false; // close the socket immediately.
  11019. });
  11020. ASSERT_FALSE(res);
  11021. }
  11022. TEST(GetWithParametersTest, GetWithParameters) {
  11023. Server svr;
  11024. svr.Get("/", [&](const Request &req, Response &) {
  11025. EXPECT_EQ("world", req.get_param_value("hello"));
  11026. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11027. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11028. });
  11029. svr.Get("/params", [&](const Request &req, Response &) {
  11030. EXPECT_EQ("world", req.get_param_value("hello"));
  11031. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11032. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11033. });
  11034. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11035. EXPECT_EQ("resource-id", req.matches[1]);
  11036. EXPECT_EQ("foo", req.get_param_value("param1"));
  11037. EXPECT_EQ("bar", req.get_param_value("param2"));
  11038. });
  11039. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11040. EXPECT_EQ("user-id", req.path_params.at("id"));
  11041. EXPECT_EQ("foo", req.get_param_value("param1"));
  11042. EXPECT_EQ("bar", req.get_param_value("param2"));
  11043. });
  11044. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11045. auto se = detail::scope_exit([&] {
  11046. svr.stop();
  11047. listen_thread.join();
  11048. ASSERT_FALSE(svr.is_running());
  11049. });
  11050. svr.wait_until_ready();
  11051. {
  11052. Client cli(HOST, PORT);
  11053. Params params;
  11054. params.emplace("hello", "world");
  11055. params.emplace("hello2", "world2");
  11056. params.emplace("hello3", "world3");
  11057. auto res = cli.Get("/", params, Headers{});
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::OK_200, res->status);
  11060. }
  11061. {
  11062. Client cli(HOST, PORT);
  11063. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11065. EXPECT_EQ(StatusCode::OK_200, res->status);
  11066. }
  11067. {
  11068. Client cli(HOST, PORT);
  11069. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11071. EXPECT_EQ(StatusCode::OK_200, res->status);
  11072. }
  11073. {
  11074. Client cli(HOST, PORT);
  11075. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11077. EXPECT_EQ(StatusCode::OK_200, res->status);
  11078. }
  11079. }
  11080. TEST(GetWithParametersTest, GetWithParameters2) {
  11081. Server svr;
  11082. svr.Get("/", [&](const Request &req, Response &res) {
  11083. auto text = req.get_param_value("hello");
  11084. res.set_content(text, "text/plain");
  11085. });
  11086. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11087. auto se = detail::scope_exit([&] {
  11088. svr.stop();
  11089. listen_thread.join();
  11090. ASSERT_FALSE(svr.is_running());
  11091. });
  11092. svr.wait_until_ready();
  11093. Client cli("localhost", PORT);
  11094. Params params;
  11095. params.emplace("hello", "world");
  11096. std::string body;
  11097. auto res = cli.Get("/", params, Headers{},
  11098. [&](const char *data, size_t data_length) {
  11099. body.append(data, data_length);
  11100. return true;
  11101. });
  11102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11103. EXPECT_EQ(StatusCode::OK_200, res->status);
  11104. EXPECT_EQ("world", body);
  11105. }
  11106. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11107. Server svr;
  11108. svr.Get("/search", [&](const Request &req, Response &res) {
  11109. auto q = req.get_param_value("q");
  11110. res.set_content(q, "text/plain");
  11111. });
  11112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11113. auto se = detail::scope_exit([&] {
  11114. svr.stop();
  11115. listen_thread.join();
  11116. ASSERT_FALSE(svr.is_running());
  11117. });
  11118. svr.wait_until_ready();
  11119. Client cli("localhost", PORT);
  11120. // Verify that Get(path, params) works without requiring Headers argument
  11121. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11123. EXPECT_EQ(StatusCode::OK_200, res->status);
  11124. EXPECT_EQ("cpp-httplib", res->body);
  11125. }
  11126. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11127. auto host = "httpbingo.org";
  11128. auto path = std::string{"/range/32"};
  11129. #ifdef CPPHTTPLIB_SSL_ENABLED
  11130. SSLClient cli(host);
  11131. #else
  11132. Client cli(host);
  11133. #endif
  11134. cli.set_default_headers({make_range_header({{1, 10}})});
  11135. cli.set_connection_timeout(5);
  11136. {
  11137. auto res = cli.Get(path);
  11138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11139. EXPECT_EQ("bcdefghijk", res->body);
  11140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11141. }
  11142. {
  11143. auto res = cli.Get(path);
  11144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11145. EXPECT_EQ("bcdefghijk", res->body);
  11146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11147. }
  11148. }
  11149. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11150. Server svr;
  11151. svr.set_default_headers({{"Hello", "World"}});
  11152. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11153. res.set_content("ok", "text/plain");
  11154. });
  11155. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11156. auto se = detail::scope_exit([&] {
  11157. svr.stop();
  11158. listen_thread.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. });
  11161. svr.wait_until_ready();
  11162. Client cli("localhost", PORT);
  11163. auto res = cli.Get("/");
  11164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11165. EXPECT_EQ(StatusCode::OK_200, res->status);
  11166. EXPECT_EQ("ok", res->body);
  11167. EXPECT_EQ("World", res->get_header_value("Hello"));
  11168. }
  11169. #ifdef CPPHTTPLIB_SSL_ENABLED
  11170. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11172. ASSERT_TRUE(svr.is_valid());
  11173. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11174. std::this_thread::sleep_for(std::chrono::seconds(2));
  11175. res.set_content("a", "text/plain");
  11176. });
  11177. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11178. res.set_content("b", "text/plain");
  11179. });
  11180. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11181. auto se = detail::scope_exit([&] {
  11182. svr.stop();
  11183. listen_thread.join();
  11184. ASSERT_FALSE(svr.is_running());
  11185. });
  11186. svr.wait_until_ready();
  11187. SSLClient cli("localhost", PORT);
  11188. cli.enable_server_certificate_verification(false);
  11189. cli.set_keep_alive(true);
  11190. cli.set_read_timeout(std::chrono::seconds(1));
  11191. auto resa = cli.Get("/a");
  11192. ASSERT_TRUE(!resa);
  11193. EXPECT_EQ(Error::Read, resa.error());
  11194. auto resb = cli.Get("/b");
  11195. ASSERT_TRUE(resb);
  11196. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11197. EXPECT_EQ("b", resb->body);
  11198. }
  11199. // Closing an idle keep-alive connection sends close_notify and returns. The
  11200. // server must not wait for the client's close_notify: an idle client never
  11201. // sends one, so the worker would be held until the read timeout expires, and
  11202. // stop() would wait for it.
  11203. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11205. ASSERT_TRUE(svr.is_valid());
  11206. svr.set_keep_alive_timeout(1);
  11207. svr.set_read_timeout(10, 0);
  11208. svr.Get("/", [](const Request &, Response &res) {
  11209. res.set_content("ok", "text/plain");
  11210. });
  11211. auto port = svr.bind_to_any_port(HOST);
  11212. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11213. auto se = detail::scope_exit([&] {
  11214. if (listen_thread.joinable()) {
  11215. svr.stop();
  11216. listen_thread.join();
  11217. }
  11218. });
  11219. svr.wait_until_ready();
  11220. SSLClient cli(HOST, port);
  11221. cli.enable_server_certificate_verification(false);
  11222. cli.set_keep_alive(true);
  11223. auto res = cli.Get("/");
  11224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11225. EXPECT_EQ(StatusCode::OK_200, res->status);
  11226. // Stay idle past the keep-alive timeout so the server closes the connection.
  11227. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11228. auto start = std::chrono::steady_clock::now();
  11229. svr.stop();
  11230. listen_thread.join();
  11231. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11232. std::chrono::steady_clock::now() - start)
  11233. .count();
  11234. EXPECT_LT(elapsed, 3000);
  11235. }
  11236. #endif
  11237. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11238. protected:
  11239. ServerTestWithAI_PASSIVE()
  11240. : cli_(HOST, PORT)
  11241. #ifdef CPPHTTPLIB_SSL_ENABLED
  11242. ,
  11243. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11244. #endif
  11245. {
  11246. #ifdef CPPHTTPLIB_SSL_ENABLED
  11247. cli_.enable_server_certificate_verification(false);
  11248. #endif
  11249. }
  11250. virtual void SetUp() {
  11251. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11252. res.set_content("Hello World!", "text/plain");
  11253. });
  11254. t_ = thread(
  11255. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11256. svr_.wait_until_ready();
  11257. }
  11258. virtual void TearDown() {
  11259. svr_.stop();
  11260. t_.join();
  11261. }
  11262. #ifdef CPPHTTPLIB_SSL_ENABLED
  11263. SSLClient cli_;
  11264. SSLServer svr_;
  11265. #else
  11266. Client cli_;
  11267. Server svr_;
  11268. #endif
  11269. thread t_;
  11270. };
  11271. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11272. auto res = cli_.Get("/hi");
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ(StatusCode::OK_200, res->status);
  11275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11276. EXPECT_EQ("Hello World!", res->body);
  11277. }
  11278. class ServerUpDownTest : public ::testing::Test {
  11279. protected:
  11280. ServerUpDownTest() : cli_(HOST, PORT) {}
  11281. virtual void SetUp() {
  11282. t_ = thread([&]() {
  11283. svr_.bind_to_any_port(HOST);
  11284. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11285. ASSERT_TRUE(svr_.listen_after_bind());
  11286. });
  11287. svr_.wait_until_ready();
  11288. }
  11289. virtual void TearDown() {
  11290. svr_.stop();
  11291. t_.join();
  11292. }
  11293. Client cli_;
  11294. Server svr_;
  11295. thread t_;
  11296. };
  11297. TEST_F(ServerUpDownTest, QuickStartStop) {
  11298. // Should not crash, especially when run with
  11299. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11300. }
  11301. class PayloadMaxLengthTest : public ::testing::Test {
  11302. protected:
  11303. PayloadMaxLengthTest()
  11304. : cli_(HOST, PORT)
  11305. #ifdef CPPHTTPLIB_SSL_ENABLED
  11306. ,
  11307. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11308. #endif
  11309. {
  11310. #ifdef CPPHTTPLIB_SSL_ENABLED
  11311. cli_.enable_server_certificate_verification(false);
  11312. #endif
  11313. }
  11314. virtual void SetUp() {
  11315. svr_.set_payload_max_length(8);
  11316. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11317. res.set_content("test", "text/plain");
  11318. });
  11319. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11320. svr_.wait_until_ready();
  11321. }
  11322. virtual void TearDown() {
  11323. svr_.stop();
  11324. t_.join();
  11325. }
  11326. #ifdef CPPHTTPLIB_SSL_ENABLED
  11327. SSLClient cli_;
  11328. SSLServer svr_;
  11329. #else
  11330. Client cli_;
  11331. Server svr_;
  11332. #endif
  11333. thread t_;
  11334. };
  11335. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11336. auto res = cli_.Post("/test", "123456789", "text/plain");
  11337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11338. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11339. res = cli_.Post("/test", "12345678", "text/plain");
  11340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11341. EXPECT_EQ(StatusCode::OK_200, res->status);
  11342. }
  11343. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11344. // Test chunked encoding with payload exceeding the 8-byte limit
  11345. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11346. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11348. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11349. }
  11350. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11351. // Test chunked encoding with payload within the 8-byte limit
  11352. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11353. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11355. EXPECT_EQ(StatusCode::OK_200, res->status);
  11356. }
  11357. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11358. // Test using send_request to send chunked data exceeding payload limit
  11359. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11360. "Host: " +
  11361. std::string(HOST) + ":" + std::to_string(PORT) +
  11362. "\r\n"
  11363. "Transfer-Encoding: chunked\r\n"
  11364. "Connection: close\r\n"
  11365. "\r\n"
  11366. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11367. "0123456789\r\n"
  11368. "0\r\n" // End chunk
  11369. "\r\n";
  11370. std::string response;
  11371. bool result = send_request(1, chunked_request, &response);
  11372. if (!result) {
  11373. // If send_request fails, it might be because the server closed the
  11374. // connection due to payload limit enforcement, which is acceptable
  11375. SUCCEED()
  11376. << "Server rejected oversized chunked request (connection closed)";
  11377. } else {
  11378. // If we got a response, check if it's an error response or connection was
  11379. // closed early Short response length indicates connection was closed due to
  11380. // payload limit
  11381. if (response.length() <= 10) {
  11382. SUCCEED() << "Server closed connection for oversized chunked request";
  11383. } else {
  11384. // Check for error status codes
  11385. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11386. response.find("Payload Too Large") != std::string::npos ||
  11387. response.find("400") != std::string::npos);
  11388. }
  11389. }
  11390. }
  11391. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11392. // Test request without Content-Length header exceeding payload limit
  11393. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11394. "Host: " +
  11395. std::string(HOST) + ":" +
  11396. std::to_string(PORT) +
  11397. "\r\n"
  11398. "Connection: close\r\n"
  11399. "\r\n";
  11400. // Add payload exceeding the 8-byte limit
  11401. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11402. request_without_content_length += large_payload;
  11403. std::string response;
  11404. bool result = send_request(1, request_without_content_length, &response);
  11405. if (!result) {
  11406. // If send_request fails, server likely closed connection due to payload
  11407. // limit
  11408. SUCCEED() << "Server rejected oversized request without Content-Length "
  11409. "(connection closed)";
  11410. } else {
  11411. // Check if server responded with error or closed connection early
  11412. if (response.length() <= 10) {
  11413. SUCCEED() << "Server closed connection for oversized request without "
  11414. "Content-Length";
  11415. } else {
  11416. // Check for error status codes
  11417. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11418. response.find("Payload Too Large") != std::string::npos ||
  11419. response.find("400") != std::string::npos);
  11420. }
  11421. }
  11422. }
  11423. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11424. // Test request without Content-Length header within payload limit
  11425. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11426. "Host: " +
  11427. std::string(HOST) + ":" +
  11428. std::to_string(PORT) +
  11429. "\r\n"
  11430. "Connection: close\r\n"
  11431. "\r\n";
  11432. // Add payload within the 8-byte limit
  11433. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11434. request_without_content_length += small_payload;
  11435. std::string response;
  11436. bool result = send_request(1, request_without_content_length, &response);
  11437. // For requests without Content-Length, the server may have different behavior
  11438. // The key is that it should not reject due to payload limit for small
  11439. // payloads
  11440. if (result) {
  11441. // Check for any HTTP response (success or error, but not connection closed)
  11442. if (response.length() > 10) {
  11443. SUCCEED()
  11444. << "Server processed request without Content-Length within limit";
  11445. } else {
  11446. // Short response might indicate connection closed, which is acceptable
  11447. SUCCEED() << "Server closed connection for request without "
  11448. "Content-Length (acceptable behavior)";
  11449. }
  11450. } else {
  11451. // Connection failure might be due to protocol requirements
  11452. SUCCEED() << "Connection issue with request without Content-Length "
  11453. "(environment-specific)";
  11454. }
  11455. }
  11456. class LargePayloadMaxLengthTest : public ::testing::Test {
  11457. protected:
  11458. LargePayloadMaxLengthTest()
  11459. : cli_(HOST, PORT)
  11460. #ifdef CPPHTTPLIB_SSL_ENABLED
  11461. ,
  11462. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11463. #endif
  11464. {
  11465. #ifdef CPPHTTPLIB_SSL_ENABLED
  11466. cli_.enable_server_certificate_verification(false);
  11467. #endif
  11468. }
  11469. virtual void SetUp() {
  11470. // Set 10MB payload limit
  11471. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11472. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11473. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11474. res.set_content("Large payload test", "text/plain");
  11475. });
  11476. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11477. svr_.wait_until_ready();
  11478. }
  11479. virtual void TearDown() {
  11480. svr_.stop();
  11481. t_.join();
  11482. }
  11483. #ifdef CPPHTTPLIB_SSL_ENABLED
  11484. SSLClient cli_;
  11485. SSLServer svr_;
  11486. #else
  11487. Client cli_;
  11488. Server svr_;
  11489. #endif
  11490. thread t_;
  11491. };
  11492. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11493. // Test chunked encoding with payload within 10MB limit
  11494. std::string medium_payload(5 * 1024 * 1024,
  11495. 'A'); // 5MB payload, within 10MB limit
  11496. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11498. EXPECT_EQ(StatusCode::OK_200, res->status);
  11499. }
  11500. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11501. // Test chunked encoding with payload exceeding 10MB limit
  11502. std::string large_payload(12 * 1024 * 1024,
  11503. 'B'); // 12MB payload, exceeds 10MB limit
  11504. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11505. // Server may either return 413 or close the connection
  11506. if (res) {
  11507. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11508. } else {
  11509. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11510. }
  11511. }
  11512. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11513. // Test request without Content-Length header within 10MB limit
  11514. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11515. "Host: " +
  11516. std::string(HOST) + ":" +
  11517. std::to_string(PORT) +
  11518. "\r\n"
  11519. "Connection: close\r\n"
  11520. "\r\n";
  11521. // Add 1MB payload (within 10MB limit)
  11522. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11523. request_without_content_length += medium_payload;
  11524. std::string response;
  11525. bool result = send_request(5, request_without_content_length, &response);
  11526. if (result) {
  11527. // Should get a proper HTTP response for payloads within limit
  11528. if (response.length() > 10) {
  11529. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11530. "10MB limit";
  11531. } else {
  11532. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11533. "Content-Length)";
  11534. }
  11535. } else {
  11536. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11537. }
  11538. }
  11539. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11540. // Test request without Content-Length header exceeding 10MB limit
  11541. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11542. "Host: " +
  11543. std::string(HOST) + ":" +
  11544. std::to_string(PORT) +
  11545. "\r\n"
  11546. "Connection: close\r\n"
  11547. "\r\n";
  11548. // Add 12MB payload (exceeds 10MB limit)
  11549. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11550. request_without_content_length += large_payload;
  11551. std::string response;
  11552. bool result = send_request(10, request_without_content_length, &response);
  11553. if (!result) {
  11554. // Server should close connection due to payload limit
  11555. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11556. "(connection closed)";
  11557. } else {
  11558. // Check for error response
  11559. if (response.length() <= 10) {
  11560. SUCCEED()
  11561. << "Server closed connection for 12MB request exceeding 10MB limit";
  11562. } else {
  11563. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11564. response.find("Payload Too Large") != std::string::npos ||
  11565. response.find("400") != std::string::npos);
  11566. }
  11567. }
  11568. }
  11569. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11570. Server svr;
  11571. svr.Get("/", [](const Request &, Response &res) {
  11572. // Claims far more than it sends, then drops the connection.
  11573. res.set_content_provider(size_t(1) << 41, "text/plain",
  11574. [](size_t, size_t, DataSink &sink) {
  11575. sink.write("abc", 3);
  11576. return false;
  11577. });
  11578. });
  11579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11580. auto se = detail::scope_exit([&] {
  11581. svr.stop();
  11582. thread.join();
  11583. ASSERT_FALSE(svr.is_running());
  11584. });
  11585. svr.wait_until_ready();
  11586. Client cli(HOST, PORT);
  11587. cli.set_payload_max_length(0);
  11588. EXPECT_FALSE(cli.Get("/"));
  11589. }
  11590. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11591. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11592. // path.
  11593. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11594. Server svr;
  11595. const size_t LIMIT = 64 * 1024; // 64KB
  11596. svr.set_payload_max_length(LIMIT);
  11597. size_t total = 0;
  11598. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11599. const ContentReader &content_reader) {
  11600. content_reader([&](const char * /*data*/, size_t len) {
  11601. total += len;
  11602. return true;
  11603. });
  11604. res.status = 200;
  11605. res.set_content("stream_ok", "text/plain");
  11606. });
  11607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11608. auto se = detail::scope_exit([&] {
  11609. svr.stop();
  11610. thread.join();
  11611. ASSERT_FALSE(svr.is_running());
  11612. });
  11613. svr.wait_until_ready();
  11614. // Prepare 256KB raw data and gzip-compress it
  11615. std::string raw(256 * 1024, 'A');
  11616. std::string gz;
  11617. {
  11618. z_stream zs{};
  11619. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11620. Z_DEFAULT_STRATEGY);
  11621. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11622. zs.avail_in = static_cast<uInt>(raw.size());
  11623. char outbuf[4096];
  11624. int ret;
  11625. do {
  11626. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11627. zs.avail_out = sizeof(outbuf);
  11628. ret = deflate(&zs, Z_FINISH);
  11629. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11630. } while (ret != Z_STREAM_END);
  11631. deflateEnd(&zs);
  11632. }
  11633. Client cli(HOST, PORT);
  11634. cli.set_connection_timeout(std::chrono::seconds(5));
  11635. Headers headers = {{"Content-Encoding", "gzip"}};
  11636. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11637. "application/octet-stream");
  11638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11639. // Server must reject oversized decompressed payloads with 413.
  11640. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11641. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11642. EXPECT_LE(total, LIMIT);
  11643. }
  11644. #ifndef CPPHTTPLIB_SSL_ENABLED
  11645. // For a request with neither Content-Length nor Transfer-Encoding, the
  11646. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11647. // compressed wire bytes straight to the ContentReader without ever routing
  11648. // them through the decompressor, so payload_max_length_ only bounded the
  11649. // compressed size on the wire, not the decompressed size.
  11650. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11651. Server svr;
  11652. const size_t LIMIT = 64 * 1024; // 64KB
  11653. svr.set_payload_max_length(LIMIT);
  11654. size_t total = 0;
  11655. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11656. const ContentReader &content_reader) {
  11657. content_reader([&](const char * /*data*/, size_t len) {
  11658. total += len;
  11659. return true;
  11660. });
  11661. res.status = 200;
  11662. res.set_content("stream_ok", "text/plain");
  11663. });
  11664. auto port = svr.bind_to_any_port(HOST);
  11665. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11666. auto se = detail::scope_exit([&] {
  11667. svr.stop();
  11668. thread.join();
  11669. ASSERT_FALSE(svr.is_running());
  11670. });
  11671. svr.wait_until_ready();
  11672. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11673. // StreamingGzipDecompression test above.
  11674. std::string raw(256 * 1024, 'A');
  11675. std::string gz;
  11676. {
  11677. httplib::detail::gzip_compressor compressor;
  11678. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11679. [&](const char *chunk, size_t len) {
  11680. gz.append(chunk, len);
  11681. return true;
  11682. });
  11683. ASSERT_TRUE(result);
  11684. }
  11685. // Send the gzip body over raw TCP with neither Content-Length nor
  11686. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11687. // kicks in.
  11688. std::string req = "POST /stream HTTP/1.1\r\n"
  11689. "Host: " +
  11690. std::string(HOST) + ":" + std::to_string(port) +
  11691. "\r\n"
  11692. "Content-Encoding: gzip\r\n"
  11693. "Connection: close\r\n"
  11694. "\r\n" +
  11695. gz;
  11696. std::string response;
  11697. ASSERT_TRUE(send_request(5, req, &response, port));
  11698. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11699. EXPECT_LE(total, LIMIT);
  11700. }
  11701. #endif
  11702. #endif
  11703. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11704. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11705. // the payload must be passed through untouched instead of being rejected.
  11706. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11707. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11708. Server svr;
  11709. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11710. res.set_content(body, "image/jpeg");
  11711. res.set_header("Content-Encoding", "UTF-8");
  11712. });
  11713. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11714. res.set_content(body, "image/jpeg");
  11715. res.set_header("Content-Encoding", "identity");
  11716. });
  11717. svr.Post("/echo", [](const Request &req, Response &res) {
  11718. res.set_content(req.body, "image/jpeg");
  11719. });
  11720. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11721. auto se = detail::scope_exit([&] {
  11722. svr.stop();
  11723. t.join();
  11724. ASSERT_FALSE(svr.is_running());
  11725. });
  11726. svr.wait_until_ready();
  11727. Client cli(HOST, PORT);
  11728. {
  11729. auto res = cli.Get("/image");
  11730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11731. EXPECT_EQ(StatusCode::OK_200, res->status);
  11732. EXPECT_EQ(body, res->body);
  11733. }
  11734. {
  11735. auto res = cli.Get("/identity");
  11736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11737. EXPECT_EQ(StatusCode::OK_200, res->status);
  11738. EXPECT_EQ(body, res->body);
  11739. }
  11740. {
  11741. // The same applies to a request body reaching the server.
  11742. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11743. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11745. EXPECT_EQ(StatusCode::OK_200, res->status);
  11746. EXPECT_EQ(body, res->body);
  11747. }
  11748. }
  11749. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11750. // gzip-encoded response even when the build has no zlib support.
  11751. static const char GZIPPED_HELLO_WORLD[] = {
  11752. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11753. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11754. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11755. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11756. // A content coding is a whole token, not something the field value merely
  11757. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11758. // as "fibre" look like Brotli, and turned a multi-coding value like
  11759. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11760. // it was never meant to see.
  11761. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11762. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11763. Server svr;
  11764. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11765. res.set_content(body, "image/jpeg");
  11766. res.set_header("Content-Encoding", "fibre");
  11767. });
  11768. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11769. res.set_content(body, "image/jpeg");
  11770. res.set_header("Content-Encoding", "gzip, br");
  11771. });
  11772. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11773. res.set_content(body, "image/jpeg");
  11774. res.set_header("Content-Encoding", "x-zstd-ish");
  11775. });
  11776. auto port = svr.bind_to_any_port(HOST);
  11777. thread t = thread([&]() { svr.listen_after_bind(); });
  11778. auto se = detail::scope_exit([&] {
  11779. svr.stop();
  11780. t.join();
  11781. ASSERT_FALSE(svr.is_running());
  11782. });
  11783. svr.wait_until_ready();
  11784. Client cli(HOST, port);
  11785. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11786. auto res = cli.Get(path);
  11787. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11788. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11789. // Not a coding we recognize, so the payload comes back untouched
  11790. EXPECT_EQ(body, res->body) << path;
  11791. }
  11792. }
  11793. // A content coding cpp-httplib recognizes but was not built with must be
  11794. // reported as such. Handing the still-compressed payload back to the caller
  11795. // would silently corrupt it.
  11796. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11797. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11798. Server svr;
  11799. // "image/jpeg" keeps the server from applying a content coding of its own,
  11800. // so the hand-crafted Content-Encoding below survives.
  11801. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11802. res.set_content(gzipped, "image/jpeg");
  11803. res.set_header("Content-Encoding", "gzip");
  11804. });
  11805. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11806. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11807. res.set_content(gzipped, "image/jpeg");
  11808. res.set_header("Content-Encoding", "GZIP");
  11809. });
  11810. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11811. auto se = detail::scope_exit([&] {
  11812. svr.stop();
  11813. t.join();
  11814. ASSERT_FALSE(svr.is_running());
  11815. });
  11816. svr.wait_until_ready();
  11817. Client cli(HOST, PORT);
  11818. {
  11819. auto res = cli.Get("/gzipped");
  11820. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11822. EXPECT_EQ("Hello World!", res->body);
  11823. #else
  11824. ASSERT_FALSE(res);
  11825. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11826. #endif
  11827. }
  11828. {
  11829. // open_stream() must behave the same way.
  11830. auto handle = cli.open_stream("GET", "/gzipped");
  11831. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11832. ASSERT_TRUE(handle.is_valid());
  11833. std::string received;
  11834. char buf[256];
  11835. ssize_t n;
  11836. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11837. received.append(buf, static_cast<size_t>(n));
  11838. }
  11839. EXPECT_EQ("Hello World!", received);
  11840. #else
  11841. EXPECT_FALSE(handle.is_valid());
  11842. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11843. #endif
  11844. }
  11845. {
  11846. // A differently-cased coding must not be mistaken for an unknown one, or
  11847. // the body would be handed back still compressed.
  11848. auto res = cli.Get("/gzipped-uppercase");
  11849. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11851. EXPECT_EQ("Hello World!", res->body);
  11852. #else
  11853. ASSERT_FALSE(res);
  11854. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11855. #endif
  11856. }
  11857. }
  11858. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11859. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11860. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11861. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11862. // body a second time and appending a second Content-Encoding field line, so
  11863. // clients that decode one coding per listed value handed back raw gzip bytes.
  11864. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11865. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11866. Server svr;
  11867. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11868. // keeps the server from applying a coding of its own.
  11869. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11870. res.set_content(gzipped, "text/plain");
  11871. res.set_header("Content-Encoding", "gzip");
  11872. });
  11873. auto port = svr.bind_to_any_port(HOST);
  11874. thread t = thread([&]() { svr.listen_after_bind(); });
  11875. auto se = detail::scope_exit([&] {
  11876. svr.stop();
  11877. t.join();
  11878. ASSERT_FALSE(svr.is_running());
  11879. });
  11880. svr.wait_until_ready();
  11881. Client cli(HOST, port);
  11882. Headers headers = {{"Accept-Encoding", "gzip"}};
  11883. auto res = cli.Get("/pre-gzipped", headers);
  11884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11885. EXPECT_EQ(StatusCode::OK_200, res->status);
  11886. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11887. EXPECT_EQ("Hello World!", res->body);
  11888. }
  11889. // A chunked provider settles its coding where the headers are written and
  11890. // reuses it at write time. Both ends of that have to hold: a handler's own
  11891. // Content-Encoding suppresses the coding, and a response without one is still
  11892. // compressed as it always was.
  11893. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11894. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11895. const std::string plain = "Hello World! Hello World! Hello World!";
  11896. Server svr;
  11897. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11898. res.set_header("Content-Encoding", "gzip");
  11899. res.set_chunked_content_provider(
  11900. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11901. sink.write(gzipped.data(), gzipped.size());
  11902. sink.done();
  11903. return true;
  11904. });
  11905. });
  11906. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11907. res.set_chunked_content_provider(
  11908. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11909. sink.write(plain.data(), plain.size());
  11910. sink.done();
  11911. return true;
  11912. });
  11913. });
  11914. auto port = svr.bind_to_any_port(HOST);
  11915. thread t = thread([&]() { svr.listen_after_bind(); });
  11916. auto se = detail::scope_exit([&] {
  11917. svr.stop();
  11918. t.join();
  11919. ASSERT_FALSE(svr.is_running());
  11920. });
  11921. svr.wait_until_ready();
  11922. Client cli(HOST, port);
  11923. Headers headers = {{"Accept-Encoding", "gzip"}};
  11924. {
  11925. auto res = cli.Get("/pre-gzipped", headers);
  11926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11927. EXPECT_EQ(StatusCode::OK_200, res->status);
  11928. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11929. EXPECT_EQ("Hello World!", res->body);
  11930. }
  11931. {
  11932. auto res = cli.Get("/negotiated", headers);
  11933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11934. EXPECT_EQ(StatusCode::OK_200, res->status);
  11935. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11936. EXPECT_EQ(plain, res->body);
  11937. }
  11938. }
  11939. #endif
  11940. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11941. // the same message as the comma-joined one, so both have to be read the same
  11942. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11943. // single gzip coding, and a body the sender says was encoded twice was handed
  11944. // back after one pass, still compressed but presented as decoded.
  11945. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11946. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11947. Server svr;
  11948. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11949. res.set_content(body, "image/jpeg");
  11950. res.headers.emplace("Content-Encoding", "gzip");
  11951. res.headers.emplace("Content-Encoding", "gzip");
  11952. });
  11953. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11954. res.set_content(body, "image/jpeg");
  11955. res.set_header("Content-Encoding", "gzip, gzip");
  11956. });
  11957. auto port = svr.bind_to_any_port(HOST);
  11958. thread t = thread([&]() { svr.listen_after_bind(); });
  11959. auto se = detail::scope_exit([&] {
  11960. svr.stop();
  11961. t.join();
  11962. ASSERT_FALSE(svr.is_running());
  11963. });
  11964. svr.wait_until_ready();
  11965. Client cli(HOST, port);
  11966. // Two codings is not something cpp-httplib decodes, so both representations
  11967. // take the pass-through path rather than one of them being gunzipped once.
  11968. for (const char *path : {"/split", "/joined"}) {
  11969. auto res = cli.Get(path);
  11970. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11971. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11972. EXPECT_EQ(body, res->body) << path;
  11973. }
  11974. }
  11975. // Regression test for DoS vulnerability: a malicious server sending a response
  11976. // without Content-Length header must not cause unbounded memory consumption on
  11977. // the client side. The client should stop reading after a reasonable limit,
  11978. // similar to the server-side set_payload_max_length protection.
  11979. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11980. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11981. #ifndef _WIN32
  11982. signal(SIGPIPE, SIG_IGN);
  11983. #endif
  11984. auto server_thread = std::thread([] {
  11985. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11986. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11987. default_socket_options(srv);
  11988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11990. sockaddr_in addr{};
  11991. addr.sin_family = AF_INET;
  11992. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11994. int opt = 1;
  11995. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11996. #ifdef _WIN32
  11997. reinterpret_cast<const char *>(&opt),
  11998. #else
  11999. &opt,
  12000. #endif
  12001. sizeof(opt));
  12002. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12003. ::listen(srv, 1);
  12004. sockaddr_in cli_addr{};
  12005. socklen_t cli_len = sizeof(cli_addr);
  12006. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12007. if (cli != INVALID_SOCKET) {
  12008. char buf[4096];
  12009. ::recv(cli, buf, sizeof(buf), 0);
  12010. // Malicious response: no Content-Length, no chunked encoding
  12011. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12012. "Connection: close\r\n"
  12013. "\r\n";
  12014. ::send(cli,
  12015. #ifdef _WIN32
  12016. static_cast<const char *>(response_header.c_str()),
  12017. static_cast<int>(response_header.size()),
  12018. #else
  12019. response_header.c_str(), response_header.size(),
  12020. #endif
  12021. 0);
  12022. // Send 10MB of data
  12023. std::string chunk(64 * 1024, 'A');
  12024. size_t total_sent = 0;
  12025. while (total_sent < MALICIOUS_DATA_SIZE) {
  12026. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12027. auto sent = ::send(cli,
  12028. #ifdef _WIN32
  12029. static_cast<const char *>(chunk.c_str()),
  12030. static_cast<int>(to_send),
  12031. #else
  12032. chunk.c_str(), to_send,
  12033. #endif
  12034. 0);
  12035. if (sent <= 0) break;
  12036. total_sent += static_cast<size_t>(sent);
  12037. }
  12038. detail::close_socket(cli);
  12039. }
  12040. detail::close_socket(srv);
  12041. });
  12042. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12043. size_t total_read = 0;
  12044. {
  12045. Client cli("127.0.0.1", PORT + 2);
  12046. cli.set_read_timeout(5, 0);
  12047. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12048. auto stream = cli.open_stream("GET", "/malicious");
  12049. ASSERT_TRUE(stream.is_valid());
  12050. char buffer[64 * 1024];
  12051. ssize_t n;
  12052. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12053. total_read += static_cast<size_t>(n);
  12054. }
  12055. } // StreamHandle and Client destroyed here, closing the socket
  12056. server_thread.join();
  12057. // With set_payload_max_length, the client must stop reading before consuming
  12058. // all 10MB. The read loop should be cut off at or near the configured limit.
  12059. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12060. << "Client read " << total_read << " bytes, exceeding the configured "
  12061. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12062. }
  12063. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12064. // the entire response body without truncation.
  12065. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12066. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12067. #ifndef _WIN32
  12068. signal(SIGPIPE, SIG_IGN);
  12069. #endif
  12070. auto server_thread = std::thread([] {
  12071. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12072. default_socket_options(srv);
  12073. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12074. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12075. sockaddr_in addr{};
  12076. addr.sin_family = AF_INET;
  12077. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12078. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12079. int opt = 1;
  12080. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12081. #ifdef _WIN32
  12082. reinterpret_cast<const char *>(&opt),
  12083. #else
  12084. &opt,
  12085. #endif
  12086. sizeof(opt));
  12087. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12088. ::listen(srv, 1);
  12089. sockaddr_in cli_addr{};
  12090. socklen_t cli_len = sizeof(cli_addr);
  12091. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12092. if (cli != INVALID_SOCKET) {
  12093. char buf[4096];
  12094. ::recv(cli, buf, sizeof(buf), 0);
  12095. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12096. "Connection: close\r\n"
  12097. "\r\n";
  12098. ::send(cli,
  12099. #ifdef _WIN32
  12100. static_cast<const char *>(response_header.c_str()),
  12101. static_cast<int>(response_header.size()),
  12102. #else
  12103. response_header.c_str(), response_header.size(),
  12104. #endif
  12105. 0);
  12106. std::string chunk(64 * 1024, 'A');
  12107. size_t total_sent = 0;
  12108. while (total_sent < DATA_SIZE) {
  12109. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12110. auto sent = ::send(cli,
  12111. #ifdef _WIN32
  12112. static_cast<const char *>(chunk.c_str()),
  12113. static_cast<int>(to_send),
  12114. #else
  12115. chunk.c_str(), to_send,
  12116. #endif
  12117. 0);
  12118. if (sent <= 0) break;
  12119. total_sent += static_cast<size_t>(sent);
  12120. }
  12121. #ifdef _WIN32
  12122. ::shutdown(cli, SD_SEND);
  12123. #else
  12124. ::shutdown(cli, SHUT_WR);
  12125. #endif
  12126. // Drain until the client closes its end, ensuring all data is delivered
  12127. char drain[1024];
  12128. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12129. detail::close_socket(cli);
  12130. }
  12131. detail::close_socket(srv);
  12132. });
  12133. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12134. size_t total_read = 0;
  12135. {
  12136. Client cli("127.0.0.1", PORT + 2);
  12137. cli.set_read_timeout(5, 0);
  12138. cli.set_payload_max_length(0); // 0 means no limit
  12139. auto stream = cli.open_stream("GET", "/data");
  12140. ASSERT_TRUE(stream.is_valid());
  12141. char buffer[64 * 1024];
  12142. ssize_t n;
  12143. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12144. total_read += static_cast<size_t>(n);
  12145. }
  12146. }
  12147. server_thread.join();
  12148. EXPECT_EQ(total_read, DATA_SIZE)
  12149. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12150. << " bytes without truncation, but only read " << total_read << " bytes.";
  12151. }
  12152. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12153. // enormous Content-Length must not cause the client to pre-allocate a huge
  12154. // response body buffer. The reservation is capped at payload_max_length_, and
  12155. // the read itself fails when the body exceeds the limit.
  12156. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12157. #ifndef _WIN32
  12158. signal(SIGPIPE, SIG_IGN);
  12159. #endif
  12160. auto server_thread = std::thread([] {
  12161. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12162. default_socket_options(srv);
  12163. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12164. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12165. sockaddr_in addr{};
  12166. addr.sin_family = AF_INET;
  12167. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12168. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12169. int opt = 1;
  12170. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12171. #ifdef _WIN32
  12172. reinterpret_cast<const char *>(&opt),
  12173. #else
  12174. &opt,
  12175. #endif
  12176. sizeof(opt));
  12177. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12178. ::listen(srv, 1);
  12179. sockaddr_in cli_addr{};
  12180. socklen_t cli_len = sizeof(cli_addr);
  12181. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12182. if (cli != INVALID_SOCKET) {
  12183. char buf[4096];
  12184. ::recv(cli, buf, sizeof(buf), 0);
  12185. // Malicious response: claim a 20GB body but send only a tiny payload.
  12186. std::string response = "HTTP/1.1 200 OK\r\n"
  12187. "Content-Length: 20000000000\r\n"
  12188. "\r\n"
  12189. "abc";
  12190. ::send(cli,
  12191. #ifdef _WIN32
  12192. static_cast<const char *>(response.c_str()),
  12193. static_cast<int>(response.size()),
  12194. #else
  12195. response.c_str(), response.size(),
  12196. #endif
  12197. 0);
  12198. detail::close_socket(cli);
  12199. }
  12200. detail::close_socket(srv);
  12201. });
  12202. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12203. {
  12204. Client cli("127.0.0.1", PORT + 2);
  12205. cli.set_read_timeout(5, 0);
  12206. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12207. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12208. // (server claims more bytes than payload_max_length permits), but it must
  12209. // not exhaust memory before getting there.
  12210. auto res = cli.Get("/malicious");
  12211. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12212. }
  12213. server_thread.join();
  12214. }
  12215. // Verify that content_receiver bypasses the default payload_max_length,
  12216. // allowing streaming downloads larger than 100MB without requiring an explicit
  12217. // set_payload_max_length call.
  12218. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12219. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12220. #ifndef _WIN32
  12221. signal(SIGPIPE, SIG_IGN);
  12222. #endif
  12223. auto server_thread = std::thread([] {
  12224. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12225. default_socket_options(srv);
  12226. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12227. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12228. sockaddr_in addr{};
  12229. addr.sin_family = AF_INET;
  12230. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12231. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12232. int opt = 1;
  12233. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12234. #ifdef _WIN32
  12235. reinterpret_cast<const char *>(&opt),
  12236. #else
  12237. &opt,
  12238. #endif
  12239. sizeof(opt));
  12240. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12241. ::listen(srv, 1);
  12242. sockaddr_in cli_addr{};
  12243. socklen_t cli_len = sizeof(cli_addr);
  12244. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12245. if (cli != INVALID_SOCKET) {
  12246. char buf[4096];
  12247. ::recv(cli, buf, sizeof(buf), 0);
  12248. // Response with Content-Length larger than default 100MB limit
  12249. auto content_length = std::to_string(DATA_SIZE);
  12250. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12251. "Content-Length: " +
  12252. content_length +
  12253. "\r\n"
  12254. "Connection: close\r\n"
  12255. "\r\n";
  12256. ::send(cli,
  12257. #ifdef _WIN32
  12258. static_cast<const char *>(response_header.c_str()),
  12259. static_cast<int>(response_header.size()),
  12260. #else
  12261. response_header.c_str(), response_header.size(),
  12262. #endif
  12263. 0);
  12264. std::string chunk(64 * 1024, 'A');
  12265. size_t total_sent = 0;
  12266. while (total_sent < DATA_SIZE) {
  12267. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12268. auto sent = ::send(cli,
  12269. #ifdef _WIN32
  12270. static_cast<const char *>(chunk.c_str()),
  12271. static_cast<int>(to_send),
  12272. #else
  12273. chunk.c_str(), to_send,
  12274. #endif
  12275. 0);
  12276. if (sent <= 0) break;
  12277. total_sent += static_cast<size_t>(sent);
  12278. }
  12279. detail::close_socket(cli);
  12280. }
  12281. detail::close_socket(srv);
  12282. });
  12283. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12284. size_t total_received = 0;
  12285. {
  12286. Client cli("127.0.0.1", PORT + 2);
  12287. cli.set_read_timeout(10, 0);
  12288. // Do NOT call set_payload_max_length — use the default 100MB limit
  12289. auto res =
  12290. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12291. total_received += data_length;
  12292. return true;
  12293. });
  12294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12295. EXPECT_EQ(StatusCode::OK_200, res->status);
  12296. }
  12297. server_thread.join();
  12298. EXPECT_EQ(total_received, DATA_SIZE)
  12299. << "With content_receiver, the client should read all " << DATA_SIZE
  12300. << " bytes despite the default 100MB payload_max_length, but only read "
  12301. << total_received << " bytes.";
  12302. }
  12303. // Verify that an explicit set_payload_max_length smaller than the response is
  12304. // enforced even when a content_receiver is used.
  12305. TEST(ClientVulnerabilityTest,
  12306. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12307. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12308. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12309. #ifndef _WIN32
  12310. signal(SIGPIPE, SIG_IGN);
  12311. #endif
  12312. auto server_thread = std::thread([] {
  12313. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12314. default_socket_options(srv);
  12315. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12316. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12317. sockaddr_in addr{};
  12318. addr.sin_family = AF_INET;
  12319. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12320. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12321. int opt = 1;
  12322. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12323. #ifdef _WIN32
  12324. reinterpret_cast<const char *>(&opt),
  12325. #else
  12326. &opt,
  12327. #endif
  12328. sizeof(opt));
  12329. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12330. ::listen(srv, 1);
  12331. sockaddr_in cli_addr{};
  12332. socklen_t cli_len = sizeof(cli_addr);
  12333. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12334. if (cli != INVALID_SOCKET) {
  12335. char buf[4096];
  12336. ::recv(cli, buf, sizeof(buf), 0);
  12337. auto content_length = std::to_string(DATA_SIZE);
  12338. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12339. "Content-Length: " +
  12340. content_length +
  12341. "\r\n"
  12342. "Connection: close\r\n"
  12343. "\r\n";
  12344. ::send(cli,
  12345. #ifdef _WIN32
  12346. static_cast<const char *>(response_header.c_str()),
  12347. static_cast<int>(response_header.size()),
  12348. #else
  12349. response_header.c_str(), response_header.size(),
  12350. #endif
  12351. 0);
  12352. std::string chunk(64 * 1024, 'A');
  12353. size_t total_sent = 0;
  12354. while (total_sent < DATA_SIZE) {
  12355. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12356. auto sent = ::send(cli,
  12357. #ifdef _WIN32
  12358. static_cast<const char *>(chunk.c_str()),
  12359. static_cast<int>(to_send),
  12360. #else
  12361. chunk.c_str(), to_send,
  12362. #endif
  12363. 0);
  12364. if (sent <= 0) break;
  12365. total_sent += static_cast<size_t>(sent);
  12366. }
  12367. detail::close_socket(cli);
  12368. }
  12369. detail::close_socket(srv);
  12370. });
  12371. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12372. size_t total_received = 0;
  12373. {
  12374. Client cli("127.0.0.1", PORT + 2);
  12375. cli.set_read_timeout(10, 0);
  12376. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12377. auto res =
  12378. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12379. total_received += data_length;
  12380. return true;
  12381. });
  12382. // Should fail because 200MB exceeds the explicit 150MB limit
  12383. EXPECT_FALSE(res);
  12384. }
  12385. server_thread.join();
  12386. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12387. << "Client with content_receiver should respect the explicit "
  12388. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12389. << total_received << " bytes.";
  12390. }
  12391. // Verify that an explicit set_payload_max_length larger than the response
  12392. // allows the content_receiver to read all data successfully.
  12393. TEST(ClientVulnerabilityTest,
  12394. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12395. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12396. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12397. #ifndef _WIN32
  12398. signal(SIGPIPE, SIG_IGN);
  12399. #endif
  12400. auto server_thread = std::thread([] {
  12401. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12402. default_socket_options(srv);
  12403. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12404. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12405. sockaddr_in addr{};
  12406. addr.sin_family = AF_INET;
  12407. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12408. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12409. int opt = 1;
  12410. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12411. #ifdef _WIN32
  12412. reinterpret_cast<const char *>(&opt),
  12413. #else
  12414. &opt,
  12415. #endif
  12416. sizeof(opt));
  12417. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12418. ::listen(srv, 1);
  12419. sockaddr_in cli_addr{};
  12420. socklen_t cli_len = sizeof(cli_addr);
  12421. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12422. if (cli != INVALID_SOCKET) {
  12423. char buf[4096];
  12424. ::recv(cli, buf, sizeof(buf), 0);
  12425. auto content_length = std::to_string(DATA_SIZE);
  12426. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12427. "Content-Length: " +
  12428. content_length +
  12429. "\r\n"
  12430. "Connection: close\r\n"
  12431. "\r\n";
  12432. ::send(cli,
  12433. #ifdef _WIN32
  12434. static_cast<const char *>(response_header.c_str()),
  12435. static_cast<int>(response_header.size()),
  12436. #else
  12437. response_header.c_str(), response_header.size(),
  12438. #endif
  12439. 0);
  12440. std::string chunk(64 * 1024, 'A');
  12441. size_t total_sent = 0;
  12442. while (total_sent < DATA_SIZE) {
  12443. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12444. auto sent = ::send(cli,
  12445. #ifdef _WIN32
  12446. static_cast<const char *>(chunk.c_str()),
  12447. static_cast<int>(to_send),
  12448. #else
  12449. chunk.c_str(), to_send,
  12450. #endif
  12451. 0);
  12452. if (sent <= 0) break;
  12453. total_sent += static_cast<size_t>(sent);
  12454. }
  12455. #ifdef _WIN32
  12456. ::shutdown(cli, SD_SEND);
  12457. #else
  12458. ::shutdown(cli, SHUT_WR);
  12459. #endif
  12460. char drain[1024];
  12461. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12462. detail::close_socket(cli);
  12463. }
  12464. detail::close_socket(srv);
  12465. });
  12466. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12467. size_t total_received = 0;
  12468. {
  12469. Client cli("127.0.0.1", PORT + 2);
  12470. cli.set_read_timeout(10, 0);
  12471. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12472. auto res =
  12473. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12474. total_received += data_length;
  12475. return true;
  12476. });
  12477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12478. EXPECT_EQ(StatusCode::OK_200, res->status);
  12479. }
  12480. server_thread.join();
  12481. EXPECT_EQ(total_received, DATA_SIZE)
  12482. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12483. << " bytes (larger than " << DATA_SIZE
  12484. << " bytes response), content_receiver should read all data, but only "
  12485. "read "
  12486. << total_received << " bytes.";
  12487. }
  12488. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12489. // Regression test for "zip bomb" attack on the client side: a malicious server
  12490. // sends a small gzip-compressed response that decompresses to a huge payload.
  12491. // The client must enforce payload_max_length on the decompressed size.
  12492. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12493. constexpr size_t DECOMPRESSED_SIZE =
  12494. 10 * 1024 * 1024; // 10MB after decompression
  12495. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12496. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12497. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12498. std::string compressed;
  12499. {
  12500. httplib::detail::gzip_compressor compressor;
  12501. bool ok =
  12502. compressor.compress(uncompressed.data(), uncompressed.size(),
  12503. /*last=*/true, [&](const char *buf, size_t len) {
  12504. compressed.append(buf, len);
  12505. return true;
  12506. });
  12507. ASSERT_TRUE(ok);
  12508. }
  12509. // Sanity: compressed data should be much smaller than the decompressed size
  12510. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12511. #ifndef _WIN32
  12512. signal(SIGPIPE, SIG_IGN);
  12513. #endif
  12514. // Set up the listening socket in the main thread so the server is guaranteed
  12515. // to be ready before the client connects (eliminates race condition).
  12516. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12517. default_socket_options(srv);
  12518. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12519. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12520. sockaddr_in addr{};
  12521. addr.sin_family = AF_INET;
  12522. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12523. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12524. int opt = 1;
  12525. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12526. #ifdef _WIN32
  12527. reinterpret_cast<const char *>(&opt),
  12528. #else
  12529. &opt,
  12530. #endif
  12531. sizeof(opt));
  12532. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12533. ASSERT_EQ(0, ::listen(srv, 1));
  12534. auto server_thread = std::thread([&compressed, srv] {
  12535. sockaddr_in cli_addr{};
  12536. socklen_t cli_len = sizeof(cli_addr);
  12537. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12538. if (cli != INVALID_SOCKET) {
  12539. // Read the full HTTP request (until \r\n\r\n)
  12540. char buf[4096];
  12541. size_t total = 0;
  12542. while (total < sizeof(buf)) {
  12543. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12544. if (n <= 0) break;
  12545. total += static_cast<size_t>(n);
  12546. // Check for end of headers
  12547. if (total >= 4) {
  12548. std::string req(buf, total);
  12549. if (req.find("\r\n\r\n") != std::string::npos) break;
  12550. }
  12551. }
  12552. // Malicious response: gzip-compressed body, no Content-Length
  12553. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12554. "Content-Encoding: gzip\r\n"
  12555. "Connection: close\r\n"
  12556. "\r\n";
  12557. ::send(cli,
  12558. #ifdef _WIN32
  12559. static_cast<const char *>(response_header.c_str()),
  12560. static_cast<int>(response_header.size()),
  12561. #else
  12562. response_header.c_str(), response_header.size(),
  12563. #endif
  12564. 0);
  12565. // Send the compressed payload (small on the wire, huge when decompressed)
  12566. size_t total_sent = 0;
  12567. while (total_sent < compressed.size()) {
  12568. auto to_send = std::min(compressed.size() - total_sent,
  12569. static_cast<size_t>(64 * 1024));
  12570. auto sent =
  12571. ::send(cli,
  12572. #ifdef _WIN32
  12573. static_cast<const char *>(compressed.c_str() + total_sent),
  12574. static_cast<int>(to_send),
  12575. #else
  12576. compressed.c_str() + total_sent, to_send,
  12577. #endif
  12578. 0);
  12579. if (sent <= 0) break;
  12580. total_sent += static_cast<size_t>(sent);
  12581. }
  12582. detail::close_socket(cli);
  12583. }
  12584. });
  12585. auto se = detail::scope_exit([&] {
  12586. detail::close_socket(srv);
  12587. server_thread.join();
  12588. });
  12589. size_t total_decompressed = 0;
  12590. {
  12591. Client cli("127.0.0.1", PORT + 3);
  12592. cli.set_read_timeout(5, 0);
  12593. cli.set_decompress(true);
  12594. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12595. auto stream = cli.open_stream("GET", "/zipbomb");
  12596. ASSERT_TRUE(stream.is_valid());
  12597. char buffer[64 * 1024];
  12598. ssize_t n;
  12599. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12600. total_decompressed += static_cast<size_t>(n);
  12601. }
  12602. }
  12603. // The decompressed size must be capped by payload_max_length. Without
  12604. // protection, the client would decompress the full 10MB from a tiny
  12605. // compressed payload, enabling a zip bomb DoS attack.
  12606. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12607. << "Client decompressed " << total_decompressed
  12608. << " bytes from a gzip response. The decompressed size should be "
  12609. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12610. }
  12611. #endif
  12612. TEST(HostAndPortPropertiesTest, NoSSL) {
  12613. httplib::Client cli("www.google.com", 1234);
  12614. ASSERT_EQ("www.google.com", cli.host());
  12615. ASSERT_EQ(1234, cli.port());
  12616. }
  12617. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12618. httplib::Client cli("www.google.com:1234");
  12619. ASSERT_EQ("www.google.com", cli.host());
  12620. ASSERT_EQ(1234, cli.port());
  12621. }
  12622. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12623. // Port number that overflows int — should not crash, client becomes invalid
  12624. httplib::Client cli("http://www.google.com:99999999999999999999");
  12625. ASSERT_FALSE(cli.is_valid());
  12626. }
  12627. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12628. // Port 99999 exceeds valid range (1-65535) — should not crash
  12629. httplib::Client cli("http://www.google.com:99999");
  12630. ASSERT_FALSE(cli.is_valid());
  12631. auto res = cli.Get("/");
  12632. EXPECT_FALSE(res);
  12633. EXPECT_EQ(Error::Connection, res.error());
  12634. }
  12635. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12636. httplib::Client cli("http://user:pass@localhost:1234");
  12637. ASSERT_FALSE(cli.is_valid());
  12638. EXPECT_FALSE(cli.Get("/"));
  12639. }
  12640. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12641. httplib::Client cli("http://www.google.com:80abc");
  12642. ASSERT_FALSE(cli.is_valid());
  12643. }
  12644. #ifdef CPPHTTPLIB_SSL_ENABLED
  12645. TEST(HostAndPortPropertiesTest, SSL) {
  12646. httplib::SSLClient cli("www.google.com");
  12647. ASSERT_EQ("www.google.com", cli.host());
  12648. ASSERT_EQ(443, cli.port());
  12649. }
  12650. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12651. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12652. std::string cert;
  12653. read_file(CA_CERT_FILE, cert);
  12654. httplib::SSLClient httplib_client("www.google.com");
  12655. // Load CA store first time
  12656. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12657. // Load CA store second time (update)
  12658. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12659. // Verify client is still valid and can make connections
  12660. httplib_client.enable_server_certificate_verification(true);
  12661. auto res = httplib_client.Get("/");
  12662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12663. // Google may return 200 or 301 depending on various factors
  12664. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12665. res->status == StatusCode::MovedPermanently_301);
  12666. }
  12667. TEST(SSLClientTest, ServerNameIndication_Online) {
  12668. auto host = "httpbingo.org";
  12669. auto path = std::string{"/get"};
  12670. SSLClient cli(host, 443);
  12671. auto res = cli.Get(path);
  12672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12673. ASSERT_EQ(StatusCode::OK_200, res->status);
  12674. }
  12675. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12676. // Use a site that will cause SSL verification failure due to self-signed cert
  12677. SSLClient cli("self-signed.badssl.com", 443);
  12678. cli.enable_server_certificate_verification(true);
  12679. auto res = cli.Get("/");
  12680. ASSERT_TRUE(!res);
  12681. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12682. // Verify backend error is captured for SSLServerVerification
  12683. // This occurs when certificate verification fails
  12684. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12685. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12686. EXPECT_NE(0UL, res.ssl_backend_error());
  12687. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12688. // For OpenSSL, ssl_error is 0 for verification errors
  12689. EXPECT_EQ(0, res.ssl_error());
  12690. #if !defined(_WIN32) || \
  12691. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12692. // On non-Windows or when Windows Schannel is disabled, the error comes
  12693. // from OpenSSL's verification
  12694. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12695. res.ssl_backend_error());
  12696. #endif
  12697. #endif
  12698. }
  12699. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12700. // Use a site where hostname doesn't match the certificate
  12701. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12702. SSLClient cli("wrong.host.badssl.com", 443);
  12703. cli.enable_server_certificate_verification(true);
  12704. cli.enable_server_hostname_verification(true);
  12705. auto res = cli.Get("/");
  12706. ASSERT_TRUE(!res);
  12707. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12708. // Verify backend error is captured for hostname verification failure
  12709. EXPECT_NE(0UL, res.ssl_backend_error());
  12710. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12711. // For OpenSSL, ssl_error is 0 for verification errors
  12712. EXPECT_EQ(0, res.ssl_error());
  12713. #if !defined(_WIN32) || \
  12714. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12715. // On non-Windows or when Windows Schannel is disabled, the error comes
  12716. // from OpenSSL's hostname verification
  12717. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12718. res.ssl_backend_error());
  12719. #endif
  12720. #endif
  12721. }
  12722. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12723. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12724. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12725. SSLClient cli("www.google.com", 443);
  12726. cli.enable_server_certificate_verification(true);
  12727. auto res = cli.Get("/");
  12728. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12729. }
  12730. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12731. SSLClient cli("www.google.com", 443);
  12732. cli.enable_server_certificate_verification(true);
  12733. cli.enable_windows_certificate_verification(false);
  12734. auto res = cli.Get("/");
  12735. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12736. }
  12737. // The server sends an intermediate cross-signed by a root Windows trusts,
  12738. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12739. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12740. SSLClient cli("accounts.spotify.com", 443);
  12741. auto res = cli.Get("/");
  12742. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12743. << " ssl_backend_error=" << res.ssl_backend_error();
  12744. }
  12745. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12746. // policy status, which no backend reports for a self-signed certificate.
  12747. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12748. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12749. ASSERT_TRUE(svr.is_valid());
  12750. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12751. auto se = detail::scope_exit([&] {
  12752. svr.stop();
  12753. t.join();
  12754. ASSERT_FALSE(svr.is_running());
  12755. });
  12756. svr.wait_until_ready();
  12757. SSLClient cli("127.0.0.1", PORT);
  12758. cli.set_connection_timeout(30);
  12759. auto res = cli.Get("/");
  12760. ASSERT_FALSE(res);
  12761. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12762. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12763. }
  12764. #endif
  12765. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12766. Client cli("https://google.com");
  12767. auto res = cli.Get("/");
  12768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12770. }
  12771. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12772. SSLClient cli("google.com");
  12773. cli.set_ca_cert_path(CA_CERT_FILE);
  12774. auto res = cli.Get("/");
  12775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12776. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12777. }
  12778. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12779. SSLClient cli("google.com");
  12780. cli.enable_server_certificate_verification(true);
  12781. cli.set_ca_cert_path("hello");
  12782. auto res = cli.Get("/");
  12783. ASSERT_TRUE(!res);
  12784. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12785. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12786. // should be set
  12787. EXPECT_EQ(0, res.ssl_error());
  12788. // Verify backend error is captured for SSLLoadingCerts
  12789. // This error occurs when loading CA certificates fails
  12790. EXPECT_NE(0UL, res.ssl_backend_error());
  12791. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12792. // OpenSSL specific error codes:
  12793. // > openssl errstr 0x80000002
  12794. // error:80000002:system library::No such file or directory
  12795. // > openssl errstr 0xA000126
  12796. // error:0A000126:SSL routines::unexpected eof while reading
  12797. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12798. res.ssl_backend_error() == 0xA000126);
  12799. #endif
  12800. }
  12801. TEST(SSLClientTest, ServerCertificateVerification4) {
  12802. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12803. ASSERT_TRUE(svr.is_valid());
  12804. svr.Get("/test", [&](const Request &, Response &res) {
  12805. res.set_content("test", "text/plain");
  12806. svr.stop();
  12807. ASSERT_TRUE(true);
  12808. });
  12809. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12810. auto se = detail::scope_exit([&] {
  12811. t.join();
  12812. ASSERT_FALSE(svr.is_running());
  12813. });
  12814. svr.wait_until_ready();
  12815. SSLClient cli("127.0.0.1", PORT);
  12816. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12817. cli.enable_server_certificate_verification(true);
  12818. cli.set_connection_timeout(30);
  12819. auto res = cli.Get("/test");
  12820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12821. ASSERT_EQ(StatusCode::OK_200, res->status);
  12822. }
  12823. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12824. std::string cert;
  12825. read_file(CA_CERT_FILE, cert);
  12826. SSLClient cli("google.com");
  12827. cli.load_ca_cert_store(cert.data(), cert.size());
  12828. const auto res = cli.Get("/");
  12829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12830. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12831. }
  12832. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12833. // clang-format off
  12834. static constexpr char cert[] =
  12835. "GlobalSign Root CA\n"
  12836. "==================\n"
  12837. "-----BEGIN CERTIFICATE-----\n"
  12838. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12839. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12840. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12841. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12842. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12843. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12844. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12845. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12846. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12847. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12848. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12849. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12850. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12851. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12852. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12853. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12854. "-----END CERTIFICATE-----\n";
  12855. // clang-format on
  12856. SSLClient cli("google.com");
  12857. cli.load_ca_cert_store(cert, sizeof(cert));
  12858. const auto res = cli.Get("/");
  12859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12860. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12861. }
  12862. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12863. SSLClient cli("www.youtube.com");
  12864. cli.set_ca_cert_path(CA_CERT_FILE);
  12865. cli.enable_server_certificate_verification(true);
  12866. cli.set_follow_location(true);
  12867. auto res = cli.Get("/");
  12868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12869. ASSERT_EQ(StatusCode::OK_200, res->status);
  12870. }
  12871. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12872. SSLClient cli("wWw.YouTube.Com");
  12873. cli.set_ca_cert_path(CA_CERT_FILE);
  12874. cli.enable_server_certificate_verification(true);
  12875. cli.enable_server_hostname_verification(true);
  12876. cli.set_follow_location(true);
  12877. auto res = cli.Get("/");
  12878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12879. ASSERT_EQ(StatusCode::OK_200, res->status);
  12880. }
  12881. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12882. SSLClient cli("gOoGlE.COm");
  12883. cli.enable_server_certificate_verification(true);
  12884. cli.enable_server_hostname_verification(true);
  12885. cli.set_follow_location(true);
  12886. auto res = cli.Get("/");
  12887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12888. ASSERT_EQ(StatusCode::OK_200, res->status);
  12889. }
  12890. TEST(SSLClientTest, Issue2004_Online) {
  12891. Client client("https://google.com");
  12892. client.set_follow_location(true);
  12893. auto res = client.Get("/");
  12894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12895. ASSERT_EQ(StatusCode::OK_200, res->status);
  12896. auto body = res->body;
  12897. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12898. }
  12899. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12900. // Create SSLClient with invalid cert/key to make is_valid() return false
  12901. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12902. "nonexistent_key.pem");
  12903. // is_valid() should be false due to cert loading failure
  12904. ASSERT_FALSE(cli.is_valid());
  12905. auto res = cli.Get("/");
  12906. ASSERT_FALSE(res);
  12907. EXPECT_EQ(Error::SSLConnection, res.error());
  12908. }
  12909. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12910. // Test for Issue #2251: SSL error not properly reported when client cert
  12911. // and key paths are swapped or mismatched
  12912. // This simulates the scenario where user accidentally swaps the cert and key
  12913. // files
  12914. // Using client cert file as private key and vice versa (completely wrong)
  12915. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12916. // Should fail validation due to cert/key mismatch
  12917. ASSERT_FALSE(cli.is_valid());
  12918. // Attempt to make a request should fail with proper error
  12919. auto res = cli.Get("/");
  12920. ASSERT_FALSE(res);
  12921. EXPECT_EQ(Error::SSLConnection, res.error());
  12922. // SSL error should be recorded in the Result object (this is the key fix for
  12923. // Issue #2251)
  12924. auto backend_error = res.ssl_backend_error();
  12925. EXPECT_NE(0u, backend_error);
  12926. }
  12927. // Tests cert/key mismatch detection at the TLS context level
  12928. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12929. // Test that using mismatched cert/key causes connection failure.
  12930. // We verify this at the SSLClient level rather than through internal
  12931. // TLS API functions.
  12932. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12933. cli.enable_server_certificate_verification(false);
  12934. cli.set_connection_timeout(2);
  12935. // The mismatch should cause a connection or handshake error
  12936. auto res = cli.Get("/test");
  12937. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12938. // Either way, the request should fail
  12939. EXPECT_FALSE(res);
  12940. }
  12941. #endif
  12942. #if 0
  12943. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12944. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12945. ASSERT_TRUE(cli != nullptr);
  12946. cli->set_address_family(AF_INET6);
  12947. cli->set_interface("en0");
  12948. auto res = cli->Get("/get");
  12949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12950. ASSERT_EQ(StatusCode::OK_200, res->status);
  12951. }
  12952. #endif
  12953. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12954. #ifdef CPPHTTPLIB_SSL_ENABLED
  12955. void ClientCertPresent(
  12956. const std::string &client_cert_file,
  12957. const std::string &client_private_key_file,
  12958. const std::string &client_encrypted_private_key_pass = std::string()) {
  12959. using namespace httplib::tls;
  12960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12961. CLIENT_CA_CERT_DIR);
  12962. ASSERT_TRUE(svr.is_valid());
  12963. svr.Get("/test", [&](const Request &req, Response &res) {
  12964. res.set_content("test", "text/plain");
  12965. auto cert = req.peer_cert();
  12966. ASSERT_TRUE(static_cast<bool>(cert));
  12967. std::string common_name = cert.subject_cn();
  12968. EXPECT_EQ("Common Name", common_name);
  12969. });
  12970. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12971. auto se = detail::scope_exit([&] {
  12972. svr.stop();
  12973. t.join();
  12974. ASSERT_FALSE(svr.is_running());
  12975. });
  12976. svr.wait_until_ready();
  12977. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12978. client_encrypted_private_key_pass);
  12979. cli.enable_server_certificate_verification(false);
  12980. cli.set_connection_timeout(30);
  12981. auto res = cli.Get("/test");
  12982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12983. ASSERT_EQ(StatusCode::OK_200, res->status);
  12984. }
  12985. TEST(SSLClientServerTest, ClientCertPresent) {
  12986. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12987. }
  12988. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12989. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12990. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12991. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12992. }
  12993. // PEM memory-based constructor tests (works with all TLS backends)
  12994. void PemMemoryClientCertPresent(
  12995. const std::string &client_cert_file,
  12996. const std::string &client_private_key_file,
  12997. const std::string &client_encrypted_private_key_pass = std::string()) {
  12998. // Read PEM files into memory
  12999. std::string server_cert_pem, server_key_pem;
  13000. std::string client_ca_pem;
  13001. std::string client_cert_pem, client_key_pem;
  13002. read_file(SERVER_CERT_FILE, server_cert_pem);
  13003. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13004. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13005. read_file(client_cert_file, client_cert_pem);
  13006. read_file(client_private_key_file, client_key_pem);
  13007. // Create server with PEM memory
  13008. SSLServer::PemMemory server_pem = {
  13009. server_cert_pem.c_str(),
  13010. server_cert_pem.size(),
  13011. server_key_pem.c_str(),
  13012. server_key_pem.size(),
  13013. client_ca_pem.c_str(),
  13014. client_ca_pem.size(),
  13015. nullptr // no password for server key
  13016. };
  13017. SSLServer svr(server_pem);
  13018. ASSERT_TRUE(svr.is_valid());
  13019. svr.Get("/test", [&](const Request &, Response &res) {
  13020. res.set_content("test", "text/plain");
  13021. });
  13022. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13023. auto se = detail::scope_exit([&] {
  13024. svr.stop();
  13025. t.join();
  13026. ASSERT_FALSE(svr.is_running());
  13027. });
  13028. svr.wait_until_ready();
  13029. // Create client with PEM memory
  13030. const char *password = client_encrypted_private_key_pass.empty()
  13031. ? nullptr
  13032. : client_encrypted_private_key_pass.c_str();
  13033. SSLClient::PemMemory client_pem = {
  13034. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13035. client_key_pem.size(), password};
  13036. SSLClient cli(HOST, PORT, client_pem);
  13037. cli.enable_server_certificate_verification(false);
  13038. cli.set_connection_timeout(30);
  13039. auto res = cli.Get("/test");
  13040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13041. ASSERT_EQ(StatusCode::OK_200, res->status);
  13042. }
  13043. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13044. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13045. }
  13046. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13047. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13048. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13049. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13050. }
  13051. TEST(SSLClientServerTest, ClientCertMissing) {
  13052. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13053. CLIENT_CA_CERT_DIR);
  13054. ASSERT_TRUE(svr.is_valid());
  13055. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13056. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13057. auto se = detail::scope_exit([&] {
  13058. svr.stop();
  13059. t.join();
  13060. ASSERT_FALSE(svr.is_running());
  13061. });
  13062. svr.wait_until_ready();
  13063. SSLClient cli(HOST, PORT);
  13064. cli.set_connection_timeout(30);
  13065. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13066. // the chain check on Windows, so the result does not depend on the order.
  13067. cli.enable_server_hostname_verification(false);
  13068. auto res = cli.Get("/test");
  13069. ASSERT_TRUE(!res);
  13070. // When client cert is missing and server requires it, connection fails
  13071. // Error type depends on backend implementation
  13072. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13073. res.error() == Error::SSLConnection);
  13074. // Verify backend error is captured
  13075. // Note: This test may have different error codes depending on the exact
  13076. // verification failure
  13077. EXPECT_NE(0UL, res.ssl_backend_error());
  13078. }
  13079. TEST(SSLClientServerTest, TrustDirOptional) {
  13080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13081. ASSERT_TRUE(svr.is_valid());
  13082. svr.Get("/test", [&](const Request &, Response &res) {
  13083. res.set_content("test", "text/plain");
  13084. });
  13085. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13086. auto se = detail::scope_exit([&] {
  13087. svr.stop();
  13088. t.join();
  13089. ASSERT_FALSE(svr.is_running());
  13090. });
  13091. svr.wait_until_ready();
  13092. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13093. cli.enable_server_certificate_verification(false);
  13094. cli.set_connection_timeout(30);
  13095. auto res = cli.Get("/test");
  13096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13097. ASSERT_EQ(StatusCode::OK_200, res->status);
  13098. }
  13099. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13100. class NoListenSSLServer : public SSLServer {
  13101. public:
  13102. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13103. const char *client_ca_cert_file_path,
  13104. const char *client_ca_cert_dir_path = nullptr)
  13105. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13106. client_ca_cert_dir_path),
  13107. stop_(false) {}
  13108. std::atomic_bool stop_;
  13109. private:
  13110. bool process_and_close_socket(socket_t /*sock*/) override {
  13111. // Don't create SSL context
  13112. while (!stop_.load()) {
  13113. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13114. }
  13115. return true;
  13116. }
  13117. };
  13118. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13119. CLIENT_CA_CERT_FILE);
  13120. ASSERT_TRUE(svr.is_valid());
  13121. svr.Get("/test", [&](const Request &, Response &res) {
  13122. res.set_content("test", "text/plain");
  13123. });
  13124. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13125. auto se = detail::scope_exit([&] {
  13126. svr.stop_ = true;
  13127. svr.stop();
  13128. t.join();
  13129. ASSERT_FALSE(svr.is_running());
  13130. });
  13131. svr.wait_until_ready();
  13132. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13133. cli.enable_server_certificate_verification(false);
  13134. cli.set_connection_timeout(1);
  13135. auto res = cli.Get("/test");
  13136. ASSERT_TRUE(!res);
  13137. EXPECT_EQ(Error::SSLConnection, res.error());
  13138. // Timeout results in WantRead error code (maps to backend-specific value)
  13139. EXPECT_NE(0, res.ssl_error());
  13140. }
  13141. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13142. // Test SSLServer with client certificate verification using the standard
  13143. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13145. CLIENT_CA_CERT_DIR);
  13146. ASSERT_TRUE(svr.is_valid());
  13147. svr.Get("/test", [&](const Request &req, Response &res) {
  13148. res.set_content("test", "text/plain");
  13149. auto cert = req.peer_cert();
  13150. ASSERT_TRUE(static_cast<bool>(cert));
  13151. auto common_name = cert.subject_cn();
  13152. EXPECT_EQ("Common Name", common_name);
  13153. });
  13154. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13155. auto se = detail::scope_exit([&] {
  13156. svr.stop();
  13157. t.join();
  13158. ASSERT_FALSE(svr.is_running());
  13159. });
  13160. svr.wait_until_ready();
  13161. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13162. cli.enable_server_certificate_verification(false);
  13163. cli.set_connection_timeout(30);
  13164. auto res = cli.Get("/test");
  13165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13166. ASSERT_EQ(StatusCode::OK_200, res->status);
  13167. }
  13168. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13169. // Verifies that wildcard matching and exact matching work consistently
  13170. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13171. using namespace httplib::tls;
  13172. // We need a running server to test against
  13173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13174. ASSERT_TRUE(svr.is_valid());
  13175. svr.Get("/test", [](const Request &, Response &res) {
  13176. res.set_content("ok", "text/plain");
  13177. });
  13178. thread t([&]() { svr.listen(HOST, PORT); });
  13179. auto se = detail::scope_exit([&] {
  13180. svr.stop();
  13181. t.join();
  13182. });
  13183. svr.wait_until_ready();
  13184. bool verify_callback_called = false;
  13185. bool verify_result_wrong = false;
  13186. SSLClient cli(HOST, PORT);
  13187. cli.enable_server_certificate_verification(true);
  13188. cli.set_ca_cert_path(CA_CERT_FILE);
  13189. cli.set_connection_timeout(5);
  13190. // Note: Test certificate has CN="Common Name", not "localhost"
  13191. bool verify_result_cn = false;
  13192. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13193. verify_callback_called = true;
  13194. if (!ctx.cert) return false;
  13195. // Test 1: "Common Name" should match (our test server cert CN)
  13196. verify_result_cn = ctx.check_hostname("Common Name");
  13197. // Test 2: wrong hostname should not match
  13198. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13199. return true; // Accept for the purpose of this test
  13200. });
  13201. auto res = cli.Get("/test");
  13202. // The request may succeed or fail depending on cert configuration
  13203. // but the callback should have been called
  13204. ASSERT_TRUE(verify_callback_called)
  13205. << "Verify callback should have been called";
  13206. // CN="Common Name" should match our test certificate
  13207. //
  13208. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13209. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13210. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13211. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13212. // <openssl/base.h>, which is included transitively when
  13213. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13214. #if defined(OPENSSL_IS_BORINGSSL)
  13215. EXPECT_FALSE(verify_result_cn)
  13216. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13217. #else
  13218. EXPECT_TRUE(verify_result_cn)
  13219. << "verify_hostname should match 'Common Name' (certificate CN)";
  13220. #endif
  13221. // Wrong hostname should not match
  13222. EXPECT_FALSE(verify_result_wrong)
  13223. << "verify_hostname should not match 'wronghost.example.com'";
  13224. }
  13225. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13226. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13227. // X509_check_ip behavior and must hold for every backend.
  13228. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13229. using namespace httplib::tls;
  13230. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13231. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13232. ASSERT_TRUE(svr.is_valid());
  13233. svr.Get("/test", [](const Request &, Response &res) {
  13234. res.set_content("ok", "text/plain");
  13235. });
  13236. thread t([&]() { svr.listen(HOST, PORT); });
  13237. auto se = detail::scope_exit([&] {
  13238. svr.stop();
  13239. t.join();
  13240. });
  13241. svr.wait_until_ready();
  13242. bool verify_callback_called = false;
  13243. bool ip_matched_via_cn = true;
  13244. SSLClient cli(HOST, PORT);
  13245. cli.enable_server_certificate_verification(true);
  13246. cli.set_ca_cert_path(CA_CERT_FILE);
  13247. cli.set_connection_timeout(5);
  13248. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13249. verify_callback_called = true;
  13250. if (!ctx.cert) return false;
  13251. // The IP appears only in the CN, so it must NOT be accepted.
  13252. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13253. return true; // Accept for the purpose of this test
  13254. });
  13255. cli.Get("/test");
  13256. ASSERT_TRUE(verify_callback_called)
  13257. << "Verify callback should have been called";
  13258. EXPECT_FALSE(ip_matched_via_cn)
  13259. << "An IP host must not be authenticated via the certificate CN";
  13260. }
  13261. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13262. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13263. using namespace httplib::tls;
  13264. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13265. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13266. ASSERT_TRUE(svr.is_valid());
  13267. svr.Get("/test", [](const Request &, Response &res) {
  13268. res.set_content("ok", "text/plain");
  13269. });
  13270. thread t([&]() { svr.listen(HOST, PORT); });
  13271. auto se = detail::scope_exit([&] {
  13272. svr.stop();
  13273. t.join();
  13274. });
  13275. svr.wait_until_ready();
  13276. bool verify_callback_called = false;
  13277. bool san_matched = false;
  13278. bool wrong_ipv6_matched = true;
  13279. bool cn_ipv6_matched = true;
  13280. SSLClient cli(HOST, PORT);
  13281. cli.enable_server_certificate_verification(true);
  13282. cli.set_ca_cert_path(CA_CERT_FILE);
  13283. cli.set_connection_timeout(5);
  13284. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13285. verify_callback_called = true;
  13286. if (!ctx.cert) return false;
  13287. // Matches the IPv6 iPAddress SAN.
  13288. san_matched = ctx.check_hostname("2001:db8::1");
  13289. // A different IPv6 address must not match.
  13290. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13291. // "::1" lives only in the CN, so it must not be accepted.
  13292. cn_ipv6_matched = ctx.check_hostname("::1");
  13293. return true; // Accept for the purpose of this test
  13294. });
  13295. cli.Get("/test");
  13296. ASSERT_TRUE(verify_callback_called)
  13297. << "Verify callback should have been called";
  13298. EXPECT_TRUE(san_matched)
  13299. << "verify_hostname should match an IPv6 iPAddress SAN";
  13300. EXPECT_FALSE(wrong_ipv6_matched)
  13301. << "verify_hostname should not match a non-matching IPv6 address";
  13302. EXPECT_FALSE(cn_ipv6_matched)
  13303. << "An IPv6 host must not be authenticated via the certificate CN";
  13304. }
  13305. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13306. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13307. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13308. using namespace httplib::tls;
  13309. // SANs: DNS:a.zz, IP:42.46.122.122
  13310. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13311. ASSERT_TRUE(svr.is_valid());
  13312. svr.Get("/test", [](const Request &, Response &res) {
  13313. res.set_content("ok", "text/plain");
  13314. });
  13315. auto port = svr.bind_to_any_port(HOST);
  13316. thread t([&]() { svr.listen_after_bind(); });
  13317. auto se = detail::scope_exit([&] {
  13318. svr.stop();
  13319. t.join();
  13320. });
  13321. svr.wait_until_ready();
  13322. bool verify_callback_called = false;
  13323. bool dns_san_matched = false;
  13324. bool ip_san_matched = false;
  13325. bool ip_matched_via_dns_san = true;
  13326. bool dns_matched_via_ip_san = true;
  13327. SSLClient cli(HOST, port);
  13328. cli.enable_server_certificate_verification(true);
  13329. cli.set_ca_cert_path(CA_CERT_FILE);
  13330. cli.set_connection_timeout(5);
  13331. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13332. verify_callback_called = true;
  13333. if (!ctx.cert) return false;
  13334. dns_san_matched = ctx.check_hostname("a.zz");
  13335. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13336. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13337. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13338. return true; // Accept for the purpose of this test
  13339. });
  13340. cli.Get("/test");
  13341. ASSERT_TRUE(verify_callback_called)
  13342. << "Verify callback should have been called";
  13343. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13344. EXPECT_TRUE(ip_san_matched)
  13345. << "verify_hostname should match an iPAddress SAN";
  13346. EXPECT_FALSE(ip_matched_via_dns_san)
  13347. << "An IP host must not be authenticated via a dNSName SAN";
  13348. EXPECT_FALSE(dns_matched_via_ip_san)
  13349. << "A DNS host must not be authenticated via an iPAddress SAN";
  13350. }
  13351. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13352. // "www.*.example.test" names one host and not every host under example.test.
  13353. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13354. using namespace httplib::tls;
  13355. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13356. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13357. ASSERT_TRUE(svr.is_valid());
  13358. svr.Get("/test", [](const Request &, Response &res) {
  13359. res.set_content("ok", "text/plain");
  13360. });
  13361. auto port = svr.bind_to_any_port(HOST);
  13362. thread t([&]() { svr.listen_after_bind(); });
  13363. auto se = detail::scope_exit([&] {
  13364. svr.stop();
  13365. t.join();
  13366. });
  13367. svr.wait_until_ready();
  13368. bool verify_callback_called = false;
  13369. bool leftmost_wildcard_matched = false;
  13370. bool wildcard_spanned_labels = true;
  13371. bool inner_wildcard_matched = true;
  13372. SSLClient cli(HOST, port);
  13373. cli.enable_server_certificate_verification(true);
  13374. cli.set_ca_cert_path(CA_CERT_FILE);
  13375. cli.set_connection_timeout(5);
  13376. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13377. verify_callback_called = true;
  13378. if (!ctx.cert) return false;
  13379. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13380. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13381. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13382. return true; // Accept for the purpose of this test
  13383. });
  13384. cli.Get("/test");
  13385. ASSERT_TRUE(verify_callback_called)
  13386. << "Verify callback should have been called";
  13387. EXPECT_TRUE(leftmost_wildcard_matched)
  13388. << "A leftmost wildcard should match a single label";
  13389. EXPECT_FALSE(wildcard_spanned_labels)
  13390. << "A wildcard label must not match more than one label";
  13391. EXPECT_FALSE(inner_wildcard_matched)
  13392. << "A wildcard outside the leftmost label must not be honoured";
  13393. }
  13394. // sans() must report each SAN entry under its own type.
  13395. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13396. using namespace httplib::tls;
  13397. // SANs: DNS:a.zz, IP:42.46.122.122
  13398. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13399. ASSERT_TRUE(svr.is_valid());
  13400. svr.Get("/test", [](const Request &, Response &res) {
  13401. res.set_content("ok", "text/plain");
  13402. });
  13403. auto port = svr.bind_to_any_port(HOST);
  13404. thread t([&]() { svr.listen_after_bind(); });
  13405. auto se = detail::scope_exit([&] {
  13406. svr.stop();
  13407. t.join();
  13408. });
  13409. svr.wait_until_ready();
  13410. bool verify_callback_called = false;
  13411. std::vector<SanEntry> sans;
  13412. SSLClient cli(HOST, port);
  13413. cli.enable_server_certificate_verification(true);
  13414. cli.set_ca_cert_path(CA_CERT_FILE);
  13415. cli.set_connection_timeout(5);
  13416. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13417. verify_callback_called = true;
  13418. if (!ctx.cert) return false;
  13419. sans = ctx.sans();
  13420. return true; // Accept for the purpose of this test
  13421. });
  13422. cli.Get("/test");
  13423. ASSERT_TRUE(verify_callback_called)
  13424. << "Verify callback should have been called";
  13425. auto has_san = [&](SanType type, const std::string &value) {
  13426. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13427. return san.type == type && san.value == value;
  13428. });
  13429. };
  13430. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13431. << "sans() should report the dNSName SAN";
  13432. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13433. << "sans() should report the iPAddress SAN";
  13434. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13435. << "sans() must not report the dNSName SAN as an address";
  13436. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13437. << "sans() must not report the iPAddress SAN as a DNS name";
  13438. }
  13439. #endif
  13440. // mbedTLS-specific callback constructor test
  13441. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13442. #ifdef CPPHTTPLIB_SSL_ENABLED
  13443. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13445. ASSERT_TRUE(svr.is_valid());
  13446. // Set up a handler to verify client certificate is present
  13447. bool client_cert_verified = false;
  13448. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13449. // Verify that client certificate was provided
  13450. client_cert_verified = true;
  13451. res.set_content("success", "text/plain");
  13452. });
  13453. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13454. auto se = detail::scope_exit([&] {
  13455. svr.stop();
  13456. t.join();
  13457. ASSERT_FALSE(svr.is_running());
  13458. });
  13459. svr.wait_until_ready();
  13460. // Client with certificate
  13461. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13462. cli.enable_server_certificate_verification(false);
  13463. cli.set_connection_timeout(30);
  13464. auto res = cli.Get("/test");
  13465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13466. ASSERT_EQ(StatusCode::OK_200, res->status);
  13467. ASSERT_TRUE(client_cert_verified);
  13468. EXPECT_EQ("success", res->body);
  13469. }
  13470. #endif
  13471. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13472. // backends
  13473. #ifdef CPPHTTPLIB_SSL_ENABLED
  13474. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13475. using namespace httplib::tls;
  13476. // Test that when client CA cert file is provided,
  13477. // the server properly requests and validates client certificates
  13478. // Create a server with client authentication
  13479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13480. ASSERT_TRUE(svr.is_valid());
  13481. bool handler_called = false;
  13482. svr.Get("/test", [&](const Request &req, Response &res) {
  13483. handler_called = true;
  13484. // Verify that a client certificate was provided
  13485. auto cert = req.peer_cert();
  13486. ASSERT_TRUE(static_cast<bool>(cert));
  13487. // Get the issuer name
  13488. std::string issuer_str = cert.issuer_name();
  13489. ASSERT_FALSE(issuer_str.empty());
  13490. // The client certificate should be issued by our test CA
  13491. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13492. res.set_content("authenticated", "text/plain");
  13493. });
  13494. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13495. auto se = detail::scope_exit([&] {
  13496. svr.stop();
  13497. t.join();
  13498. ASSERT_FALSE(svr.is_running());
  13499. });
  13500. svr.wait_until_ready();
  13501. // Connect with a client certificate issued by the CA
  13502. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13503. cli.enable_server_certificate_verification(false);
  13504. cli.set_connection_timeout(30);
  13505. auto res = cli.Get("/test");
  13506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13507. ASSERT_EQ(StatusCode::OK_200, res->status);
  13508. ASSERT_TRUE(handler_called);
  13509. EXPECT_EQ("authenticated", res->body);
  13510. }
  13511. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13512. using namespace httplib::tls;
  13513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13514. ASSERT_TRUE(svr.is_valid());
  13515. svr.Get("/test", [](const Request &, Response &res) {
  13516. res.set_content("ok", "text/plain");
  13517. });
  13518. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13519. auto se = detail::scope_exit([&] {
  13520. svr.stop();
  13521. t.join();
  13522. });
  13523. svr.wait_until_ready();
  13524. SSLClient cli(HOST, PORT);
  13525. cli.enable_server_certificate_verification(false);
  13526. cli.set_connection_timeout(30);
  13527. bool cert_checked = false;
  13528. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13529. if (ctx.cert) {
  13530. auto sans = ctx.sans();
  13531. // Test certificate may or may not have SANs - just verify the API
  13532. // works If SANs exist, verify the types are valid
  13533. for (const auto &san : sans) {
  13534. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13535. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13536. san.type == SanType::OTHER);
  13537. EXPECT_FALSE(san.value.empty());
  13538. }
  13539. cert_checked = true;
  13540. }
  13541. return true;
  13542. });
  13543. auto res = cli.Get("/test");
  13544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13545. EXPECT_TRUE(cert_checked);
  13546. }
  13547. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13548. using namespace httplib::tls;
  13549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13550. ASSERT_TRUE(svr.is_valid());
  13551. svr.Get("/test", [](const Request &, Response &res) {
  13552. res.set_content("ok", "text/plain");
  13553. });
  13554. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13555. auto se = detail::scope_exit([&] {
  13556. svr.stop();
  13557. t.join();
  13558. });
  13559. svr.wait_until_ready();
  13560. SSLClient cli(HOST, PORT);
  13561. cli.enable_server_certificate_verification(false);
  13562. cli.set_connection_timeout(30);
  13563. bool validity_checked = false;
  13564. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13565. if (ctx.cert) {
  13566. time_t not_before = 0, not_after = 0;
  13567. bool result = ctx.validity(not_before, not_after);
  13568. EXPECT_TRUE(result);
  13569. // Verify that not_before < now < not_after for a valid cert
  13570. time_t now = time(nullptr);
  13571. EXPECT_LT(not_before, now);
  13572. EXPECT_GT(not_after, now);
  13573. validity_checked = true;
  13574. }
  13575. return true;
  13576. });
  13577. auto res = cli.Get("/test");
  13578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13579. EXPECT_TRUE(validity_checked);
  13580. }
  13581. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13582. using namespace httplib::tls;
  13583. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13584. ASSERT_TRUE(svr.is_valid());
  13585. svr.Get("/test", [](const Request &, Response &res) {
  13586. res.set_content("ok", "text/plain");
  13587. });
  13588. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13589. auto se = detail::scope_exit([&] {
  13590. svr.stop();
  13591. t.join();
  13592. });
  13593. svr.wait_until_ready();
  13594. SSLClient cli(HOST, PORT);
  13595. cli.enable_server_certificate_verification(false);
  13596. cli.set_connection_timeout(30);
  13597. bool serial_checked = false;
  13598. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13599. if (ctx.cert) {
  13600. std::string serial = ctx.serial();
  13601. EXPECT_FALSE(serial.empty());
  13602. // Serial should be a hex string
  13603. for (char c : serial) {
  13604. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13605. (c >= 'a' && c <= 'f'));
  13606. }
  13607. serial_checked = true;
  13608. }
  13609. return true;
  13610. });
  13611. auto res = cli.Get("/test");
  13612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13613. EXPECT_TRUE(serial_checked);
  13614. }
  13615. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13616. // Test 1: Valid CA file - no error should be recorded
  13617. {
  13618. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13619. CLIENT_CA_CERT_FILE);
  13620. ASSERT_TRUE(svr.is_valid());
  13621. // With valid setup, last_ssl_error should be 0
  13622. EXPECT_EQ(0, svr.ssl_last_error());
  13623. }
  13624. // Test 2: Invalid CA file content
  13625. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13626. {
  13627. // Create a temporary file with completely invalid content
  13628. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13629. {
  13630. std::ofstream ofs(temp_invalid_ca);
  13631. ofs << "This is not a certificate file at all\n";
  13632. ofs << "Just plain text content\n";
  13633. }
  13634. // Create server with invalid CA file
  13635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13636. // Clean up temporary file
  13637. std::remove(temp_invalid_ca);
  13638. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13639. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13640. // Note: SSL_CTX_load_verify_locations typically fails first,
  13641. // but our error handling code path is still exercised
  13642. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13643. }
  13644. }
  13645. TEST(VerifyCallbackTest, VerifyContextFields) {
  13646. using namespace httplib::tls;
  13647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13648. ASSERT_TRUE(svr.is_valid());
  13649. svr.Get("/test", [](const Request &, Response &res) {
  13650. res.set_content("ok", "text/plain");
  13651. });
  13652. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13653. auto se = detail::scope_exit([&] {
  13654. svr.stop();
  13655. t.join();
  13656. });
  13657. svr.wait_until_ready();
  13658. SSLClient cli(HOST, PORT);
  13659. cli.enable_server_certificate_verification(false);
  13660. cli.set_connection_timeout(30);
  13661. int callback_count = 0;
  13662. bool saw_leaf_cert = false;
  13663. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13664. if (ctx.cert) {
  13665. callback_count++;
  13666. // We should see at least one certificate (the leaf)
  13667. std::string cn = ctx.subject_cn();
  13668. if (!cn.empty()) { saw_leaf_cert = true; }
  13669. // Verify context fields are populated
  13670. EXPECT_NE(ctx.session, nullptr);
  13671. EXPECT_GE(ctx.depth, 0);
  13672. }
  13673. return true;
  13674. });
  13675. auto res = cli.Get("/test");
  13676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13677. EXPECT_GT(callback_count, 0);
  13678. EXPECT_TRUE(saw_leaf_cert);
  13679. }
  13680. // A verifier belongs to the client that set it, not to the thread that set it.
  13681. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13682. using namespace httplib::tls;
  13683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13684. ASSERT_TRUE(svr.is_valid());
  13685. svr.Get("/test", [](const Request &, Response &res) {
  13686. res.set_content("ok", "text/plain");
  13687. });
  13688. auto port = svr.bind_to_any_port(HOST);
  13689. thread t([&]() { svr.listen_after_bind(); });
  13690. auto se = detail::scope_exit([&] {
  13691. svr.stop();
  13692. t.join();
  13693. });
  13694. svr.wait_until_ready();
  13695. auto rejecting_calls = 0;
  13696. SSLClient rejecting(HOST, port);
  13697. rejecting.enable_server_certificate_verification(false);
  13698. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13699. rejecting_calls++;
  13700. return false;
  13701. });
  13702. auto accepting_calls = 0;
  13703. SSLClient accepting(HOST, port);
  13704. accepting.enable_server_certificate_verification(false);
  13705. // Set on another thread than the requests below.
  13706. thread([&]() {
  13707. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13708. accepting_calls++;
  13709. return true;
  13710. });
  13711. }).join();
  13712. // Requested on another thread than the verifier was set on.
  13713. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13714. EXPECT_GT(rejecting_calls, 0);
  13715. auto res = accepting.Get("/test");
  13716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13717. EXPECT_GT(accepting_calls, 0);
  13718. }
  13719. // VerifyContext::session is the same handle the other tls:: functions take.
  13720. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13721. using namespace httplib::tls;
  13722. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13723. ASSERT_TRUE(svr.is_valid());
  13724. svr.Get("/test", [](const Request &, Response &res) {
  13725. res.set_content("ok", "text/plain");
  13726. });
  13727. auto port = svr.bind_to_any_port(HOST);
  13728. thread t([&]() { svr.listen_after_bind(); });
  13729. auto se = detail::scope_exit([&] {
  13730. svr.stop();
  13731. t.join();
  13732. });
  13733. svr.wait_until_ready();
  13734. SSLClient cli(HOST, port);
  13735. cli.enable_server_certificate_verification(false);
  13736. session_t verifier_session = nullptr;
  13737. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13738. verifier_session = ctx.session;
  13739. return true;
  13740. });
  13741. session_t session_verifier_session = nullptr;
  13742. cli.set_session_verifier([&](session_t session) {
  13743. session_verifier_session = session;
  13744. return SSLVerifierResponse::NoDecisionMade;
  13745. });
  13746. auto res = cli.Get("/test");
  13747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13748. EXPECT_NE(nullptr, verifier_session);
  13749. EXPECT_EQ(session_verifier_session, verifier_session);
  13750. }
  13751. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13752. using httplib::tls::TlsError;
  13753. // Test that verify_error_to_string returns empty for success
  13754. std::string success_str = TlsError::verify_error_to_string(0);
  13755. EXPECT_TRUE(success_str.empty());
  13756. // Test that verify_error_to_string returns non-empty for error codes
  13757. // Using a common error code (certificate expired)
  13758. std::string error_str =
  13759. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13760. EXPECT_FALSE(error_str.empty());
  13761. }
  13762. TEST(SessionVerifierTest, CertificateAccepted) {
  13763. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13764. ASSERT_TRUE(svr.is_valid());
  13765. svr.Get("/test", [](const Request &, Response &res) {
  13766. res.set_content("ok", "text/plain");
  13767. });
  13768. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13769. auto se = detail::scope_exit([&] {
  13770. svr.stop();
  13771. t.join();
  13772. });
  13773. svr.wait_until_ready();
  13774. SSLClient cli(HOST, PORT);
  13775. cli.enable_server_certificate_verification(false);
  13776. cli.set_connection_timeout(30);
  13777. bool callback_called = false;
  13778. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13779. EXPECT_NE(session, nullptr);
  13780. callback_called = true;
  13781. return SSLVerifierResponse::CertificateAccepted;
  13782. });
  13783. auto res = cli.Get("/test");
  13784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13785. EXPECT_EQ(200, res->status);
  13786. EXPECT_TRUE(callback_called);
  13787. }
  13788. TEST(SessionVerifierTest, CertificateRejected) {
  13789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13790. ASSERT_TRUE(svr.is_valid());
  13791. svr.Get("/test", [](const Request &, Response &res) {
  13792. res.set_content("ok", "text/plain");
  13793. });
  13794. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13795. auto se = detail::scope_exit([&] {
  13796. svr.stop();
  13797. t.join();
  13798. });
  13799. svr.wait_until_ready();
  13800. SSLClient cli(HOST, PORT);
  13801. cli.enable_server_certificate_verification(false);
  13802. cli.set_connection_timeout(30);
  13803. bool callback_called = false;
  13804. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13805. EXPECT_NE(session, nullptr);
  13806. callback_called = true;
  13807. return SSLVerifierResponse::CertificateRejected;
  13808. });
  13809. auto res = cli.Get("/test");
  13810. EXPECT_FALSE(res);
  13811. EXPECT_TRUE(callback_called);
  13812. }
  13813. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13815. ASSERT_TRUE(svr.is_valid());
  13816. svr.Get("/test", [](const Request &, Response &res) {
  13817. res.set_content("ok", "text/plain");
  13818. });
  13819. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13820. auto se = detail::scope_exit([&] {
  13821. svr.stop();
  13822. t.join();
  13823. });
  13824. svr.wait_until_ready();
  13825. // NoDecisionMade with verification disabled should succeed (no default check)
  13826. SSLClient cli(HOST, PORT);
  13827. cli.enable_server_certificate_verification(false);
  13828. cli.set_connection_timeout(30);
  13829. bool callback_called = false;
  13830. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13831. EXPECT_NE(session, nullptr);
  13832. callback_called = true;
  13833. return SSLVerifierResponse::NoDecisionMade;
  13834. });
  13835. auto res = cli.Get("/test");
  13836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13837. EXPECT_EQ(200, res->status);
  13838. EXPECT_TRUE(callback_called);
  13839. }
  13840. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13842. ASSERT_TRUE(svr.is_valid());
  13843. svr.Get("/test", [](const Request &, Response &res) {
  13844. res.set_content("ok", "text/plain");
  13845. });
  13846. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13847. auto se = detail::scope_exit([&] {
  13848. svr.stop();
  13849. t.join();
  13850. });
  13851. svr.wait_until_ready();
  13852. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13853. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13854. // so we only check that the request fails, not whether the callback was
  13855. // called.
  13856. SSLClient cli(HOST, PORT);
  13857. cli.enable_server_certificate_verification(true);
  13858. cli.set_connection_timeout(30);
  13859. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13860. EXPECT_NE(session, nullptr);
  13861. return SSLVerifierResponse::NoDecisionMade;
  13862. });
  13863. auto res = cli.Get("/test");
  13864. EXPECT_FALSE(res);
  13865. }
  13866. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13867. // Test SSL server using PemMemory constructor with client CA certificates
  13868. // Read PEM files
  13869. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13870. read_file(SERVER_CERT_FILE, server_cert_pem);
  13871. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13872. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13873. // Create SSLServer with PemMemory constructor including client CA
  13874. SSLServer::PemMemory server_pem = {
  13875. server_cert_pem.c_str(),
  13876. server_cert_pem.size(),
  13877. server_key_pem.c_str(),
  13878. server_key_pem.size(),
  13879. client_ca_pem.c_str(),
  13880. client_ca_pem.size(),
  13881. nullptr // no password for server key
  13882. };
  13883. SSLServer svr(server_pem);
  13884. ASSERT_TRUE(svr.is_valid());
  13885. // No SSL error should be recorded for valid setup
  13886. EXPECT_EQ(0, svr.ssl_last_error());
  13887. // Set up server endpoints
  13888. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13889. res.set_content("ok", "text/plain");
  13890. });
  13891. // Start server in a thread
  13892. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13893. svr.wait_until_ready();
  13894. // Connect with client certificate (using constructor with paths)
  13895. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13896. cli.enable_server_certificate_verification(false);
  13897. auto res = cli.Get("/test-pem-ca");
  13898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13899. EXPECT_EQ(200, res->status);
  13900. EXPECT_EQ("ok", res->body);
  13901. svr.stop();
  13902. server_thread.join();
  13903. }
  13904. #endif
  13905. #ifdef _WIN32
  13906. TEST(CleanupTest, WSACleanup) {
  13907. int ret = WSACleanup();
  13908. ASSERT_EQ(0, ret);
  13909. }
  13910. #endif
  13911. #ifndef CPPHTTPLIB_SSL_ENABLED
  13912. TEST(NoSSLSupport, SimpleInterface) {
  13913. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13914. }
  13915. #endif
  13916. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13917. TEST(InvalidScheme, SimpleInterface) {
  13918. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13919. }
  13920. #endif
  13921. TEST(NoScheme, SimpleInterface) {
  13922. Client cli("yahoo.com:80");
  13923. ASSERT_TRUE(cli.is_valid());
  13924. }
  13925. TEST(SendAPI, SimpleInterface_Online) {
  13926. Client cli("http://yahoo.com");
  13927. Request req;
  13928. req.method = "GET";
  13929. req.path = "/";
  13930. auto res = cli.send(req);
  13931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13932. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13933. }
  13934. TEST(SendAPI, WithParamsInRequest) {
  13935. Server svr;
  13936. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13937. EXPECT_TRUE(req.has_param("test"));
  13938. EXPECT_EQ("test_value", req.get_param_value("test"));
  13939. });
  13940. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13941. auto se = detail::scope_exit([&] {
  13942. svr.stop();
  13943. t.join();
  13944. ASSERT_FALSE(svr.is_running());
  13945. });
  13946. svr.wait_until_ready();
  13947. Client cli(HOST, PORT);
  13948. {
  13949. Request req;
  13950. req.method = "GET";
  13951. req.path = "/";
  13952. req.params.emplace("test", "test_value");
  13953. auto res = cli.send(req);
  13954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13955. }
  13956. {
  13957. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13959. }
  13960. }
  13961. TEST(ClientImplMethods, GetSocketTest) {
  13962. httplib::Server svr;
  13963. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13964. res.status = StatusCode::OK_200;
  13965. });
  13966. auto port = svr.bind_to_any_port("127.0.0.1");
  13967. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13968. auto se = detail::scope_exit([&] {
  13969. svr.stop();
  13970. thread.join();
  13971. ASSERT_FALSE(svr.is_running());
  13972. });
  13973. svr.wait_until_ready();
  13974. {
  13975. httplib::Client cli("127.0.0.1", port);
  13976. cli.set_keep_alive(true);
  13977. // Use the behavior of cpp-httplib of opening the connection
  13978. // only when the first request happens. If that changes,
  13979. // this test would be obsolete.
  13980. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13981. // This also implicitly tests the server. But other tests would fail much
  13982. // earlier than this one to be considered.
  13983. auto res = cli.Get("/");
  13984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13985. EXPECT_EQ(StatusCode::OK_200, res->status);
  13986. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13987. }
  13988. }
  13989. #ifdef CPPHTTPLIB_SSL_ENABLED
  13990. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13991. Client cli("http://yahoo.com");
  13992. auto res = cli.Get("/");
  13993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13994. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13995. cli.set_follow_location(true);
  13996. res = cli.Get("/");
  13997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13998. EXPECT_EQ(StatusCode::OK_200, res->status);
  13999. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14000. }
  14001. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14002. Client cli("https://yahoo.com");
  14003. auto res = cli.Get("/");
  14004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14005. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14006. cli.set_follow_location(true);
  14007. res = cli.Get("/");
  14008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14009. EXPECT_EQ(StatusCode::OK_200, res->status);
  14010. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14011. }
  14012. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14013. Client cli("https://yahoo.com");
  14014. auto res = cli.Get("/");
  14015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14016. ASSERT_FALSE(!res);
  14017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14018. ASSERT_FALSE(res == nullptr);
  14019. ASSERT_TRUE(res != nullptr);
  14020. EXPECT_EQ(Error::Success, res.error());
  14021. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14022. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14023. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14024. cli.set_follow_location(true);
  14025. res = cli.Get("/");
  14026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14027. EXPECT_EQ(Error::Success, res.error());
  14028. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14029. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14030. EXPECT_EQ(StatusCode::OK_200, res->status);
  14031. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14032. }
  14033. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14034. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14035. Client cli("https://cdnjs.cloudflare.com");
  14036. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14037. Headers{{"Accept-Encoding", "br"}});
  14038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14039. EXPECT_EQ(StatusCode::OK_200, res->status);
  14040. EXPECT_EQ(287630U, res->body.size());
  14041. EXPECT_EQ("application/javascript; charset=utf-8",
  14042. res->get_header_value("Content-Type"));
  14043. }
  14044. #endif
  14045. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14046. #undef REDIR_HOST // Silence compiler warning
  14047. #define REDIR_HOST "https://httpbingo.org"
  14048. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14049. Client cli(REDIR_HOST);
  14050. cli.set_follow_location(true);
  14051. auto res =
  14052. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14054. EXPECT_EQ(StatusCode::OK_200, res->status);
  14055. }
  14056. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14057. Client cli(REDIR_HOST);
  14058. cli.set_follow_location(true);
  14059. Params params;
  14060. params.emplace("url", "http://example.com");
  14061. params.emplace("status_code", "302");
  14062. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14064. EXPECT_EQ(StatusCode::OK_200, res->status);
  14065. }
  14066. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14067. Client cli(REDIR_HOST);
  14068. cli.set_follow_location(true);
  14069. Params params;
  14070. params.emplace("url", "http://example.com");
  14071. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14073. EXPECT_EQ(StatusCode::OK_200, res->status);
  14074. }
  14075. TEST(HttpToHttpsRedirectTest, CertFile) {
  14076. auto ssl_port = PORT + 1;
  14077. Server svr;
  14078. ASSERT_TRUE(svr.is_valid());
  14079. svr.Get("/index", [&](const Request &, Response &res) {
  14080. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14081. "/index");
  14082. svr.stop();
  14083. });
  14084. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14085. ASSERT_TRUE(ssl_svr.is_valid());
  14086. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14087. res.set_content("test", "text/plain");
  14088. ssl_svr.stop();
  14089. });
  14090. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14091. thread t2 =
  14092. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14093. auto se = detail::scope_exit([&] {
  14094. t2.join();
  14095. t.join();
  14096. ASSERT_FALSE(svr.is_running());
  14097. });
  14098. svr.wait_until_ready();
  14099. ssl_svr.wait_until_ready();
  14100. Client cli("127.0.0.1", PORT);
  14101. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14102. cli.enable_server_certificate_verification(true);
  14103. cli.set_follow_location(true);
  14104. cli.set_connection_timeout(30);
  14105. auto res = cli.Get("/index");
  14106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14107. ASSERT_EQ(StatusCode::OK_200, res->status);
  14108. }
  14109. TEST(SSLClientRedirectTest, CertFile) {
  14110. auto ssl_port = PORT + 1;
  14111. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14112. ASSERT_TRUE(ssl_svr1.is_valid());
  14113. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14114. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14115. "/index");
  14116. ssl_svr1.stop();
  14117. });
  14118. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14119. ASSERT_TRUE(ssl_svr2.is_valid());
  14120. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14121. res.set_content("test", "text/plain");
  14122. ssl_svr2.stop();
  14123. });
  14124. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14125. thread t2 =
  14126. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14127. auto se = detail::scope_exit([&] {
  14128. t2.join();
  14129. t.join();
  14130. ASSERT_FALSE(ssl_svr1.is_running());
  14131. });
  14132. ssl_svr1.wait_until_ready();
  14133. ssl_svr2.wait_until_ready();
  14134. SSLClient cli("127.0.0.1", PORT);
  14135. std::string cert;
  14136. read_file(SERVER_CERT2_FILE, cert);
  14137. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14138. cli.enable_server_certificate_verification(true);
  14139. cli.set_follow_location(true);
  14140. cli.set_connection_timeout(30);
  14141. auto res = cli.Get("/index");
  14142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14143. ASSERT_EQ(StatusCode::OK_200, res->status);
  14144. }
  14145. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14146. // another port, so the client follows it with a new client.
  14147. static Result GetThroughTlsRedirectToDifferentPort(
  14148. const std::function<void(SSLClient &)> &setup,
  14149. const char *target_cert = SERVER_CERT2_FILE) {
  14150. auto ssl_port = PORT + 1;
  14151. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14152. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14153. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14154. "/index");
  14155. });
  14156. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14157. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14158. res.set_content("test", "text/plain");
  14159. });
  14160. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14161. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14162. auto se = detail::scope_exit([&] {
  14163. ssl_svr2.stop();
  14164. ssl_svr1.stop();
  14165. t2.join();
  14166. t.join();
  14167. });
  14168. ssl_svr1.wait_until_ready();
  14169. ssl_svr2.wait_until_ready();
  14170. SSLClient cli("127.0.0.1", PORT);
  14171. cli.set_follow_location(true);
  14172. cli.set_connection_timeout(30);
  14173. setup(cli);
  14174. return cli.Get("/index");
  14175. }
  14176. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14177. auto calls = 0;
  14178. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14179. cli.enable_server_certificate_verification(false);
  14180. // Accept the first server only.
  14181. cli.set_session_verifier([&](tls::session_t) {
  14182. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14183. : SSLVerifierResponse::CertificateRejected;
  14184. });
  14185. });
  14186. EXPECT_FALSE(res);
  14187. EXPECT_EQ(2, calls);
  14188. }
  14189. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14190. std::string pinned;
  14191. auto res = GetThroughTlsRedirectToDifferentPort(
  14192. [&](SSLClient &cli) {
  14193. cli.enable_server_certificate_verification(false);
  14194. // Pin the first certificate seen.
  14195. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14196. if (pinned.empty()) { pinned = ctx.serial(); }
  14197. return ctx.serial() == pinned;
  14198. });
  14199. },
  14200. // A certificate other than the first server's.
  14201. SERVER_CERT_FILE);
  14202. EXPECT_FALSE(res);
  14203. EXPECT_FALSE(pinned.empty());
  14204. }
  14205. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14206. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14207. std::string cert;
  14208. read_file(SERVER_CERT2_FILE, cert);
  14209. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14210. });
  14211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14212. EXPECT_EQ(StatusCode::OK_200, res->status);
  14213. }
  14214. #endif
  14215. #ifdef CPPHTTPLIB_SSL_ENABLED
  14216. // Test that set_ca_cert_store() skips system certs (consistent with
  14217. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14218. // should be trusted - system certs should NOT be loaded.
  14219. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14220. // Load a specific cert that is NOT a system CA cert
  14221. std::string cert;
  14222. read_file(SERVER_CERT2_FILE, cert);
  14223. SSLClient cli("google.com");
  14224. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14225. cli.enable_server_certificate_verification(true);
  14226. // This should FAIL because:
  14227. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14228. // 2. System certs should NOT be loaded when custom store is set
  14229. // If system certs WERE loaded, this would succeed
  14230. auto res = cli.Get("/");
  14231. ASSERT_FALSE(res);
  14232. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14233. }
  14234. // Same as above, but through the native store handle path. Regression test:
  14235. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14236. // merged system certs into the user-provided store.
  14237. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14238. std::string cert;
  14239. read_file(SERVER_CERT2_FILE, cert);
  14240. SSLClient cli("google.com");
  14241. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14242. cli.enable_server_certificate_verification(true);
  14243. auto res = cli.Get("/");
  14244. ASSERT_FALSE(res);
  14245. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14246. }
  14247. // A custom store set via the native handle must still verify a server whose
  14248. // cert it does contain.
  14249. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14250. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14251. ASSERT_TRUE(svr.is_valid());
  14252. svr.Get("/test", [&](const Request &, Response &res) {
  14253. res.set_content("test", "text/plain");
  14254. });
  14255. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14256. auto se = detail::scope_exit([&] {
  14257. svr.stop();
  14258. t.join();
  14259. ASSERT_FALSE(svr.is_running());
  14260. });
  14261. svr.wait_until_ready();
  14262. SSLClient cli("127.0.0.1", PORT);
  14263. std::string cert;
  14264. read_file(SERVER_CERT2_FILE, cert);
  14265. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14266. cli.enable_server_certificate_verification(true);
  14267. cli.set_connection_timeout(30);
  14268. auto res = cli.Get("/test");
  14269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14270. ASSERT_EQ(StatusCode::OK_200, res->status);
  14271. }
  14272. // CA certs loaded through the universal Client must be transferred to the
  14273. // client created internally for following an HTTPS redirect. Regression test:
  14274. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14275. // the CA data for redirect transfer.
  14276. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14277. auto ssl_port = PORT + 1;
  14278. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14279. ASSERT_TRUE(ssl_svr1.is_valid());
  14280. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14281. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14282. "/index");
  14283. });
  14284. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14285. ASSERT_TRUE(ssl_svr2.is_valid());
  14286. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14287. res.set_content("test", "text/plain");
  14288. });
  14289. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14290. thread t2 =
  14291. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14292. auto se = detail::scope_exit([&] {
  14293. ssl_svr2.stop();
  14294. ssl_svr1.stop();
  14295. t2.join();
  14296. t.join();
  14297. ASSERT_FALSE(ssl_svr1.is_running());
  14298. });
  14299. ssl_svr1.wait_until_ready();
  14300. ssl_svr2.wait_until_ready();
  14301. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14302. std::string cert;
  14303. read_file(SERVER_CERT2_FILE, cert);
  14304. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14305. cli.enable_server_certificate_verification(true);
  14306. cli.set_follow_location(true);
  14307. cli.set_connection_timeout(30);
  14308. auto res = cli.Get("/index");
  14309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14310. ASSERT_EQ(StatusCode::OK_200, res->status);
  14311. }
  14312. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14313. // so a host signed by a system CA verifies even though a custom CA is set
  14314. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14315. std::string cert;
  14316. read_file(SERVER_CERT2_FILE, cert);
  14317. SSLClient cli("google.com");
  14318. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14319. cli.enable_system_ca(true);
  14320. cli.enable_server_certificate_verification(true);
  14321. auto res = cli.Get("/");
  14322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14323. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14324. }
  14325. // The custom CA remains effective when combined with the system CA
  14326. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14327. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14328. ASSERT_TRUE(svr.is_valid());
  14329. svr.Get("/test", [&](const Request &, Response &res) {
  14330. res.set_content("test", "text/plain");
  14331. });
  14332. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14333. auto se = detail::scope_exit([&] {
  14334. svr.stop();
  14335. t.join();
  14336. ASSERT_FALSE(svr.is_running());
  14337. });
  14338. svr.wait_until_ready();
  14339. SSLClient cli("127.0.0.1", PORT);
  14340. std::string cert;
  14341. read_file(SERVER_CERT2_FILE, cert);
  14342. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14343. cli.enable_system_ca(true);
  14344. cli.enable_server_certificate_verification(true);
  14345. cli.set_connection_timeout(30);
  14346. auto res = cli.Get("/test");
  14347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14348. ASSERT_EQ(StatusCode::OK_200, res->status);
  14349. }
  14350. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14351. // skip chain verification entirely (only the certificate identity was
  14352. // checked), so a server presenting an untrusted certificate with a matching
  14353. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14354. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14355. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14356. ASSERT_TRUE(svr.is_valid());
  14357. svr.Get("/test", [&](const Request &, Response &res) {
  14358. res.set_content("test", "text/plain");
  14359. });
  14360. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14361. auto se = detail::scope_exit([&] {
  14362. svr.stop();
  14363. t.join();
  14364. ASSERT_FALSE(svr.is_running());
  14365. });
  14366. svr.wait_until_ready();
  14367. SSLClient cli("127.0.0.1", PORT);
  14368. std::string cert;
  14369. // A trusted CA that did not sign the server certificate. The server cert
  14370. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14371. // this connection.
  14372. read_file(CLIENT_CA_CERT_FILE, cert);
  14373. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14374. cli.enable_server_certificate_verification(true);
  14375. cli.set_connection_timeout(30);
  14376. auto res = cli.Get("/test");
  14377. ASSERT_FALSE(res);
  14378. }
  14379. // enable_system_ca(false) prevents system CA loading entirely
  14380. TEST(SSLClientTest, DisableSystemCa_Online) {
  14381. SSLClient cli("google.com");
  14382. cli.enable_system_ca(false);
  14383. cli.enable_server_certificate_verification(true);
  14384. auto res = cli.Get("/");
  14385. ASSERT_FALSE(res);
  14386. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14387. // itself when the CA chain is empty
  14388. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14389. res.error() == Error::SSLConnection);
  14390. }
  14391. // The universal Client forwards enable_system_ca()
  14392. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14393. std::string cert;
  14394. read_file(SERVER_CERT2_FILE, cert);
  14395. Client cli("https://google.com");
  14396. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14397. cli.enable_system_ca(true);
  14398. cli.enable_server_certificate_verification(true);
  14399. auto res = cli.Get("/");
  14400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14401. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14402. }
  14403. // The system CA policy must carry over to the client created internally for
  14404. // following a cross-host HTTPS redirect
  14405. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14406. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14407. ASSERT_TRUE(svr.is_valid());
  14408. svr.Get("/index", [&](const Request &, Response &res) {
  14409. res.set_redirect("https://www.google.com/");
  14410. });
  14411. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14412. auto se = detail::scope_exit([&] {
  14413. svr.stop();
  14414. t.join();
  14415. ASSERT_FALSE(svr.is_running());
  14416. });
  14417. svr.wait_until_ready();
  14418. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14419. std::string cert;
  14420. read_file(SERVER_CERT2_FILE, cert);
  14421. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14422. cli.enable_system_ca(true);
  14423. cli.enable_server_certificate_verification(true);
  14424. cli.set_follow_location(true);
  14425. cli.set_connection_timeout(30);
  14426. // Receiving any response proves the redirect client completed the TLS
  14427. // handshake with a system-CA-signed host
  14428. auto res = cli.Get("/index");
  14429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14430. }
  14431. TEST(MultipartFormDataTest, LargeData) {
  14432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14433. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14434. const ContentReader &content_reader) {
  14435. if (req.is_multipart_form_data()) {
  14436. std::vector<FormData> items;
  14437. content_reader(
  14438. [&](const FormData &file) {
  14439. items.push_back(file);
  14440. return true;
  14441. },
  14442. [&](const char *data, size_t data_length) {
  14443. items.back().content.append(data, data_length);
  14444. return true;
  14445. });
  14446. EXPECT_TRUE(std::string(items[0].name) == "document");
  14447. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14448. EXPECT_TRUE(items[0].filename == "2MB_data");
  14449. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14450. EXPECT_TRUE(items[1].name == "hello");
  14451. EXPECT_TRUE(items[1].content == "world");
  14452. EXPECT_TRUE(items[1].filename == "");
  14453. EXPECT_TRUE(items[1].content_type == "");
  14454. } else {
  14455. std::string body;
  14456. content_reader([&](const char *data, size_t data_length) {
  14457. body.append(data, data_length);
  14458. return true;
  14459. });
  14460. }
  14461. });
  14462. auto port = svr.bind_to_any_port(HOST);
  14463. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14464. auto se = detail::scope_exit([&] {
  14465. svr.stop();
  14466. t.join();
  14467. ASSERT_FALSE(svr.is_running());
  14468. });
  14469. svr.wait_until_ready();
  14470. {
  14471. std::string data(1024 * 1024 * 2, '.');
  14472. std::stringstream buffer;
  14473. buffer << data;
  14474. SSLClient cli(HOST, port);
  14475. cli.enable_server_certificate_verification(false);
  14476. UploadFormDataItems items{
  14477. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14478. {"hello", "world", "", ""},
  14479. };
  14480. auto res = cli.Post("/post", items);
  14481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14482. ASSERT_EQ(StatusCode::OK_200, res->status);
  14483. }
  14484. }
  14485. TEST(MultipartFormDataTest, DataProviderItems) {
  14486. std::random_device seed_gen;
  14487. std::mt19937 random(seed_gen());
  14488. std::string rand1;
  14489. rand1.resize(1000);
  14490. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14491. std::string rand2;
  14492. rand2.resize(3000);
  14493. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14495. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14496. const ContentReader &content_reader) {
  14497. ASSERT_FALSE(req.is_multipart_form_data());
  14498. std::string body;
  14499. content_reader([&](const char *data, size_t data_length) {
  14500. body.append(data, data_length);
  14501. return true;
  14502. });
  14503. EXPECT_EQ(body, "");
  14504. });
  14505. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14506. const ContentReader &content_reader) {
  14507. ASSERT_TRUE(req.is_multipart_form_data());
  14508. std::vector<FormData> items;
  14509. content_reader(
  14510. [&](const FormData &file) {
  14511. items.push_back(file);
  14512. return true;
  14513. },
  14514. [&](const char *data, size_t data_length) {
  14515. items.back().content.append(data, data_length);
  14516. return true;
  14517. });
  14518. ASSERT_TRUE(items.size() == 2);
  14519. EXPECT_EQ(std::string(items[0].name), "name1");
  14520. EXPECT_EQ(items[0].content, "Testing123");
  14521. EXPECT_EQ(items[0].filename, "filename1");
  14522. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14523. EXPECT_EQ(items[1].name, "name2");
  14524. EXPECT_EQ(items[1].content, "Testing456");
  14525. EXPECT_EQ(items[1].filename, "");
  14526. EXPECT_EQ(items[1].content_type, "");
  14527. });
  14528. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14529. const ContentReader &content_reader) {
  14530. ASSERT_TRUE(req.is_multipart_form_data());
  14531. std::vector<FormData> items;
  14532. content_reader(
  14533. [&](const FormData &file) {
  14534. items.push_back(file);
  14535. return true;
  14536. },
  14537. [&](const char *data, size_t data_length) {
  14538. items.back().content.append(data, data_length);
  14539. return true;
  14540. });
  14541. ASSERT_TRUE(items.size() == 2);
  14542. EXPECT_EQ(items[0].name, "name3");
  14543. EXPECT_EQ(items[0].content, rand1);
  14544. EXPECT_EQ(items[0].filename, "filename3");
  14545. EXPECT_EQ(items[0].content_type, "");
  14546. EXPECT_EQ(items[1].name, "name4");
  14547. EXPECT_EQ(items[1].content, rand2);
  14548. EXPECT_EQ(items[1].filename, "filename4");
  14549. EXPECT_EQ(items[1].content_type, "");
  14550. });
  14551. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14552. const ContentReader &content_reader) {
  14553. ASSERT_TRUE(req.is_multipart_form_data());
  14554. std::vector<FormData> items;
  14555. content_reader(
  14556. [&](const FormData &file) {
  14557. items.push_back(file);
  14558. return true;
  14559. },
  14560. [&](const char *data, size_t data_length) {
  14561. items.back().content.append(data, data_length);
  14562. return true;
  14563. });
  14564. ASSERT_TRUE(items.size() == 4);
  14565. EXPECT_EQ(std::string(items[0].name), "name1");
  14566. EXPECT_EQ(items[0].content, "Testing123");
  14567. EXPECT_EQ(items[0].filename, "filename1");
  14568. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14569. EXPECT_EQ(items[1].name, "name2");
  14570. EXPECT_EQ(items[1].content, "Testing456");
  14571. EXPECT_EQ(items[1].filename, "");
  14572. EXPECT_EQ(items[1].content_type, "");
  14573. EXPECT_EQ(items[2].name, "name3");
  14574. EXPECT_EQ(items[2].content, rand1);
  14575. EXPECT_EQ(items[2].filename, "filename3");
  14576. EXPECT_EQ(items[2].content_type, "");
  14577. EXPECT_EQ(items[3].name, "name4");
  14578. EXPECT_EQ(items[3].content, rand2);
  14579. EXPECT_EQ(items[3].filename, "filename4");
  14580. EXPECT_EQ(items[3].content_type, "");
  14581. });
  14582. auto port = svr.bind_to_any_port("localhost");
  14583. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14584. auto se = detail::scope_exit([&] {
  14585. svr.stop();
  14586. t.join();
  14587. ASSERT_FALSE(svr.is_running());
  14588. });
  14589. svr.wait_until_ready();
  14590. {
  14591. SSLClient cli("localhost", port);
  14592. cli.enable_server_certificate_verification(false);
  14593. UploadFormDataItems items{
  14594. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14595. {"name2", "Testing456", "", ""}, // not a file
  14596. };
  14597. {
  14598. auto res = cli.Post("/post-none", {}, {}, {});
  14599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14600. ASSERT_EQ(StatusCode::OK_200, res->status);
  14601. }
  14602. FormDataProviderItems providers;
  14603. {
  14604. auto res =
  14605. cli.Post("/post-items", {}, items, providers); // empty providers
  14606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14607. ASSERT_EQ(StatusCode::OK_200, res->status);
  14608. }
  14609. providers.push_back({"name3",
  14610. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14611. // test the offset is given correctly at each step
  14612. if (!offset)
  14613. sink.os.write(rand1.data(), 30);
  14614. else if (offset == 30)
  14615. sink.os.write(rand1.data() + 30, 300);
  14616. else if (offset == 330)
  14617. sink.os.write(rand1.data() + 330, 670);
  14618. else if (offset == rand1.size())
  14619. sink.done();
  14620. return true;
  14621. },
  14622. "filename3",
  14623. {}});
  14624. providers.push_back({"name4",
  14625. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14626. // test the offset is given correctly at each step
  14627. if (!offset)
  14628. sink.os.write(rand2.data(), 2000);
  14629. else if (offset == 2000)
  14630. sink.os.write(rand2.data() + 2000, 1);
  14631. else if (offset == 2001)
  14632. sink.os.write(rand2.data() + 2001, 999);
  14633. else if (offset == rand2.size())
  14634. sink.done();
  14635. return true;
  14636. },
  14637. "filename4",
  14638. {}});
  14639. {
  14640. auto res = cli.Post("/post-providers", {}, {}, providers);
  14641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14642. ASSERT_EQ(StatusCode::OK_200, res->status);
  14643. }
  14644. {
  14645. auto res = cli.Post("/post-both", {}, items, providers);
  14646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14647. ASSERT_EQ(StatusCode::OK_200, res->status);
  14648. }
  14649. }
  14650. }
  14651. TEST(MultipartFormDataTest, BadHeader) {
  14652. Server svr;
  14653. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14654. res.set_content("ok", "text/plain");
  14655. });
  14656. thread t = thread([&] { svr.listen(HOST, PORT); });
  14657. auto se = detail::scope_exit([&] {
  14658. svr.stop();
  14659. t.join();
  14660. ASSERT_FALSE(svr.is_running());
  14661. });
  14662. svr.wait_until_ready();
  14663. const std::string body =
  14664. "This is the preamble. It is to be ignored, though it\r\n"
  14665. "is a handy place for composition agents to include an\r\n"
  14666. "explanatory note to non-MIME conformant readers.\r\n"
  14667. "\r\n"
  14668. "\r\n"
  14669. "--simple boundary\r\n"
  14670. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14671. ": BAD...\r\n"
  14672. "\r\n"
  14673. "value1\r\n"
  14674. "--simple boundary\r\n"
  14675. "Content-Disposition: form-data; name=\"field2\"; "
  14676. "filename=\"example.txt\"\r\n"
  14677. "\r\n"
  14678. "value2\r\n"
  14679. "--simple boundary--\r\n"
  14680. "This is the epilogue. It is also to be ignored.\r\n";
  14681. std::string content_type =
  14682. R"(multipart/form-data; boundary="simple boundary")";
  14683. Client cli(HOST, PORT);
  14684. auto res = cli.Post("/post", body, content_type.c_str());
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14687. }
  14688. TEST(MultipartFormDataTest, WithPreamble) {
  14689. Server svr;
  14690. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14691. res.set_content("ok", "text/plain");
  14692. });
  14693. thread t = thread([&] { svr.listen(HOST, PORT); });
  14694. auto se = detail::scope_exit([&] {
  14695. svr.stop();
  14696. t.join();
  14697. ASSERT_FALSE(svr.is_running());
  14698. });
  14699. svr.wait_until_ready();
  14700. const std::string body =
  14701. "This is the preamble. It is to be ignored, though it\r\n"
  14702. "is a handy place for composition agents to include an\r\n"
  14703. "explanatory note to non-MIME conformant readers.\r\n"
  14704. "\r\n"
  14705. "\r\n"
  14706. "--simple boundary\r\n"
  14707. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14708. "\r\n"
  14709. "value1\r\n"
  14710. "--simple boundary\r\n"
  14711. "Content-Disposition: form-data; name=\"field2\"; "
  14712. "filename=\"example.txt\"\r\n"
  14713. "\r\n"
  14714. "value2\r\n"
  14715. "--simple boundary--\r\n"
  14716. "This is the epilogue. It is also to be ignored.\r\n";
  14717. std::string content_type =
  14718. R"(multipart/form-data; boundary="simple boundary")";
  14719. Client cli(HOST, PORT);
  14720. auto res = cli.Post("/post", body, content_type.c_str());
  14721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14722. EXPECT_EQ(StatusCode::OK_200, res->status);
  14723. }
  14724. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14726. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14727. const ContentReader &content_reader) {
  14728. if (req.is_multipart_form_data()) {
  14729. std::vector<FormData> items;
  14730. content_reader(
  14731. [&](const FormData &file) {
  14732. items.push_back(file);
  14733. return true;
  14734. },
  14735. [&](const char *data, size_t data_length) {
  14736. items.back().content.append(data, data_length);
  14737. return true;
  14738. });
  14739. EXPECT_TRUE(std::string(items[0].name) == "document");
  14740. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14741. EXPECT_TRUE(items[0].filename == "2MB_data");
  14742. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14743. EXPECT_TRUE(items[1].name == "hello");
  14744. EXPECT_TRUE(items[1].content == "world");
  14745. EXPECT_TRUE(items[1].filename == "");
  14746. EXPECT_TRUE(items[1].content_type == "");
  14747. } else {
  14748. std::string body;
  14749. content_reader([&](const char *data, size_t data_length) {
  14750. body.append(data, data_length);
  14751. return true;
  14752. });
  14753. }
  14754. });
  14755. auto port = svr.bind_to_any_port("localhost");
  14756. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14757. auto se = detail::scope_exit([&] {
  14758. svr.stop();
  14759. t.join();
  14760. ASSERT_FALSE(svr.is_running());
  14761. });
  14762. svr.wait_until_ready();
  14763. {
  14764. std::string data(1024 * 1024 * 2, '.');
  14765. std::stringstream buffer;
  14766. buffer << data;
  14767. SSLClient cli("localhost", port);
  14768. cli.enable_server_certificate_verification(false);
  14769. UploadFormDataItems items{
  14770. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14771. {"hello", "world", "", ""},
  14772. };
  14773. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14775. ASSERT_EQ(StatusCode::OK_200, res->status);
  14776. }
  14777. }
  14778. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14779. std::string data(1024 * 1024 * 2, '&');
  14780. std::stringstream buffer;
  14781. buffer << data;
  14782. Client cli("https://localhost:8080");
  14783. UploadFormDataItems items{
  14784. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14785. {"hello", "world", "", ""},
  14786. };
  14787. for (const char &c : " \t\r\n") {
  14788. auto res =
  14789. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14790. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14791. ASSERT_FALSE(res);
  14792. }
  14793. }
  14794. TEST(MultipartFormDataTest, PutFormData) {
  14795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14796. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14797. const ContentReader &content_reader) {
  14798. if (req.is_multipart_form_data()) {
  14799. std::vector<FormData> items;
  14800. content_reader(
  14801. [&](const FormData &file) {
  14802. items.push_back(file);
  14803. return true;
  14804. },
  14805. [&](const char *data, size_t data_length) {
  14806. items.back().content.append(data, data_length);
  14807. return true;
  14808. });
  14809. EXPECT_TRUE(std::string(items[0].name) == "document");
  14810. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14811. EXPECT_TRUE(items[0].filename == "2MB_data");
  14812. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14813. EXPECT_TRUE(items[1].name == "hello");
  14814. EXPECT_TRUE(items[1].content == "world");
  14815. EXPECT_TRUE(items[1].filename == "");
  14816. EXPECT_TRUE(items[1].content_type == "");
  14817. } else {
  14818. std::string body;
  14819. content_reader([&](const char *data, size_t data_length) {
  14820. body.append(data, data_length);
  14821. return true;
  14822. });
  14823. }
  14824. });
  14825. auto port = svr.bind_to_any_port("localhost");
  14826. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14827. auto se = detail::scope_exit([&] {
  14828. svr.stop();
  14829. t.join();
  14830. ASSERT_FALSE(svr.is_running());
  14831. });
  14832. svr.wait_until_ready();
  14833. {
  14834. std::string data(1024 * 1024 * 2, '&');
  14835. std::stringstream buffer;
  14836. buffer << data;
  14837. SSLClient cli("localhost", port);
  14838. cli.enable_server_certificate_verification(false);
  14839. UploadFormDataItems items{
  14840. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14841. {"hello", "world", "", ""},
  14842. };
  14843. auto res = cli.Put("/put", items);
  14844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14845. ASSERT_EQ(StatusCode::OK_200, res->status);
  14846. }
  14847. }
  14848. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14850. svr.Put("/put_customboundary",
  14851. [&](const Request &req, const Response & /*res*/,
  14852. const ContentReader &content_reader) {
  14853. if (req.is_multipart_form_data()) {
  14854. std::vector<FormData> items;
  14855. content_reader(
  14856. [&](const FormData &file) {
  14857. items.push_back(file);
  14858. return true;
  14859. },
  14860. [&](const char *data, size_t data_length) {
  14861. items.back().content.append(data, data_length);
  14862. return true;
  14863. });
  14864. EXPECT_TRUE(std::string(items[0].name) == "document");
  14865. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14866. EXPECT_TRUE(items[0].filename == "2MB_data");
  14867. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14868. EXPECT_TRUE(items[1].name == "hello");
  14869. EXPECT_TRUE(items[1].content == "world");
  14870. EXPECT_TRUE(items[1].filename == "");
  14871. EXPECT_TRUE(items[1].content_type == "");
  14872. } else {
  14873. std::string body;
  14874. content_reader([&](const char *data, size_t data_length) {
  14875. body.append(data, data_length);
  14876. return true;
  14877. });
  14878. }
  14879. });
  14880. auto port = svr.bind_to_any_port("localhost");
  14881. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14882. auto se = detail::scope_exit([&] {
  14883. svr.stop();
  14884. t.join();
  14885. ASSERT_FALSE(svr.is_running());
  14886. });
  14887. svr.wait_until_ready();
  14888. {
  14889. std::string data(1024 * 1024 * 2, '&');
  14890. std::stringstream buffer;
  14891. buffer << data;
  14892. SSLClient cli("localhost", port);
  14893. cli.enable_server_certificate_verification(false);
  14894. UploadFormDataItems items{
  14895. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14896. {"hello", "world", "", ""},
  14897. };
  14898. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14900. ASSERT_EQ(StatusCode::OK_200, res->status);
  14901. }
  14902. }
  14903. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14904. std::string data(1024 * 1024 * 2, '&');
  14905. std::stringstream buffer;
  14906. buffer << data;
  14907. Client cli("https://localhost:8080");
  14908. cli.enable_server_certificate_verification(false);
  14909. UploadFormDataItems items{
  14910. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14911. {"hello", "world", "", ""},
  14912. };
  14913. for (const char &c : " \t\r\n") {
  14914. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14915. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14916. ASSERT_FALSE(res);
  14917. }
  14918. }
  14919. TEST(MultipartFormDataTest, AlternateFilename) {
  14920. auto handled = false;
  14921. Server svr;
  14922. svr.Post("/test", [&](const Request &req, Response &res) {
  14923. ASSERT_EQ(2u, req.form.files.size());
  14924. ASSERT_EQ(1u, req.form.fields.size());
  14925. // Test files
  14926. const auto &file1 = req.form.get_file("file1");
  14927. ASSERT_EQ("file1", file1.name);
  14928. ASSERT_EQ("A.txt", file1.filename);
  14929. ASSERT_EQ("text/plain", file1.content_type);
  14930. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14931. const auto &file2 = req.form.get_file("file2");
  14932. ASSERT_EQ("file2", file2.name);
  14933. ASSERT_EQ("a.html", file2.filename);
  14934. ASSERT_EQ("text/html", file2.content_type);
  14935. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14936. file2.content);
  14937. // Test text field
  14938. const auto &text = req.form.get_field("text");
  14939. ASSERT_EQ("text default", text);
  14940. res.set_content("ok", "text/plain");
  14941. handled = true;
  14942. });
  14943. thread t = thread([&] { svr.listen(HOST, PORT); });
  14944. auto se = detail::scope_exit([&] {
  14945. svr.stop();
  14946. t.join();
  14947. ASSERT_FALSE(svr.is_running());
  14948. ASSERT_TRUE(handled);
  14949. });
  14950. svr.wait_until_ready();
  14951. auto req = "POST /test HTTP/1.1\r\n"
  14952. "Host: localhost\r\n"
  14953. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14954. "Content-Length: 399\r\n"
  14955. "\r\n"
  14956. "----------\r\n"
  14957. "Content-Disposition: form-data; name=\"text\"\r\n"
  14958. "\r\n"
  14959. "text default\r\n"
  14960. "----------\r\n"
  14961. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14962. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14963. "Content-Type: text/plain\r\n"
  14964. "\r\n"
  14965. "Content of a.txt.\r\n"
  14966. "\r\n"
  14967. "----------\r\n"
  14968. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14969. "\"a.html\"\r\n"
  14970. "Content-Type: text/html\r\n"
  14971. "\r\n"
  14972. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14973. "\r\n"
  14974. "------------\r\n";
  14975. ASSERT_TRUE(send_request(1, req));
  14976. }
  14977. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14978. auto handled = false;
  14979. Server svr;
  14980. svr.Post("/test", [&](const Request &req, Response &res) {
  14981. // Case-insensitive "utf-8''" prefix with a long value
  14982. const auto &file = req.form.get_file("file1");
  14983. ASSERT_EQ("file1", file.name);
  14984. // 8000 chars exercises both the Content-Disposition parser and the
  14985. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14986. // Prior to the fix, std::regex_match on this header would cause O(N)
  14987. // stack recursion in libstdc++, leading to SIGSEGV.
  14988. std::string expected_filename(8000, 'A');
  14989. ASSERT_EQ(expected_filename, file.filename);
  14990. res.set_content("ok", "text/plain");
  14991. handled = true;
  14992. });
  14993. thread t = thread([&] { svr.listen(HOST, PORT); });
  14994. auto se = detail::scope_exit([&] {
  14995. svr.stop();
  14996. t.join();
  14997. ASSERT_FALSE(svr.is_running());
  14998. ASSERT_TRUE(handled);
  14999. });
  15000. svr.wait_until_ready();
  15001. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15002. // Regression test for GHSA-qq6v-r583-3h69
  15003. std::string long_filename(8000, 'A');
  15004. std::string body = "----------\r\n"
  15005. "Content-Disposition: form-data; name=\"file1\"; "
  15006. "filename*=\"Utf-8''" +
  15007. long_filename +
  15008. "\"\r\n"
  15009. "\r\n"
  15010. "hello\r\n"
  15011. "------------\r\n";
  15012. auto req = "POST /test HTTP/1.1\r\n"
  15013. "Host: localhost\r\n"
  15014. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15015. "Content-Length: " +
  15016. std::to_string(body.size()) + "\r\n\r\n" + body;
  15017. ASSERT_TRUE(send_request(1, req));
  15018. }
  15019. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15020. auto handled = false;
  15021. Server svr;
  15022. svr.Post("/test", [&](const Request &req, Response &) {
  15023. ASSERT_EQ(2u, req.form.fields.size());
  15024. const auto &text1 = req.form.get_field("text1");
  15025. ASSERT_EQ("text1", text1);
  15026. const auto &text2 = req.form.get_field("text2");
  15027. ASSERT_EQ("text2", text2);
  15028. handled = true;
  15029. });
  15030. thread t = thread([&] { svr.listen(HOST, PORT); });
  15031. auto se = detail::scope_exit([&] {
  15032. svr.stop();
  15033. t.join();
  15034. ASSERT_FALSE(svr.is_running());
  15035. ASSERT_TRUE(handled);
  15036. });
  15037. svr.wait_until_ready();
  15038. auto req = "POST /test HTTP/1.1\r\n"
  15039. "Host: localhost\r\n"
  15040. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15041. "Content-Length: 146\r\n"
  15042. "\r\n----------\r\n"
  15043. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15044. "\r\n"
  15045. "text1"
  15046. "\r\n----------\r\n"
  15047. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15048. "\r\n"
  15049. "text2"
  15050. "\r\n------------";
  15051. std::string response;
  15052. ASSERT_TRUE(send_request(1, req, &response));
  15053. ASSERT_EQ("200", response.substr(9, 3));
  15054. }
  15055. TEST(MultipartFormDataTest, ContentLength) {
  15056. auto handled = false;
  15057. Server svr;
  15058. svr.Post("/test", [&](const Request &req, Response &) {
  15059. ASSERT_EQ(2u, req.form.fields.size());
  15060. const auto &text1 = req.form.get_field("text1");
  15061. ASSERT_EQ("text1", text1);
  15062. const auto &text2 = req.form.get_field("text2");
  15063. ASSERT_EQ("text2", text2);
  15064. handled = true;
  15065. });
  15066. thread t = thread([&] { svr.listen(HOST, PORT); });
  15067. auto se = detail::scope_exit([&] {
  15068. svr.stop();
  15069. t.join();
  15070. ASSERT_FALSE(svr.is_running());
  15071. ASSERT_TRUE(handled);
  15072. });
  15073. svr.wait_until_ready();
  15074. auto req = "POST /test HTTP/1.1\r\n"
  15075. "Host: localhost\r\n"
  15076. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15077. "Content-Length: 167\r\n"
  15078. "\r\n----------\r\n"
  15079. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15080. "Content-Length: 5\r\n"
  15081. "\r\n"
  15082. "text1"
  15083. "\r\n----------\r\n"
  15084. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15085. "\r\n"
  15086. "text2"
  15087. "\r\n------------\r\n";
  15088. std::string response;
  15089. ASSERT_TRUE(send_request(1, req, &response));
  15090. ASSERT_EQ("200", response.substr(9, 3));
  15091. }
  15092. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15093. auto handled = false;
  15094. Server svr;
  15095. svr.Post("/test", [&](const Request &req, Response &) {
  15096. ASSERT_EQ(2u, req.form.fields.size());
  15097. const auto &text1 = req.form.get_field("text1");
  15098. ASSERT_EQ("text1", text1);
  15099. // TODO: Add header access for text fields if needed
  15100. const auto &text2 = req.form.get_field("text2");
  15101. ASSERT_EQ("text2", text2);
  15102. // TODO: Header access for text fields needs to be implemented
  15103. // auto &headers = it->second.headers;
  15104. // ASSERT_EQ(3U, headers.size());
  15105. // auto custom_header = headers.find("x-whatever");
  15106. // ASSERT_TRUE(custom_header != headers.end());
  15107. // ASSERT_NE("customvalue", custom_header->second);
  15108. // ASSERT_EQ("CustomValue", custom_header->second);
  15109. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15110. handled = true;
  15111. });
  15112. thread t = thread([&] { svr.listen(HOST, PORT); });
  15113. auto se = detail::scope_exit([&] {
  15114. svr.stop();
  15115. t.join();
  15116. ASSERT_FALSE(svr.is_running());
  15117. ASSERT_TRUE(handled);
  15118. });
  15119. svr.wait_until_ready();
  15120. auto req = "POST /test HTTP/1.1\r\n"
  15121. "Host: localhost\r\n"
  15122. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15123. "Content-Length: 232\r\n"
  15124. "\r\n----------\r\n"
  15125. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15126. "Content-Length: 5\r\n"
  15127. "X-Test: 1\r\n"
  15128. "\r\n"
  15129. "text1"
  15130. "\r\n----------\r\n"
  15131. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15132. "Content-Type: text/plain\r\n"
  15133. "X-Whatever: CustomValue\r\n"
  15134. "\r\n"
  15135. "text2"
  15136. "\r\n------------\r\n"
  15137. "That should be disregarded. Not even read";
  15138. std::string response;
  15139. ASSERT_TRUE(send_request(1, req, &response));
  15140. ASSERT_EQ("200", response.substr(9, 3));
  15141. }
  15142. TEST(MultipartFormDataTest, LargeHeader) {
  15143. auto handled = false;
  15144. Server svr;
  15145. svr.Post("/test", [&](const Request &req, Response &) {
  15146. ASSERT_EQ(1u, req.form.fields.size());
  15147. const auto &text = req.form.get_field("name1");
  15148. ASSERT_EQ("text1", text);
  15149. handled = true;
  15150. });
  15151. thread t = thread([&] { svr.listen(HOST, PORT); });
  15152. auto se = detail::scope_exit([&] {
  15153. svr.stop();
  15154. t.join();
  15155. ASSERT_FALSE(svr.is_running());
  15156. ASSERT_TRUE(handled);
  15157. });
  15158. svr.wait_until_ready();
  15159. auto boundary = std::string("cpp-httplib-multipart-data");
  15160. std::string content = "--" + boundary +
  15161. "\r\n"
  15162. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15163. "\r\n"
  15164. "text1\r\n"
  15165. "--" +
  15166. boundary + "--\r\n";
  15167. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15168. "Host: localhost\r\n"
  15169. "Content-Type: multipart/form-data;boundary=" +
  15170. boundary +
  15171. "\r\n"
  15172. "Content-Length: " +
  15173. std::to_string(content.size()) +
  15174. "\r\n"
  15175. "Dummy-Header: ";
  15176. std::string header_suffix = "\r\n"
  15177. "\r\n";
  15178. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15179. size_t header_dummy_size =
  15180. read_buff_size -
  15181. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15182. auto header_dummy = std::string(header_dummy_size, '@');
  15183. auto req = header_prefix + header_dummy + header_suffix + content;
  15184. std::string response;
  15185. ASSERT_TRUE(send_request(1, req, &response));
  15186. ASSERT_EQ("200", response.substr(9, 3));
  15187. }
  15188. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15189. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15190. // (not chunked Transfer-Encoding) after the streaming refactor.
  15191. auto handled = false;
  15192. Server svr;
  15193. svr.Post("/upload", [&](const Request &req, Response &res) {
  15194. auto cl_it = req.headers.find("Content-Length");
  15195. EXPECT_TRUE(cl_it != req.headers.end());
  15196. auto te_it = req.headers.find("Transfer-Encoding");
  15197. EXPECT_TRUE(te_it == req.headers.end());
  15198. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15199. res.set_content("ok", "text/plain");
  15200. handled = true;
  15201. });
  15202. auto port = svr.bind_to_any_port(HOST);
  15203. auto t = thread([&] { svr.listen_after_bind(); });
  15204. auto se = detail::scope_exit([&] {
  15205. svr.stop();
  15206. t.join();
  15207. ASSERT_FALSE(svr.is_running());
  15208. ASSERT_TRUE(handled);
  15209. });
  15210. svr.wait_until_ready();
  15211. UploadFormDataItems items = {
  15212. {"field1", "hello", "", "text/plain"},
  15213. {"file1", "world", "test.txt", "application/octet-stream"},
  15214. };
  15215. Client cli(HOST, port);
  15216. auto res = cli.Post("/upload", {}, items);
  15217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15218. EXPECT_EQ(StatusCode::OK_200, res->status);
  15219. }
  15220. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15221. // Verify that make_multipart_content_provider coalesces many small segments
  15222. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15223. constexpr size_t kItemCount = 1000;
  15224. UploadFormDataItems items;
  15225. items.reserve(kItemCount);
  15226. for (size_t i = 0; i < kItemCount; i++) {
  15227. items.push_back(
  15228. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15229. }
  15230. const std::string boundary = "----test-boundary";
  15231. auto content_length = detail::get_multipart_content_length(items, boundary);
  15232. auto provider = detail::make_multipart_content_provider(items, boundary);
  15233. // Drive the provider the same way write_content_with_progress does
  15234. size_t write_count = 0;
  15235. size_t total_bytes = 0;
  15236. DataSink sink;
  15237. size_t offset = 0;
  15238. sink.write = [&](const char *d, size_t l) -> bool {
  15239. (void)d;
  15240. write_count++;
  15241. total_bytes += l;
  15242. offset += l;
  15243. return true;
  15244. };
  15245. sink.is_writable = []() -> bool { return true; };
  15246. while (offset < content_length) {
  15247. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15248. }
  15249. EXPECT_EQ(content_length, total_bytes);
  15250. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15251. // With buffering into 64KB blocks, write_count should be much smaller.
  15252. auto segment_count = 3 * kItemCount + 1;
  15253. EXPECT_LT(write_count, segment_count / 10);
  15254. }
  15255. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15256. // Integration test: send many UploadFormDataItems and verify the server
  15257. // receives all of them correctly (#2410).
  15258. constexpr size_t kItemCount = 500;
  15259. auto handled = false;
  15260. Server svr;
  15261. svr.Post("/upload", [&](const Request &req, Response &res) {
  15262. EXPECT_EQ(kItemCount, req.form.fields.size());
  15263. for (size_t i = 0; i < kItemCount; i++) {
  15264. auto key = "field" + std::to_string(i);
  15265. auto val = "value" + std::to_string(i);
  15266. auto it = req.form.fields.find(key);
  15267. if (it != req.form.fields.end()) {
  15268. EXPECT_EQ(val, it->second.content);
  15269. } else {
  15270. ADD_FAILURE() << "Missing field: " << key;
  15271. }
  15272. }
  15273. res.set_content("ok", "text/plain");
  15274. handled = true;
  15275. });
  15276. auto port = svr.bind_to_any_port(HOST);
  15277. auto t = thread([&] { svr.listen_after_bind(); });
  15278. auto se = detail::scope_exit([&] {
  15279. svr.stop();
  15280. t.join();
  15281. ASSERT_FALSE(svr.is_running());
  15282. ASSERT_TRUE(handled);
  15283. });
  15284. svr.wait_until_ready();
  15285. UploadFormDataItems items;
  15286. items.reserve(kItemCount);
  15287. for (size_t i = 0; i < kItemCount; i++) {
  15288. items.push_back(
  15289. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15290. }
  15291. Client cli(HOST, port);
  15292. auto res = cli.Post("/upload", items);
  15293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15294. EXPECT_EQ(StatusCode::OK_200, res->status);
  15295. }
  15296. TEST(MultipartFormDataTest, MakeFileProvider) {
  15297. // Verify make_file_provider sends a file's contents correctly.
  15298. const std::string file_content(4096, 'Z');
  15299. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15300. {
  15301. std::ofstream ofs(tmp_path, std::ios::binary);
  15302. ofs.write(file_content.data(),
  15303. static_cast<std::streamsize>(file_content.size()));
  15304. }
  15305. auto handled = false;
  15306. Server svr;
  15307. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15308. const ContentReader &content_reader) {
  15309. ASSERT_TRUE(req.is_multipart_form_data());
  15310. std::vector<FormData> items;
  15311. content_reader(
  15312. [&](const FormData &file) {
  15313. items.push_back(file);
  15314. return true;
  15315. },
  15316. [&](const char *data, size_t data_length) {
  15317. items.back().content.append(data, data_length);
  15318. return true;
  15319. });
  15320. ASSERT_EQ(1u, items.size());
  15321. EXPECT_EQ("myfile", items[0].name);
  15322. EXPECT_EQ("data.bin", items[0].filename);
  15323. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15324. EXPECT_EQ(file_content, items[0].content);
  15325. handled = true;
  15326. });
  15327. auto port = svr.bind_to_any_port(HOST);
  15328. auto t = thread([&] { svr.listen_after_bind(); });
  15329. auto se = detail::scope_exit([&] {
  15330. svr.stop();
  15331. t.join();
  15332. ASSERT_FALSE(svr.is_running());
  15333. ASSERT_TRUE(handled);
  15334. std::remove(tmp_path.c_str());
  15335. });
  15336. svr.wait_until_ready();
  15337. FormDataProviderItems providers;
  15338. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15339. "application/octet-stream"));
  15340. Client cli(HOST, port);
  15341. auto res = cli.Post("/upload", {}, {}, providers);
  15342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15343. EXPECT_EQ(StatusCode::OK_200, res->status);
  15344. }
  15345. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15346. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15347. // (100) headers is rejected with a 400 Bad Request response.
  15348. Server svr;
  15349. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15350. res.set_content("ok", "text/plain");
  15351. });
  15352. thread t = thread([&] { svr.listen(HOST, PORT); });
  15353. auto se = detail::scope_exit([&] {
  15354. svr.stop();
  15355. t.join();
  15356. ASSERT_FALSE(svr.is_running());
  15357. });
  15358. svr.wait_until_ready();
  15359. // Build a multipart part with 101 custom headers (exceeding
  15360. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15361. std::stringstream body;
  15362. body << "--simpleboundary\r\n"
  15363. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15364. for (int i = 0; i < 101; i++) {
  15365. body << "X-Custom-Header-" << i << ": value\r\n";
  15366. }
  15367. body << "\r\n"
  15368. << "value1\r\n"
  15369. << "--simpleboundary--\r\n";
  15370. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15371. Client cli(HOST, PORT);
  15372. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15375. }
  15376. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15377. // A body that never contains the declared boundary must not be accumulated
  15378. // while the parser waits for it. Buffering it would also make every read
  15379. // rescan everything seen so far, which is quadratic in the body size.
  15380. Server svr;
  15381. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15382. res.set_content("ok", "text/plain");
  15383. });
  15384. auto port = svr.bind_to_any_port(HOST);
  15385. thread t = thread([&] { svr.listen_after_bind(); });
  15386. auto se = detail::scope_exit([&] {
  15387. svr.stop();
  15388. t.join();
  15389. ASSERT_FALSE(svr.is_running());
  15390. });
  15391. svr.wait_until_ready();
  15392. Client cli(HOST, port);
  15393. cli.set_read_timeout(60, 0);
  15394. cli.set_write_timeout(60, 0);
  15395. // '-' is the worst case: it matches the first character of the boundary, so
  15396. // every position has to be checked against it.
  15397. auto post_dashes = [&](size_t size) {
  15398. const std::string body(size, '-');
  15399. auto start = std::chrono::steady_clock::now();
  15400. auto res =
  15401. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15402. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15403. std::chrono::steady_clock::now() - start)
  15404. .count();
  15405. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15406. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15407. return ms;
  15408. };
  15409. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15410. // Windows.
  15411. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15412. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15413. // Comparing the two sizes rather than checking an absolute duration keeps
  15414. // this meaningful across build types and CI load, both of which move the
  15415. // absolute numbers by more than an order of magnitude. Four times the bytes
  15416. // costs about four times the time when parsing is linear, and about sixteen
  15417. // times when the body is buffered and rescanned.
  15418. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15419. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15420. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15421. << "ms, which suggests the body is being buffered and rescanned";
  15422. }
  15423. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15424. // A boundary can only be followed by CRLF or by "--", so anything else is
  15425. // malformed no matter what comes next. The parser must say so right away
  15426. // instead of buffering the rest of the declared body.
  15427. Server svr;
  15428. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15429. res.set_content("ok", "text/plain");
  15430. });
  15431. auto port = svr.bind_to_any_port(HOST);
  15432. thread t = thread([&] { svr.listen_after_bind(); });
  15433. auto se = detail::scope_exit([&] {
  15434. svr.stop();
  15435. t.join();
  15436. ASSERT_FALSE(svr.is_running());
  15437. });
  15438. svr.wait_until_ready();
  15439. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15440. // buffers instead of failing would still be waiting for the remaining bytes.
  15441. const std::string body = "--zzzz\r\n"
  15442. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15443. "\r\n"
  15444. "text1"
  15445. "\r\n--zzzzXX";
  15446. const std::string req = "POST /post HTTP/1.1\r\n"
  15447. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15448. "Content-Length: 1048576\r\n"
  15449. "\r\n" +
  15450. body;
  15451. std::string response;
  15452. ASSERT_TRUE(send_request(3, req, &response, port));
  15453. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15454. EXPECT_EQ("400", response.substr(9, 3));
  15455. }
  15456. // Posts a multipart body split into two writes, so that the server sees the
  15457. // split at whatever offset the caller chose, and expects the single "text1"
  15458. // field to come through.
  15459. static void expect_split_multipart_ok(const std::string &body1,
  15460. const std::string &body2) {
  15461. auto handled = false;
  15462. Server svr;
  15463. svr.Post("/post", [&](const Request &req, Response &) {
  15464. EXPECT_EQ(1u, req.form.fields.size());
  15465. EXPECT_EQ("text1", req.form.get_field("text1"));
  15466. handled = true;
  15467. });
  15468. auto port = svr.bind_to_any_port(HOST);
  15469. thread t = thread([&] { svr.listen_after_bind(); });
  15470. auto se = detail::scope_exit([&] {
  15471. svr.stop();
  15472. t.join();
  15473. ASSERT_FALSE(svr.is_running());
  15474. ASSERT_TRUE(handled);
  15475. });
  15476. svr.wait_until_ready();
  15477. // "Connection: close" makes the server close once it has answered, so the
  15478. // response drain ends immediately instead of idling until the read timeout.
  15479. const std::string head =
  15480. "POST /post HTTP/1.1\r\n"
  15481. "Host: localhost\r\n"
  15482. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15483. "Connection: close\r\n"
  15484. "Content-Length: " +
  15485. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15486. std::string response;
  15487. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15488. ASSERT_GE(response.size(), 12u) << "no response";
  15489. EXPECT_EQ("200", response.substr(9, 3));
  15490. }
  15491. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15492. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15493. // ignored, including when it does not arrive in the same read as the
  15494. // close-delimiter itself.
  15495. expect_split_multipart_ok("--zzzz\r\n"
  15496. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15497. "\r\n"
  15498. "text1"
  15499. "\r\n--zzzz--",
  15500. "\r\nthis epilogue must be ignored\r\n");
  15501. }
  15502. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15503. // The initial boundary may be preceded by a preamble of any length and may
  15504. // straddle a read boundary. Discarding data while waiting for it must not
  15505. // throw away a partial boundary sitting at the end of the buffer.
  15506. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15507. "zz\r\n"
  15508. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15509. "\r\n"
  15510. "text1"
  15511. "\r\n--zzzz--\r\n");
  15512. }
  15513. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15514. // The received boundary was only checked for being non-empty, so it could be
  15515. // as long as a header is allowed to be. The parser scans the body for
  15516. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15517. // costs a nearly full comparison at nearly every position, making the
  15518. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15519. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15520. Server svr;
  15521. svr.Post("/post", [](const Request &req, Response &res) {
  15522. EXPECT_EQ(1u, req.form.fields.size());
  15523. EXPECT_EQ("text1", req.form.get_field("text1"));
  15524. res.set_content("ok", "text/plain");
  15525. });
  15526. auto port = svr.bind_to_any_port(HOST);
  15527. thread t = thread([&] { svr.listen_after_bind(); });
  15528. auto se = detail::scope_exit([&] {
  15529. svr.stop();
  15530. t.join();
  15531. ASSERT_FALSE(svr.is_running());
  15532. });
  15533. svr.wait_until_ready();
  15534. Client cli(HOST, port);
  15535. auto post_with_boundary_of_length = [&](size_t len) {
  15536. const std::string boundary(len, 'a');
  15537. const std::string body =
  15538. "--" + boundary +
  15539. "\r\n"
  15540. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15541. "\r\n"
  15542. "text1"
  15543. "\r\n--" +
  15544. boundary + "--\r\n";
  15545. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15546. };
  15547. auto res = post_with_boundary_of_length(70);
  15548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15549. EXPECT_EQ(StatusCode::OK_200, res->status);
  15550. res = post_with_boundary_of_length(71);
  15551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15552. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15553. }
  15554. TEST(MakeFileBodyTest, Basic) {
  15555. const std::string file_content(4096, 'Z');
  15556. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15557. {
  15558. std::ofstream ofs(tmp_path, std::ios::binary);
  15559. ofs.write(file_content.data(),
  15560. static_cast<std::streamsize>(file_content.size()));
  15561. }
  15562. auto handled = false;
  15563. Server svr;
  15564. svr.Post("/upload", [&](const Request &req, Response &res) {
  15565. EXPECT_EQ(file_content, req.body);
  15566. handled = true;
  15567. res.status = StatusCode::OK_200;
  15568. });
  15569. auto port = svr.bind_to_any_port(HOST);
  15570. auto t = thread([&] { svr.listen_after_bind(); });
  15571. auto se = detail::scope_exit([&] {
  15572. svr.stop();
  15573. t.join();
  15574. ASSERT_FALSE(svr.is_running());
  15575. ASSERT_TRUE(handled);
  15576. std::remove(tmp_path.c_str());
  15577. });
  15578. svr.wait_until_ready();
  15579. auto fb = make_file_body(tmp_path);
  15580. ASSERT_GT(fb.first, 0u);
  15581. Client cli(HOST, port);
  15582. auto res =
  15583. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15585. EXPECT_EQ(StatusCode::OK_200, res->status);
  15586. }
  15587. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15588. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15589. {
  15590. std::ofstream ofs(path, std::ios::binary);
  15591. const std::string content(100, 'A');
  15592. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15593. }
  15594. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15595. auto body = make_file_body(path);
  15596. ASSERT_EQ(100u, body.first);
  15597. ASSERT_TRUE(static_cast<bool>(body.second));
  15598. // Rewritten shorter after its length was measured - and, on a server, after
  15599. // that length has already gone out as Content-Length.
  15600. {
  15601. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15602. const std::string content(10, 'A');
  15603. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15604. }
  15605. std::string written;
  15606. DataSink sink;
  15607. sink.write = [&](const char *d, size_t l) {
  15608. written.append(d, l);
  15609. return true;
  15610. };
  15611. // The provider has to report failure. write_content_with_progress() advances
  15612. // its offset only by what was written, so a provider that returns true
  15613. // without completing the length it promised is called again straight away,
  15614. // and again.
  15615. EXPECT_FALSE(body.second(0, body.first, sink));
  15616. EXPECT_EQ(std::string(10, 'A'), written);
  15617. }
  15618. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15619. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15620. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15621. {
  15622. std::ofstream ofs(path, std::ios::binary);
  15623. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15624. }
  15625. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15626. auto body = make_file_body(path);
  15627. ASSERT_EQ(content.size(), body.first);
  15628. ASSERT_TRUE(static_cast<bool>(body.second));
  15629. std::string written;
  15630. DataSink sink;
  15631. sink.write = [&](const char *d, size_t l) {
  15632. written.append(d, l);
  15633. return true;
  15634. };
  15635. EXPECT_TRUE(body.second(0, body.first, sink));
  15636. EXPECT_EQ(content, written);
  15637. }
  15638. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15639. static constexpr unsigned int number_of_tasks{1000000};
  15640. std::atomic_uint count{0};
  15641. std::unique_ptr<TaskQueue> task_queue{
  15642. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15643. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15644. auto queued = task_queue->enqueue(
  15645. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15646. EXPECT_TRUE(queued);
  15647. }
  15648. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15649. task_queue->shutdown();
  15650. #else
  15651. EXPECT_NO_THROW(task_queue->shutdown());
  15652. #endif
  15653. EXPECT_EQ(number_of_tasks, count.load());
  15654. }
  15655. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15656. static constexpr unsigned int number_of_tasks{1000000};
  15657. static constexpr unsigned int qlimit{2};
  15658. unsigned int queued_count{0};
  15659. std::atomic_uint count{0};
  15660. std::unique_ptr<TaskQueue> task_queue{
  15661. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15662. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15663. if (task_queue->enqueue(
  15664. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15665. queued_count++;
  15666. }
  15667. }
  15668. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15669. task_queue->shutdown();
  15670. #else
  15671. EXPECT_NO_THROW(task_queue->shutdown());
  15672. #endif
  15673. EXPECT_EQ(queued_count, count.load());
  15674. EXPECT_TRUE(queued_count <= number_of_tasks);
  15675. EXPECT_TRUE(queued_count >= qlimit);
  15676. }
  15677. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15678. // Use a short idle timeout so a dynamic thread spawns, times out and
  15679. // exits during the test, and the pool keeps working afterwards.
  15680. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15681. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15682. /*idle_timeout_sec=*/1}};
  15683. std::atomic_uint count{0};
  15684. std::condition_variable cv;
  15685. std::mutex mtx;
  15686. bool release = false;
  15687. // Block the base thread so the second task spawns a dynamic thread.
  15688. EXPECT_TRUE(task_queue->enqueue([&] {
  15689. std::unique_lock<std::mutex> lock(mtx);
  15690. while (!release) {
  15691. cv.wait(lock);
  15692. }
  15693. count++;
  15694. }));
  15695. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15696. // Let the dynamic thread finish its task and exceed the idle timeout.
  15697. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15698. {
  15699. std::unique_lock<std::mutex> lock(mtx);
  15700. release = true;
  15701. }
  15702. cv.notify_all();
  15703. // The pool must still accept and run tasks after the dynamic thread exited.
  15704. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15705. task_queue->shutdown();
  15706. EXPECT_EQ(3u, count.load());
  15707. }
  15708. TEST(TaskQueueTest, MaxQueuedRequests) {
  15709. static constexpr unsigned int qlimit{3};
  15710. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15711. std::condition_variable sem_cv;
  15712. std::mutex sem_mtx;
  15713. int credits = 0;
  15714. bool queued;
  15715. /* Fill up the queue with tasks that will block until we give them credits to
  15716. * complete. */
  15717. for (unsigned int n = 0; n <= qlimit;) {
  15718. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15719. std::unique_lock<std::mutex> lock(sem_mtx);
  15720. while (credits <= 0) {
  15721. sem_cv.wait(lock);
  15722. }
  15723. /* Consume the credit and signal the test code if they are all gone. */
  15724. if (--credits == 0) { sem_cv.notify_one(); }
  15725. });
  15726. if (n < qlimit) {
  15727. /* The first qlimit enqueues must succeed. */
  15728. EXPECT_TRUE(queued);
  15729. } else {
  15730. /* The last one will succeed only when the worker thread
  15731. * starts and dequeues the first blocking task. Although
  15732. * not necessary for the correctness of this test, we sleep for
  15733. * a short while to avoid busy waiting. */
  15734. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15735. }
  15736. if (queued) { n++; }
  15737. }
  15738. /* Further enqueues must fail since the queue is full. */
  15739. for (auto i = 0; i < 4; i++) {
  15740. queued = task_queue->enqueue([] {});
  15741. EXPECT_FALSE(queued);
  15742. }
  15743. /* Give the credits to allow the previous tasks to complete. */
  15744. {
  15745. std::unique_lock<std::mutex> lock(sem_mtx);
  15746. credits += qlimit + 1;
  15747. }
  15748. sem_cv.notify_all();
  15749. /* Wait for all the credits to be consumed. */
  15750. {
  15751. std::unique_lock<std::mutex> lock(sem_mtx);
  15752. while (credits > 0) {
  15753. sem_cv.wait(lock);
  15754. }
  15755. }
  15756. /* Check that we are able again to enqueue at least qlimit tasks. */
  15757. for (unsigned int i = 0; i < qlimit; i++) {
  15758. queued = task_queue->enqueue([] {});
  15759. EXPECT_TRUE(queued);
  15760. }
  15761. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15762. task_queue->shutdown();
  15763. #else
  15764. EXPECT_NO_THROW(task_queue->shutdown());
  15765. #endif
  15766. }
  15767. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15768. Server svr;
  15769. std::string method;
  15770. std::string body;
  15771. auto has_content_length = false;
  15772. auto has_transfer_encoding = false;
  15773. std::atomic<int> bad_requests{0};
  15774. // Leftover body bytes get parsed as a malformed request and answered with
  15775. // 400
  15776. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15777. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15778. });
  15779. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15780. res.set_redirect("/down", StatusCode::SeeOther_303);
  15781. });
  15782. svr.Get("/down", [&](const Request &req, Response &res) {
  15783. method = req.method;
  15784. body = req.body;
  15785. has_content_length = req.has_header("Content-Length");
  15786. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15787. res.set_content("ok", "text/plain");
  15788. });
  15789. auto port = svr.bind_to_any_port(HOST);
  15790. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15791. auto se = detail::scope_exit([&] {
  15792. svr.stop();
  15793. thread.join();
  15794. ASSERT_FALSE(svr.is_running());
  15795. });
  15796. svr.wait_until_ready();
  15797. const std::string payload = "SECRET-BODY";
  15798. auto check = [&](Client &cli, const Result &res) {
  15799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15800. EXPECT_EQ(StatusCode::OK_200, res->status);
  15801. EXPECT_EQ("ok", res->body);
  15802. EXPECT_EQ("GET", method);
  15803. EXPECT_TRUE(body.empty());
  15804. EXPECT_FALSE(has_content_length);
  15805. EXPECT_FALSE(has_transfer_encoding);
  15806. // Nothing of the original body may be left on the connection
  15807. auto res2 = cli.Get("/down");
  15808. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15809. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15810. EXPECT_EQ("ok", res2->body);
  15811. EXPECT_EQ(0, bad_requests);
  15812. };
  15813. // With content length
  15814. {
  15815. Client cli(HOST, port);
  15816. cli.set_keep_alive(true);
  15817. cli.set_follow_location(true);
  15818. auto res = cli.Post(
  15819. "/up", payload.size(),
  15820. [&](size_t offset, size_t length, DataSink &sink) {
  15821. return sink.write(payload.data() + offset, length);
  15822. },
  15823. "text/plain");
  15824. check(cli, res);
  15825. }
  15826. // Without content length (chunked)
  15827. {
  15828. Client cli(HOST, port);
  15829. cli.set_keep_alive(true);
  15830. cli.set_follow_location(true);
  15831. auto res = cli.Post(
  15832. "/up",
  15833. [&](size_t /*offset*/, DataSink &sink) {
  15834. sink.write(payload.data(), payload.size());
  15835. sink.done();
  15836. return true;
  15837. },
  15838. "text/plain");
  15839. check(cli, res);
  15840. }
  15841. }
  15842. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15843. Server svr;
  15844. std::string target;
  15845. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15846. // Echo the still-encoded name back in the Location
  15847. const std::string prefix = "/start/";
  15848. res.status = StatusCode::Found_302;
  15849. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15850. });
  15851. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15852. target = req.target;
  15853. res.set_content("ok", "text/plain");
  15854. });
  15855. auto port = svr.bind_to_any_port(HOST);
  15856. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15857. auto se = detail::scope_exit([&] {
  15858. svr.stop();
  15859. thread.join();
  15860. ASSERT_FALSE(svr.is_running());
  15861. });
  15862. svr.wait_until_ready();
  15863. // Decoding the Location path would turn the first four into a path
  15864. // separator, a query delimiter, a fragment delimiter and a different
  15865. // percent-encoded octet. The rest must keep reaching the server as they are.
  15866. const std::vector<std::string> names = {
  15867. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15868. };
  15869. for (auto path_encode : {true, false}) {
  15870. Client cli(HOST, port);
  15871. cli.set_follow_location(true);
  15872. cli.set_path_encode(path_encode);
  15873. for (const auto &name : names) {
  15874. target.clear();
  15875. auto res = cli.Get("/start/" + name);
  15876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15877. EXPECT_EQ(StatusCode::OK_200, res->status);
  15878. EXPECT_EQ("/dest/" + name, target);
  15879. }
  15880. }
  15881. }
  15882. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15883. Server svr;
  15884. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15885. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15886. });
  15887. svr.Get("/hello", [](const Request &req, Response &res) {
  15888. res.set_content(req.get_param_value("key"), "text/plain");
  15889. });
  15890. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15891. auto se = detail::scope_exit([&] {
  15892. svr.stop();
  15893. thread.join();
  15894. ASSERT_FALSE(svr.is_running());
  15895. });
  15896. svr.wait_until_ready();
  15897. {
  15898. Client cli(HOST, PORT);
  15899. cli.set_follow_location(true);
  15900. auto res = cli.Get("/");
  15901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15902. EXPECT_EQ(StatusCode::OK_200, res->status);
  15903. EXPECT_EQ("val&key2=val2", res->body);
  15904. }
  15905. }
  15906. #endif
  15907. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15908. Server svr;
  15909. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15910. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15911. });
  15912. svr.Get("/hello", [](const Request &req, Response &res) {
  15913. res.set_content(req.get_param_value("key"), "text/plain");
  15914. });
  15915. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15916. auto se = detail::scope_exit([&] {
  15917. svr.stop();
  15918. thread.join();
  15919. ASSERT_FALSE(svr.is_running());
  15920. });
  15921. svr.wait_until_ready();
  15922. {
  15923. Client cli(HOST, PORT);
  15924. cli.set_follow_location(true);
  15925. auto res = cli.Get("/");
  15926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15927. EXPECT_EQ(StatusCode::OK_200, res->status);
  15928. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15929. }
  15930. }
  15931. TEST(RedirectTest, RedirectWithPlusInPath) {
  15932. Server svr;
  15933. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15934. res.set_redirect("/a+b");
  15935. });
  15936. // Route pattern uses regex; escape + as \\+
  15937. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15938. res.set_content(req.path, "text/plain");
  15939. });
  15940. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15941. auto se = detail::scope_exit([&] {
  15942. svr.stop();
  15943. thread.join();
  15944. ASSERT_FALSE(svr.is_running());
  15945. });
  15946. svr.wait_until_ready();
  15947. {
  15948. Client cli(HOST, PORT);
  15949. cli.set_follow_location(true);
  15950. auto res = cli.Get("/");
  15951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15952. EXPECT_EQ(StatusCode::OK_200, res->status);
  15953. EXPECT_EQ("/a+b", res->body);
  15954. }
  15955. }
  15956. TEST(RedirectTest, ResolveRelativeLocation) {
  15957. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15958. const std::vector<std::pair<std::string, std::string>> cases = {
  15959. {"g", "/b/c/g"},
  15960. {"./g", "/b/c/g"},
  15961. {"g/", "/b/c/g/"},
  15962. {"?y", "/b/c/d;p?y"},
  15963. {"g?y", "/b/c/g?y"},
  15964. {"#s", "/b/c/d;p?q#s"},
  15965. {"g#s", "/b/c/g#s"},
  15966. {"g?y#s", "/b/c/g?y#s"},
  15967. {";x", "/b/c/;x"},
  15968. {"g;x", "/b/c/g;x"},
  15969. {".", "/b/c/"},
  15970. {"./", "/b/c/"},
  15971. {"..", "/b/"},
  15972. {"../", "/b/"},
  15973. {"../g", "/b/g"},
  15974. {"../..", "/"},
  15975. {"../../", "/"},
  15976. {"../../g", "/g"},
  15977. {"../../../g", "/g"},
  15978. {"g.", "/b/c/g."},
  15979. {".g", "/b/c/.g"},
  15980. {"g..", "/b/c/g.."},
  15981. {"..g", "/b/c/..g"},
  15982. {"./../g", "/b/g"},
  15983. {"./g/.", "/b/c/g/"},
  15984. {"g/./h", "/b/c/g/h"},
  15985. {"g/../h", "/b/c/h"},
  15986. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15987. {"g;x=1/../y", "/b/c/y"},
  15988. {"g?y/./x", "/b/c/g?y/./x"},
  15989. {"g#s/../x", "/b/c/g#s/../x"},
  15990. // Not relative-path references, so left for parse_url.
  15991. {"/g", "/g"},
  15992. {"//g", "//g"},
  15993. {"http://g/x", "http://g/x"},
  15994. {"g:h", "g:h"},
  15995. };
  15996. for (const auto &c : cases) {
  15997. EXPECT_EQ(c.second,
  15998. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15999. << c.first;
  16000. }
  16001. }
  16002. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16003. Server svr;
  16004. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16005. res.set_redirect(req.get_param_value("to"));
  16006. });
  16007. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16008. res.set_content(req.target, "text/plain");
  16009. });
  16010. svr.Get("/other", [](const Request &req, Response &res) {
  16011. res.set_content(req.target, "text/plain");
  16012. });
  16013. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16014. auto se = detail::scope_exit([&] {
  16015. svr.stop();
  16016. thread.join();
  16017. ASSERT_FALSE(svr.is_running());
  16018. });
  16019. svr.wait_until_ready();
  16020. const std::vector<std::pair<std::string, std::string>> cases = {
  16021. {"next", "/dir/next"},
  16022. {"./next?x=1", "/dir/next?x=1"},
  16023. {"../other", "/other"},
  16024. };
  16025. for (const auto &c : cases) {
  16026. Client cli(HOST, PORT);
  16027. cli.set_follow_location(true);
  16028. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16029. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16030. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16031. EXPECT_EQ(c.second, res->body) << c.first;
  16032. }
  16033. }
  16034. #ifdef CPPHTTPLIB_SSL_ENABLED
  16035. TEST(RedirectTest, Issue2185_Online) {
  16036. SSLClient client("github.com");
  16037. client.set_follow_location(true);
  16038. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16039. "Coollab-Windows.zip");
  16040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16041. EXPECT_EQ(StatusCode::OK_200, res->status);
  16042. EXPECT_EQ(9920427U, res->body.size());
  16043. }
  16044. #endif
  16045. TEST(VulnerabilityTest, CRLFInjection) {
  16046. Server svr;
  16047. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16048. res.set_content("Hello 1", "text/plain");
  16049. });
  16050. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16051. res.set_content("Hello 2", "text/plain");
  16052. });
  16053. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16054. res.set_content("Hello 3", "text/plain");
  16055. });
  16056. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16057. res.set_content("Hello 4", "text/plain");
  16058. });
  16059. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16060. for (const auto &x : req.headers) {
  16061. auto key = x.first;
  16062. EXPECT_STRNE("evil", key.c_str());
  16063. }
  16064. });
  16065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16066. auto se = detail::scope_exit([&] {
  16067. svr.stop();
  16068. thread.join();
  16069. ASSERT_FALSE(svr.is_running());
  16070. });
  16071. svr.wait_until_ready();
  16072. {
  16073. Client cli(HOST, PORT);
  16074. cli.Post("/test1", "A=B",
  16075. "application/x-www-form-urlencoded\r\nevil: hello1");
  16076. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16077. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16078. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16079. }
  16080. }
  16081. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16082. auto server_thread = std::thread([] {
  16083. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16084. default_socket_options(srv);
  16085. sockaddr_in addr{};
  16086. addr.sin_family = AF_INET;
  16087. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16088. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16089. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16090. ::listen(srv, 1);
  16091. sockaddr_in cli_addr{};
  16092. socklen_t cli_len = sizeof(cli_addr);
  16093. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16094. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16095. std::string buf_all;
  16096. char buf[2048];
  16097. ssize_t n;
  16098. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16099. buf_all.append(buf, static_cast<size_t>(n));
  16100. size_t pos;
  16101. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16102. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16103. auto e = request_block.find("\r\n");
  16104. if (e != std::string::npos) {
  16105. auto request_line = request_block.substr(0, e);
  16106. std::string msg =
  16107. "CRLF injection detected in request line: '" + request_line + "'";
  16108. EXPECT_FALSE(true) << msg;
  16109. }
  16110. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16111. ::send(cli,
  16112. #ifdef _WIN32
  16113. static_cast<const char *>(resp.c_str()),
  16114. static_cast<int>(resp.size()),
  16115. #else
  16116. resp.c_str(), resp.size(),
  16117. #endif
  16118. 0);
  16119. buf_all.erase(0, pos + 4);
  16120. }
  16121. }
  16122. detail::close_socket(cli);
  16123. detail::close_socket(srv);
  16124. });
  16125. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16126. auto cli = Client("127.0.0.1", PORT + 1);
  16127. auto headers = Headers{
  16128. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16129. {"Connection", "keep-alive"}};
  16130. auto res = cli.Get("/hi", headers);
  16131. EXPECT_FALSE(res);
  16132. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16133. server_thread.join();
  16134. }
  16135. // A request rejected before any byte reaches the socket must fail right away
  16136. // instead of waiting for a response the server will never send.
  16137. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16138. // The kernel completes the TCP handshake from the listen backlog, so the
  16139. // client connects, but nothing ever reads, responds or closes.
  16140. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16141. default_socket_options(srv);
  16142. sockaddr_in addr{};
  16143. addr.sin_family = AF_INET;
  16144. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16145. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16146. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16147. ASSERT_EQ(0, ::listen(srv, 8));
  16148. auto cli = Client("127.0.0.1", PORT + 1);
  16149. cli.set_read_timeout(10, 0);
  16150. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16151. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16152. std::chrono::steady_clock::now() - start)
  16153. .count();
  16154. };
  16155. {
  16156. Request req;
  16157. req.method = "GE T";
  16158. req.path = "/";
  16159. auto start = std::chrono::steady_clock::now();
  16160. auto res = cli.send(req);
  16161. EXPECT_FALSE(res);
  16162. EXPECT_EQ(Error::Write, res.error());
  16163. EXPECT_LT(elapsed_ms(start), 1000);
  16164. }
  16165. {
  16166. auto start = std::chrono::steady_clock::now();
  16167. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16168. EXPECT_FALSE(res);
  16169. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16170. EXPECT_LT(elapsed_ms(start), 1000);
  16171. }
  16172. EXPECT_FALSE(cli.is_socket_open());
  16173. detail::close_socket(srv);
  16174. }
  16175. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16176. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16177. default_socket_options(srv);
  16178. sockaddr_in addr{};
  16179. addr.sin_family = AF_INET;
  16180. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16181. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16182. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16183. ASSERT_EQ(0, ::listen(srv, 1));
  16184. std::string received;
  16185. auto server_thread = std::thread([&] {
  16186. auto sock = ::accept(srv, nullptr, nullptr);
  16187. if (sock == INVALID_SOCKET) { return; }
  16188. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16189. char buf[2048];
  16190. ssize_t n;
  16191. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16192. received.append(buf, static_cast<size_t>(n));
  16193. }
  16194. detail::close_socket(sock);
  16195. });
  16196. {
  16197. auto cli = Client("127.0.0.1", PORT + 1);
  16198. // "Z" sorts after the default headers, so writing straight to the socket
  16199. // would have sent the request line and those headers before the rejection.
  16200. auto handle =
  16201. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16202. EXPECT_FALSE(handle.is_valid());
  16203. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16204. }
  16205. server_thread.join();
  16206. detail::close_socket(srv);
  16207. EXPECT_TRUE(received.empty()) << received;
  16208. }
  16209. TEST(PathParamsTest, StaticMatch) {
  16210. const auto pattern = "/users/all";
  16211. detail::PathParamsMatcher matcher(pattern);
  16212. Request request;
  16213. request.path = "/users/all";
  16214. ASSERT_TRUE(matcher.match(request));
  16215. std::unordered_map<std::string, std::string> expected_params = {};
  16216. EXPECT_EQ(request.path_params, expected_params);
  16217. }
  16218. TEST(PathParamsTest, StaticMismatch) {
  16219. const auto pattern = "/users/all";
  16220. detail::PathParamsMatcher matcher(pattern);
  16221. Request request;
  16222. request.path = "/users/1";
  16223. ASSERT_FALSE(matcher.match(request));
  16224. }
  16225. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16226. const auto pattern = "/users/:id/subscriptions";
  16227. detail::PathParamsMatcher matcher(pattern);
  16228. Request request;
  16229. request.path = "/users/42/subscriptions";
  16230. ASSERT_TRUE(matcher.match(request));
  16231. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16232. EXPECT_EQ(request.path_params, expected_params);
  16233. }
  16234. TEST(PathParamsTest, SingleParamInTheEnd) {
  16235. const auto pattern = "/users/:id";
  16236. detail::PathParamsMatcher matcher(pattern);
  16237. Request request;
  16238. request.path = "/users/24";
  16239. ASSERT_TRUE(matcher.match(request));
  16240. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16241. EXPECT_EQ(request.path_params, expected_params);
  16242. }
  16243. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16244. const auto pattern = "/users/:id/";
  16245. detail::PathParamsMatcher matcher(pattern);
  16246. Request request;
  16247. request.path = "/users/42/";
  16248. ASSERT_TRUE(matcher.match(request));
  16249. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16250. EXPECT_EQ(request.path_params, expected_params);
  16251. }
  16252. TEST(PathParamsTest, EmptyParam) {
  16253. const auto pattern = "/users/:id/";
  16254. detail::PathParamsMatcher matcher(pattern);
  16255. Request request;
  16256. request.path = "/users//";
  16257. ASSERT_TRUE(matcher.match(request));
  16258. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16259. EXPECT_EQ(request.path_params, expected_params);
  16260. }
  16261. TEST(PathParamsTest, FragmentMismatch) {
  16262. const auto pattern = "/users/:id/";
  16263. detail::PathParamsMatcher matcher(pattern);
  16264. Request request;
  16265. request.path = "/admins/24/";
  16266. ASSERT_FALSE(matcher.match(request));
  16267. }
  16268. TEST(PathParamsTest, ExtraFragments) {
  16269. const auto pattern = "/users/:id";
  16270. detail::PathParamsMatcher matcher(pattern);
  16271. Request request;
  16272. request.path = "/users/42/subscriptions";
  16273. ASSERT_FALSE(matcher.match(request));
  16274. }
  16275. TEST(PathParamsTest, MissingTrailingParam) {
  16276. const auto pattern = "/users/:id";
  16277. detail::PathParamsMatcher matcher(pattern);
  16278. Request request;
  16279. request.path = "/users";
  16280. ASSERT_FALSE(matcher.match(request));
  16281. }
  16282. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16283. const auto pattern = "/users/:id/subscriptions";
  16284. detail::PathParamsMatcher matcher(pattern);
  16285. Request request;
  16286. request.path = "/users/subscriptions";
  16287. ASSERT_FALSE(matcher.match(request));
  16288. }
  16289. TEST(PathParamsTest, MultipleParams) {
  16290. const auto pattern = "/users/:userid/subscriptions/:subid";
  16291. detail::PathParamsMatcher matcher(pattern);
  16292. Request request;
  16293. request.path = "/users/42/subscriptions/2";
  16294. ASSERT_TRUE(matcher.match(request));
  16295. std::unordered_map<std::string, std::string> expected_params = {
  16296. {"userid", "42"}, {"subid", "2"}};
  16297. EXPECT_EQ(request.path_params, expected_params);
  16298. }
  16299. TEST(PathParamsTest, SequenceOfParams) {
  16300. const auto pattern = "/values/:x/:y/:z";
  16301. detail::PathParamsMatcher matcher(pattern);
  16302. Request request;
  16303. request.path = "/values/1/2/3";
  16304. ASSERT_TRUE(matcher.match(request));
  16305. std::unordered_map<std::string, std::string> expected_params = {
  16306. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16307. EXPECT_EQ(request.path_params, expected_params);
  16308. }
  16309. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16310. const auto pattern = "/prefix:suffix";
  16311. detail::PathParamsMatcher matcher(pattern);
  16312. Request request;
  16313. request.path = "/prefix:suffix";
  16314. ASSERT_TRUE(matcher.match(request));
  16315. const std::unordered_map<std::string, std::string> expected_params = {};
  16316. EXPECT_EQ(request.path_params, expected_params);
  16317. }
  16318. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16319. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16320. // calling thread's stack on a long enough path for a quantified pattern;
  16321. // RegexMatcher must refuse to run regex matching on paths beyond
  16322. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16323. detail::RegexMatcher matcher("/files/(.*)");
  16324. Request within_limit;
  16325. within_limit.path = "/files/" + std::string(10, 'A');
  16326. EXPECT_TRUE(matcher.match(within_limit));
  16327. Request over_limit;
  16328. over_limit.path =
  16329. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16330. EXPECT_FALSE(matcher.match(over_limit));
  16331. }
  16332. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16333. Server svr;
  16334. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16335. res.set_content("ok", "text/plain");
  16336. });
  16337. auto port = svr.bind_to_any_port(HOST);
  16338. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16339. auto se = detail::scope_exit([&] {
  16340. svr.stop();
  16341. thread.join();
  16342. ASSERT_FALSE(svr.is_running());
  16343. });
  16344. svr.wait_until_ready();
  16345. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16346. // request URI limit; this used to be able to crash the process.
  16347. std::string path =
  16348. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16349. std::string req = "GET " + path +
  16350. " HTTP/1.1\r\n"
  16351. "Host: " +
  16352. std::string(HOST) + ":" + std::to_string(port) +
  16353. "\r\n"
  16354. "Connection: close\r\n"
  16355. "\r\n";
  16356. std::string response;
  16357. ASSERT_TRUE(send_request(5, req, &response, port));
  16358. EXPECT_NE(std::string::npos, response.find("404"));
  16359. }
  16360. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16361. Server svr;
  16362. auto handler = [](const Request & /*req*/, Response &res) {
  16363. res.set_content("hit", "text/plain");
  16364. };
  16365. // No regex metacharacter, so this one is compared literally
  16366. svr.Get("/literal/route", handler);
  16367. // '.' is a regex metacharacter, so this one must keep regex semantics
  16368. svr.Get("/a.c", handler);
  16369. auto port = svr.bind_to_any_port(HOST);
  16370. std::thread t([&]() { svr.listen_after_bind(); });
  16371. auto se = detail::scope_exit([&] {
  16372. svr.stop();
  16373. t.join();
  16374. ASSERT_FALSE(svr.is_running());
  16375. });
  16376. svr.wait_until_ready();
  16377. Client cli(HOST, port);
  16378. struct {
  16379. const char *path;
  16380. int status;
  16381. } cases[] = {
  16382. {"/literal/route", StatusCode::OK_200},
  16383. {"/literal/routes", StatusCode::NotFound_404},
  16384. {"/literal/rout", StatusCode::NotFound_404},
  16385. {"/abc", StatusCode::OK_200},
  16386. {"/a.c", StatusCode::OK_200},
  16387. };
  16388. for (const auto &x : cases) {
  16389. auto res = cli.Get(x.path);
  16390. ASSERT_TRUE(res) << x.path;
  16391. EXPECT_EQ(x.status, res->status) << x.path;
  16392. }
  16393. }
  16394. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16395. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16396. // from exhausting the stack, so it must only constrain routes that actually
  16397. // run a regular expression. A literal route is matched by comparison and
  16398. // stays usable at any length.
  16399. Server svr;
  16400. const std::string pattern =
  16401. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16402. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16403. res.set_content("hit", "text/plain");
  16404. });
  16405. auto port = svr.bind_to_any_port(HOST);
  16406. std::thread t([&]() { svr.listen_after_bind(); });
  16407. auto se = detail::scope_exit([&] {
  16408. svr.stop();
  16409. t.join();
  16410. ASSERT_FALSE(svr.is_running());
  16411. });
  16412. svr.wait_until_ready();
  16413. Client cli(HOST, port);
  16414. auto res = cli.Get(pattern);
  16415. ASSERT_TRUE(res);
  16416. EXPECT_EQ(StatusCode::OK_200, res->status);
  16417. }
  16418. TEST(ParseUrlTest, VariousPatterns) {
  16419. {
  16420. detail::UrlComponents uc;
  16421. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16422. EXPECT_EQ("http", uc.scheme);
  16423. EXPECT_EQ("example.com", uc.host);
  16424. EXPECT_EQ("8080", uc.port);
  16425. EXPECT_EQ("/path", uc.path);
  16426. EXPECT_EQ("?q=1", uc.query);
  16427. }
  16428. {
  16429. detail::UrlComponents uc;
  16430. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16431. EXPECT_EQ("https", uc.scheme);
  16432. EXPECT_EQ("example.com", uc.host);
  16433. EXPECT_TRUE(uc.port.empty());
  16434. EXPECT_EQ("/path", uc.path);
  16435. }
  16436. {
  16437. detail::UrlComponents uc;
  16438. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16439. EXPECT_EQ("::1", uc.host);
  16440. EXPECT_EQ("8080", uc.port);
  16441. EXPECT_EQ("/path", uc.path);
  16442. }
  16443. {
  16444. detail::UrlComponents uc;
  16445. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16446. }
  16447. {
  16448. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16449. // the path while the connection still targets the bracketed host.
  16450. detail::UrlComponents uc;
  16451. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16452. }
  16453. {
  16454. detail::UrlComponents uc;
  16455. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16456. }
  16457. {
  16458. detail::UrlComponents uc;
  16459. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16460. EXPECT_EQ("::1", uc.host);
  16461. EXPECT_TRUE(uc.port.empty());
  16462. EXPECT_EQ("/path", uc.path);
  16463. }
  16464. {
  16465. detail::UrlComponents uc;
  16466. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16467. EXPECT_TRUE(uc.scheme.empty());
  16468. EXPECT_EQ("example.com", uc.host);
  16469. EXPECT_EQ("/path", uc.path);
  16470. EXPECT_EQ("?q=1", uc.query);
  16471. }
  16472. {
  16473. detail::UrlComponents uc;
  16474. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16475. EXPECT_TRUE(uc.host.empty());
  16476. EXPECT_EQ("/path", uc.path);
  16477. EXPECT_EQ("?q=1", uc.query);
  16478. }
  16479. {
  16480. detail::UrlComponents uc;
  16481. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16482. EXPECT_EQ("example.com", uc.host);
  16483. EXPECT_EQ("8080", uc.port);
  16484. }
  16485. {
  16486. // Unix socket path — must not be parsed as host
  16487. detail::UrlComponents uc;
  16488. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16489. EXPECT_TRUE(uc.host.empty());
  16490. }
  16491. {
  16492. detail::UrlComponents uc;
  16493. ASSERT_TRUE(detail::parse_url("", uc));
  16494. EXPECT_TRUE(uc.host.empty());
  16495. EXPECT_TRUE(uc.path.empty());
  16496. }
  16497. {
  16498. detail::UrlComponents uc;
  16499. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16500. }
  16501. {
  16502. detail::UrlComponents uc;
  16503. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16504. }
  16505. {
  16506. // Accepted by parse_url; callers restrict to http/https
  16507. detail::UrlComponents uc;
  16508. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16509. EXPECT_EQ("ftp", uc.scheme);
  16510. }
  16511. {
  16512. detail::UrlComponents uc;
  16513. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16514. }
  16515. {
  16516. detail::UrlComponents uc;
  16517. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16518. }
  16519. }
  16520. TEST(ParseUrlTest, FragmentHandling) {
  16521. {
  16522. detail::UrlComponents uc;
  16523. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16524. EXPECT_EQ("/path", uc.path);
  16525. EXPECT_TRUE(uc.query.empty());
  16526. }
  16527. {
  16528. detail::UrlComponents uc;
  16529. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16530. EXPECT_TRUE(uc.path.empty());
  16531. EXPECT_TRUE(uc.query.empty());
  16532. }
  16533. }
  16534. TEST(ParseUrlTest, UserinfoHandling) {
  16535. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16536. // parsers would see evil.com as the host.
  16537. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16538. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16539. for (auto url : urls) {
  16540. detail::UrlComponents uc;
  16541. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16542. }
  16543. }
  16544. TEST(ParseUrlTest, IPv6EdgeCases) {
  16545. {
  16546. detail::UrlComponents uc;
  16547. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16548. EXPECT_TRUE(uc.scheme.empty());
  16549. EXPECT_EQ("::1", uc.host);
  16550. EXPECT_EQ("8080", uc.port);
  16551. }
  16552. {
  16553. // Zone ID '%25' is not in [a-fA-F0-9:]
  16554. detail::UrlComponents uc;
  16555. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16556. }
  16557. }
  16558. TEST(ParseUrlTest, SchemeEdgeCases) {
  16559. {
  16560. detail::UrlComponents uc;
  16561. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16562. }
  16563. {
  16564. detail::UrlComponents uc;
  16565. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16566. }
  16567. {
  16568. detail::UrlComponents uc;
  16569. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16570. }
  16571. }
  16572. TEST(ParseUrlTest, PortEdgeCases) {
  16573. {
  16574. detail::UrlComponents uc;
  16575. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16576. EXPECT_TRUE(uc.port.empty());
  16577. EXPECT_EQ("/path", uc.path);
  16578. }
  16579. {
  16580. // parse_url accepts any port string; validation is done by parse_port
  16581. detail::UrlComponents uc;
  16582. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16583. EXPECT_EQ("abc", uc.port);
  16584. }
  16585. }
  16586. TEST(ParseUrlTest, WebSocketPatterns) {
  16587. {
  16588. detail::UrlComponents uc;
  16589. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16590. EXPECT_EQ("ws", uc.scheme);
  16591. EXPECT_EQ("echo.example.com", uc.host);
  16592. EXPECT_EQ("8080", uc.port);
  16593. EXPECT_EQ("/ws", uc.path);
  16594. }
  16595. {
  16596. detail::UrlComponents uc;
  16597. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16598. EXPECT_EQ("wss", uc.scheme);
  16599. EXPECT_EQ("echo.example.com", uc.host);
  16600. EXPECT_TRUE(uc.port.empty());
  16601. EXPECT_EQ("/ws", uc.path);
  16602. }
  16603. }
  16604. TEST(ParseUrlTest, QueryOnly) {
  16605. detail::UrlComponents uc;
  16606. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16607. EXPECT_TRUE(uc.host.empty());
  16608. EXPECT_TRUE(uc.path.empty());
  16609. EXPECT_EQ("?q=1&r=2", uc.query);
  16610. }
  16611. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16612. detail::UrlComponents uc;
  16613. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16614. EXPECT_TRUE(uc.scheme.empty());
  16615. EXPECT_EQ("example.com", uc.host);
  16616. EXPECT_EQ("443", uc.port);
  16617. EXPECT_EQ("/path", uc.path);
  16618. }
  16619. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16620. // If ipv6 regex working, regex match codepath is taken.
  16621. // else port will default to 80 in Client impl
  16622. int clientImplMagicPort = 80;
  16623. int port = 4321;
  16624. // above ports must be different to avoid false negative
  16625. EXPECT_NE(clientImplMagicPort, port);
  16626. std::string ipV6TestURL = "http://[ff06::c3]";
  16627. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16628. CLIENT_PRIVATE_KEY_FILE);
  16629. EXPECT_EQ(cli.port(), port);
  16630. }
  16631. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16632. auto file_path = "./www/dir/index.html";
  16633. auto dir_path = "./www/dir";
  16634. detail::FileStat stat_file(file_path);
  16635. EXPECT_TRUE(stat_file.is_file());
  16636. EXPECT_FALSE(stat_file.is_dir());
  16637. detail::FileStat stat_dir(dir_path);
  16638. EXPECT_FALSE(stat_dir.is_file());
  16639. EXPECT_TRUE(stat_dir.is_dir());
  16640. }
  16641. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16642. // IPv4 with default HTTP port (80)
  16643. EXPECT_EQ("example.com",
  16644. detail::make_host_and_port_string("example.com", 80, false));
  16645. // IPv4 with default HTTPS port (443)
  16646. EXPECT_EQ("example.com",
  16647. detail::make_host_and_port_string("example.com", 443, true));
  16648. // IPv4 with non-default HTTP port
  16649. EXPECT_EQ("example.com:8080",
  16650. detail::make_host_and_port_string("example.com", 8080, false));
  16651. // IPv4 with non-default HTTPS port
  16652. EXPECT_EQ("example.com:8443",
  16653. detail::make_host_and_port_string("example.com", 8443, true));
  16654. // IPv6 with default HTTP port (80)
  16655. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16656. // IPv6 with default HTTPS port (443)
  16657. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16658. // IPv6 with non-default HTTP port
  16659. EXPECT_EQ("[::1]:8080",
  16660. detail::make_host_and_port_string("::1", 8080, false));
  16661. // IPv6 with non-default HTTPS port
  16662. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16663. // IPv6 full address with default port
  16664. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16665. detail::make_host_and_port_string(
  16666. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16667. // IPv6 full address with non-default port
  16668. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16669. detail::make_host_and_port_string(
  16670. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16671. // IPv6 localhost with non-default port
  16672. EXPECT_EQ("[::1]:3000",
  16673. detail::make_host_and_port_string("::1", 3000, false));
  16674. // IPv6 with zone ID (link-local address) with default port
  16675. EXPECT_EQ("[fe80::1%eth0]",
  16676. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16677. // IPv6 with zone ID (link-local address) with non-default port
  16678. EXPECT_EQ("[fe80::1%eth0]:8080",
  16679. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16680. // Edge case: Port 443 with is_ssl=false (should add port)
  16681. EXPECT_EQ("example.com:443",
  16682. detail::make_host_and_port_string("example.com", 443, false));
  16683. // Edge case: Port 80 with is_ssl=true (should add port)
  16684. EXPECT_EQ("example.com:80",
  16685. detail::make_host_and_port_string("example.com", 80, true));
  16686. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16687. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16688. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16689. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16690. // Security fix: Already bracketed IPv6 should not get double brackets
  16691. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16692. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16693. EXPECT_EQ("[::1]:8080",
  16694. detail::make_host_and_port_string("[::1]", 8080, false));
  16695. EXPECT_EQ("[2001:db8::1]:8080",
  16696. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16697. EXPECT_EQ("[fe80::1%eth0]",
  16698. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16699. EXPECT_EQ("[fe80::1%eth0]:8080",
  16700. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16701. // Edge case: Empty host (should return as-is)
  16702. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16703. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16704. // This is a known limitation but shouldn't crash
  16705. EXPECT_EQ("[host:name]",
  16706. detail::make_host_and_port_string("host:name", 80, false));
  16707. // Port number edge cases (no validation, but should not crash)
  16708. EXPECT_EQ("example.com:0",
  16709. detail::make_host_and_port_string("example.com", 0, false));
  16710. EXPECT_EQ("example.com:-1",
  16711. detail::make_host_and_port_string("example.com", -1, false));
  16712. EXPECT_EQ("example.com:65535",
  16713. detail::make_host_and_port_string("example.com", 65535, false));
  16714. EXPECT_EQ("example.com:65536",
  16715. detail::make_host_and_port_string("example.com", 65536, false));
  16716. }
  16717. #ifdef CPPHTTPLIB_SSL_ENABLED
  16718. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16719. httplib::SSLClient cli("roblox.com", 443);
  16720. cli.set_follow_location(true);
  16721. auto res = cli.Get("/");
  16722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16723. EXPECT_EQ(StatusCode::OK_200, res->status);
  16724. }
  16725. #endif
  16726. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16727. Server svr;
  16728. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16729. EXPECT_EQ(res.status, 400);
  16730. });
  16731. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16732. auto se = detail::scope_exit([&] {
  16733. svr.stop();
  16734. thread.join();
  16735. ASSERT_FALSE(svr.is_running());
  16736. });
  16737. svr.wait_until_ready();
  16738. Client cli(HOST, PORT);
  16739. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16740. }
  16741. TEST(InvalidHeaderCharsTest, is_field_name) {
  16742. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16743. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16744. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16745. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16746. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16747. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16748. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16749. EXPECT_FALSE(detail::fields::is_field_name(""));
  16750. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16751. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16752. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16753. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16754. }
  16755. TEST(InvalidHeaderCharsTest, is_field_value) {
  16756. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16757. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16758. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16759. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16760. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16761. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16762. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16763. EXPECT_TRUE(detail::fields::is_field_value(""));
  16764. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16765. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16766. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16767. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16768. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16769. }
  16770. TEST(InvalidHeaderCharsTest, OnServer) {
  16771. Server svr;
  16772. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16773. std::string header = "Not Set";
  16774. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16775. res.set_header(header, "value");
  16776. res.set_content("Page Content Page Content", "text/plain");
  16777. });
  16778. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16779. std::string header = "Not Set";
  16780. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16781. res.set_header("X-Test", header);
  16782. res.set_content("Page Content Page Content", "text/plain");
  16783. });
  16784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16785. auto se = detail::scope_exit([&] {
  16786. svr.stop();
  16787. thread.join();
  16788. ASSERT_FALSE(svr.is_running());
  16789. });
  16790. svr.wait_until_ready();
  16791. Client cli(HOST, PORT);
  16792. {
  16793. auto res = cli.Get(
  16794. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16796. EXPECT_EQ("Page Content Page Content", res->body);
  16797. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16798. }
  16799. {
  16800. auto res = cli.Get(
  16801. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16803. EXPECT_EQ("Page Content Page Content", res->body);
  16804. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16805. }
  16806. }
  16807. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16808. auto handled = false;
  16809. Server svr;
  16810. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16811. thread t = thread([&] { svr.listen(HOST, PORT); });
  16812. auto se = detail::scope_exit([&] {
  16813. svr.stop();
  16814. t.join();
  16815. ASSERT_FALSE(svr.is_running());
  16816. ASSERT_FALSE(handled);
  16817. });
  16818. svr.wait_until_ready();
  16819. auto req = "POST /test HTTP/1.1\r\n"
  16820. "Content-Length: x\r\n"
  16821. "\r\n";
  16822. std::string response;
  16823. ASSERT_TRUE(send_request(1, req, &response));
  16824. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16825. response.substr(0, response.find("\r\n")));
  16826. }
  16827. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16828. // case-insensitive, and a server that receives a 100-continue expectation in
  16829. // an HTTP/1.0 request MUST ignore it.
  16830. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16831. std::string response;
  16832. ASSERT_TRUE(send_request(1, req, &response, port));
  16833. *got_100 = response.find("100 Continue") != std::string::npos;
  16834. }
  16835. class ExpectTokenTest : public ::testing::Test {
  16836. protected:
  16837. void SetUp() override {
  16838. svr_.Post("/p", [](const Request &, Response &res) {
  16839. res.set_content("ok", "text/plain");
  16840. });
  16841. port_ = svr_.bind_to_any_port(HOST);
  16842. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16843. svr_.wait_until_ready();
  16844. }
  16845. void TearDown() override {
  16846. svr_.stop();
  16847. if (thread_.joinable()) { thread_.join(); }
  16848. }
  16849. std::string request(const char *version, const char *expect_value) const {
  16850. return std::string("POST /p ") + version +
  16851. "\r\n"
  16852. "Host: localhost\r\n"
  16853. "Content-Length: 2\r\n"
  16854. "Connection: close\r\n"
  16855. "Expect: " +
  16856. expect_value +
  16857. "\r\n"
  16858. "\r\n"
  16859. "hi";
  16860. }
  16861. Server svr_;
  16862. int port_ = 0;
  16863. thread thread_;
  16864. };
  16865. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16866. bool got_100 = false;
  16867. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16868. EXPECT_TRUE(got_100);
  16869. }
  16870. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16871. bool got_100 = true;
  16872. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16873. EXPECT_FALSE(got_100);
  16874. }
  16875. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16876. bool got_100 = false;
  16877. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16878. EXPECT_TRUE(got_100);
  16879. }
  16880. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16881. bool got_100 = false;
  16882. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16883. EXPECT_TRUE(got_100);
  16884. }
  16885. // `100 Continue` is sent only when the server starts reading the body, so a
  16886. // request rejected before that never invites the client to send it. The
  16887. // requests below carry the expectation but withhold the body, as a client
  16888. // waiting for `100 Continue` would.
  16889. // A POST that expects `100 Continue` and withholds its two-byte body.
  16890. static std::string expect_headers_only(const std::string &path) {
  16891. return "POST " + path +
  16892. " HTTP/1.1\r\n"
  16893. "Host: localhost\r\n"
  16894. "Content-Length: 2\r\n"
  16895. "Expect: 100-continue\r\n"
  16896. "\r\n";
  16897. }
  16898. class ExpectLazyContinueTest : public ::testing::Test {
  16899. protected:
  16900. void SetUp() override {
  16901. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16902. if (req.path == "/pre-routing") {
  16903. res.status = StatusCode::Unauthorized_401;
  16904. return Server::HandlerResponse::Handled;
  16905. }
  16906. return Server::HandlerResponse::Unhandled;
  16907. });
  16908. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16909. if (req.matched_route == "/pre-request") {
  16910. res.status = StatusCode::Forbidden_403;
  16911. return Server::HandlerResponse::Handled;
  16912. }
  16913. return Server::HandlerResponse::Unhandled;
  16914. });
  16915. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16916. res.set_content("ok", "text/plain");
  16917. });
  16918. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16919. res.set_content("ok", "text/plain");
  16920. });
  16921. svr_.Post("/reader-used", [](const Request &, Response &res,
  16922. const ContentReader &content_reader) {
  16923. std::string body;
  16924. content_reader([&](const char *data, size_t len) {
  16925. body.append(data, len);
  16926. return true;
  16927. });
  16928. res.set_content(body, "text/plain");
  16929. });
  16930. svr_.Post("/reader-unused",
  16931. [](const Request &, Response &res, const ContentReader &) {
  16932. res.set_content("ignored", "text/plain");
  16933. });
  16934. port_ = svr_.bind_to_any_port(HOST);
  16935. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16936. svr_.wait_until_ready();
  16937. }
  16938. void TearDown() override {
  16939. svr_.stop();
  16940. if (thread_.joinable()) { thread_.join(); }
  16941. }
  16942. // Sends `req` and reads until the server closes the connection. Returns
  16943. // false if the read had to wait for the client-side timeout instead.
  16944. bool send_until_closed(const std::string &req, std::string *resp) const {
  16945. auto start = std::chrono::steady_clock::now();
  16946. if (!send_request(3, req, resp, port_)) { return false; }
  16947. auto elapsed = std::chrono::steady_clock::now() - start;
  16948. return elapsed < std::chrono::seconds(2);
  16949. }
  16950. // The final response comes without `100 Continue`, and the server closes
  16951. // the connection since the body may or may not follow.
  16952. void expect_final_without_interim(const std::string &path,
  16953. const char *status_line) const {
  16954. std::string resp;
  16955. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16956. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16957. EXPECT_EQ(0u, resp.find(status_line));
  16958. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16959. }
  16960. Server svr_;
  16961. int port_ = 0;
  16962. thread thread_;
  16963. };
  16964. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16965. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16966. }
  16967. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16968. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16969. }
  16970. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16971. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16972. }
  16973. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16974. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16975. }
  16976. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16977. // The body follows once `100 Continue` has had time to arrive.
  16978. auto req = expect_headers_only("/reader-used");
  16979. req.insert(req.size() - 2, "Connection: close\r\n");
  16980. std::string resp;
  16981. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16982. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16983. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16984. EXPECT_NE(std::string::npos, resp.find("hi"));
  16985. }
  16986. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16987. // Large enough for the client to add `Expect: 100-continue` itself.
  16988. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16989. std::atomic<bool> body_sent{false};
  16990. Client cli(HOST, port_);
  16991. auto res = cli.Post(
  16992. "/pre-request", length,
  16993. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16994. body_sent = true;
  16995. std::string chunk(len, 'x');
  16996. sink.write(chunk.data(), chunk.size());
  16997. return true;
  16998. },
  16999. "application/octet-stream");
  17000. ASSERT_TRUE(res);
  17001. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17002. EXPECT_FALSE(body_sent);
  17003. }
  17004. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17005. Server svr;
  17006. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17007. return StatusCode::ExpectationFailed_417;
  17008. });
  17009. svr.Post("/p", [](const Request &, Response &res) {
  17010. res.set_content("ok", "text/plain");
  17011. });
  17012. auto port = svr.bind_to_any_port(HOST);
  17013. thread t = thread([&] { svr.listen_after_bind(); });
  17014. auto se = detail::scope_exit([&] {
  17015. svr.stop();
  17016. t.join();
  17017. });
  17018. svr.wait_until_ready();
  17019. std::string resp;
  17020. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17021. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17022. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17023. // Exactly one response: the route handler must not run after the 417.
  17024. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17025. }
  17026. #ifndef _WIN32
  17027. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17028. static constexpr char reject[] = "Unauthorized";
  17029. static constexpr char accept[] = "Upload accepted";
  17030. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17031. Server svr;
  17032. svr.set_expect_100_continue_handler(
  17033. [](const Request & /*req*/, Response &res) {
  17034. res.status = StatusCode::Unauthorized_401;
  17035. res.set_content(reject, "text/plain");
  17036. return res.status;
  17037. });
  17038. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17039. res.set_content(accept, "text/plain");
  17040. });
  17041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17042. auto se = detail::scope_exit([&] {
  17043. svr.stop();
  17044. thread.join();
  17045. ASSERT_FALSE(svr.is_running());
  17046. });
  17047. svr.wait_until_ready();
  17048. {
  17049. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17050. curl_easy_init(), &curl_easy_cleanup};
  17051. ASSERT_NE(curl, nullptr);
  17052. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17053. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17054. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17055. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17056. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17057. &curl_slist_free_all};
  17058. ASSERT_NE(list, nullptr);
  17059. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17060. struct read_data {
  17061. size_t read_size;
  17062. size_t total_size;
  17063. } data = {0, total_size};
  17064. using read_callback_t =
  17065. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17066. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17067. void *userdata) -> size_t {
  17068. read_data *d = (read_data *)userdata;
  17069. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17070. std::fill_n(ptr, size * nmemb, 'A');
  17071. d->read_size += size * nmemb;
  17072. return size * nmemb;
  17073. };
  17074. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17075. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17076. std::vector<char> buffer;
  17077. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17078. using write_callback_t =
  17079. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17080. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17081. void *userdata) -> size_t {
  17082. std::vector<char> *buf = (std::vector<char> *)userdata;
  17083. buf->reserve(buf->size() + size * nmemb + 1);
  17084. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17085. return size * nmemb;
  17086. };
  17087. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17088. {
  17089. const auto res = curl_easy_perform(curl.get());
  17090. ASSERT_EQ(res, CURLE_OK);
  17091. }
  17092. {
  17093. auto response_code = long{};
  17094. const auto res =
  17095. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17096. ASSERT_EQ(res, CURLE_OK);
  17097. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17098. }
  17099. {
  17100. auto dl = curl_off_t{};
  17101. const auto res =
  17102. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17103. ASSERT_EQ(res, CURLE_OK);
  17104. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17105. }
  17106. {
  17107. buffer.push_back('\0');
  17108. ASSERT_STRCASEEQ(buffer.data(), reject);
  17109. }
  17110. }
  17111. }
  17112. #endif
  17113. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17114. // Regression test for #2458.
  17115. //
  17116. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17117. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17118. // ticket can make the client socket spuriously readable during the
  17119. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17120. // the client withholds the body and then blocks reading a response that never
  17121. // comes, failing with `Failed to read connection`.
  17122. //
  17123. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17124. // within the timeout. This raw OpenSSL server deliberately never sends
  17125. // `100 Continue`; the client must still deliver the body and receive 200.
  17126. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17127. signal(SIGPIPE, SIG_IGN);
  17128. const auto port = PORT + 4;
  17129. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17130. ASSERT_NE(srv, INVALID_SOCKET);
  17131. int opt = 1;
  17132. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17133. sockaddr_in addr{};
  17134. addr.sin_family = AF_INET;
  17135. addr.sin_port = htons(static_cast<uint16_t>(port));
  17136. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17137. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17138. ASSERT_EQ(0, ::listen(srv, 1));
  17139. std::atomic<size_t> server_body_bytes{0};
  17140. auto server_thread = std::thread([&] {
  17141. sockaddr_in cli_addr{};
  17142. socklen_t cli_len = sizeof(cli_addr);
  17143. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17144. if (cli == INVALID_SOCKET) { return; }
  17145. // Bound the lifetime of the server side so a buggy client (which never
  17146. // sends the body) cannot make this thread block forever on join.
  17147. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17148. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17149. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17150. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17151. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17152. SSL *ssl = SSL_new(ctx);
  17153. SSL_set_fd(ssl, static_cast<int>(cli));
  17154. if (SSL_accept(ssl) > 0) {
  17155. // Read the request headers. Reading here also flushes the TLS 1.3
  17156. // session tickets to the client. Deliberately do NOT send
  17157. // `100 Continue`.
  17158. std::string buf;
  17159. char tmp[1024];
  17160. while (buf.find("\r\n\r\n") == std::string::npos) {
  17161. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17162. if (n <= 0) { break; }
  17163. buf.append(tmp, static_cast<size_t>(n));
  17164. }
  17165. // A correct client sends the body now; count what arrives.
  17166. auto pos = buf.find("\r\n\r\n");
  17167. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17168. while (body < 4096) {
  17169. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17170. if (n <= 0) { break; }
  17171. body += static_cast<size_t>(n);
  17172. }
  17173. server_body_bytes = body;
  17174. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17175. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17176. SSL_shutdown(ssl);
  17177. }
  17178. SSL_free(ssl);
  17179. detail::close_socket(cli);
  17180. SSL_CTX_free(ctx);
  17181. });
  17182. auto se = detail::scope_exit([&] {
  17183. server_thread.join();
  17184. detail::close_socket(srv);
  17185. });
  17186. SSLClient cli("127.0.0.1", port);
  17187. cli.enable_server_certificate_verification(false);
  17188. cli.set_connection_timeout(5, 0);
  17189. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17190. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17191. std::string body(4096, 'A');
  17192. auto res = cli.Put("/api/test", body, "application/json");
  17193. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17194. EXPECT_EQ(StatusCode::OK_200, res->status);
  17195. EXPECT_EQ(body.size(), server_body_bytes.load());
  17196. }
  17197. #endif
  17198. template <typename S, typename C>
  17199. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17200. svr.Get("/stream", [&](const Request &, Response &res) {
  17201. auto data = new std::string("01234567890123456789");
  17202. res.set_content_provider(
  17203. data->size(), "text/plain",
  17204. [&, data](size_t offset, size_t length, DataSink &sink) {
  17205. const size_t DATA_CHUNK_SIZE = 4;
  17206. const auto &d = *data;
  17207. std::this_thread::sleep_for(std::chrono::seconds(1));
  17208. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17209. return true;
  17210. },
  17211. [data](bool success) {
  17212. EXPECT_FALSE(success);
  17213. delete data;
  17214. });
  17215. });
  17216. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17217. auto i = new size_t(0);
  17218. res.set_content_provider(
  17219. "text/plain",
  17220. [i](size_t, DataSink &sink) {
  17221. if (*i < 5) {
  17222. std::this_thread::sleep_for(std::chrono::seconds(1));
  17223. sink.write("abcd", 4);
  17224. (*i)++;
  17225. } else {
  17226. sink.done();
  17227. }
  17228. return true;
  17229. },
  17230. [i](bool success) {
  17231. EXPECT_FALSE(success);
  17232. delete i;
  17233. });
  17234. });
  17235. svr.Get("/chunked", [&](const Request &, Response &res) {
  17236. auto i = new size_t(0);
  17237. res.set_chunked_content_provider(
  17238. "text/plain",
  17239. [i](size_t, DataSink &sink) {
  17240. if (*i < 5) {
  17241. std::this_thread::sleep_for(std::chrono::seconds(1));
  17242. sink.os << "abcd";
  17243. (*i)++;
  17244. } else {
  17245. sink.done();
  17246. }
  17247. return true;
  17248. },
  17249. [i](bool success) {
  17250. EXPECT_FALSE(success);
  17251. delete i;
  17252. });
  17253. });
  17254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17255. auto se = detail::scope_exit([&] {
  17256. svr.stop();
  17257. listen_thread.join();
  17258. ASSERT_FALSE(svr.is_running());
  17259. });
  17260. svr.wait_until_ready();
  17261. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17262. {
  17263. auto start = std::chrono::steady_clock::now();
  17264. auto res = cli.Get("/stream");
  17265. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17266. std::chrono::steady_clock::now() - start)
  17267. .count();
  17268. ASSERT_FALSE(res);
  17269. EXPECT_EQ(Error::Read, res.error());
  17270. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17271. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17272. }
  17273. {
  17274. auto start = std::chrono::steady_clock::now();
  17275. auto res = cli.Get("/stream_without_length");
  17276. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17277. std::chrono::steady_clock::now() - start)
  17278. .count();
  17279. ASSERT_FALSE(res);
  17280. EXPECT_EQ(Error::Read, res.error());
  17281. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17282. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17283. }
  17284. {
  17285. auto start = std::chrono::steady_clock::now();
  17286. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17287. EXPECT_EQ("abcd", string(data, data_length));
  17288. return true;
  17289. });
  17290. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17291. std::chrono::steady_clock::now() - start)
  17292. .count();
  17293. ASSERT_FALSE(res);
  17294. EXPECT_EQ(Error::Read, res.error());
  17295. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17296. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17297. }
  17298. }
  17299. TEST(MaxTimeoutTest, ContentStream) {
  17300. time_t timeout = 2000;
  17301. time_t threshold = 200;
  17302. Server svr;
  17303. Client cli("localhost", PORT);
  17304. max_timeout_test(svr, cli, timeout, threshold);
  17305. }
  17306. #ifdef CPPHTTPLIB_SSL_ENABLED
  17307. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17308. time_t timeout = 2000;
  17309. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17311. SSLClient cli("localhost", PORT);
  17312. cli.enable_server_certificate_verification(false);
  17313. max_timeout_test(svr, cli, timeout, threshold);
  17314. }
  17315. #endif
  17316. class EventDispatcher {
  17317. public:
  17318. EventDispatcher() {}
  17319. bool wait_event(DataSink *sink) {
  17320. unique_lock<mutex> lk(m_);
  17321. int id = id_;
  17322. // Wait with timeout to prevent hanging if client disconnects
  17323. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17324. [&] { return cid_ == id; })) {
  17325. return false; // Timeout occurred
  17326. }
  17327. sink->write(message_.data(), message_.size());
  17328. return true;
  17329. }
  17330. void send_event(const string &message) {
  17331. lock_guard<mutex> lk(m_);
  17332. cid_ = id_++;
  17333. message_ = message;
  17334. cv_.notify_all();
  17335. }
  17336. private:
  17337. mutex m_;
  17338. condition_variable cv_;
  17339. atomic_int id_{0};
  17340. atomic_int cid_{-1};
  17341. string message_;
  17342. };
  17343. TEST(ClientInThreadTest, Issue2068) {
  17344. EventDispatcher ed;
  17345. Server svr;
  17346. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17347. res.set_chunked_content_provider("text/event-stream",
  17348. [&](size_t /*offset*/, DataSink &sink) {
  17349. return ed.wait_event(&sink);
  17350. });
  17351. });
  17352. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17353. svr.wait_until_ready();
  17354. thread event_thread([&] {
  17355. int id = 0;
  17356. while (svr.is_running()) {
  17357. this_thread::sleep_for(chrono::milliseconds(500));
  17358. std::stringstream ss;
  17359. ss << "data: " << id << "\n\n";
  17360. ed.send_event(ss.str());
  17361. id++;
  17362. }
  17363. });
  17364. auto se = detail::scope_exit([&] {
  17365. svr.stop();
  17366. listen_thread.join();
  17367. event_thread.join();
  17368. ASSERT_FALSE(svr.is_running());
  17369. });
  17370. {
  17371. auto client = detail::make_unique<Client>(HOST, PORT);
  17372. client->set_read_timeout(std::chrono::minutes(10));
  17373. std::atomic<bool> stop{false};
  17374. std::thread t([&] {
  17375. client->Get("/event1",
  17376. [&](const char *, size_t) -> bool { return !stop; });
  17377. });
  17378. std::this_thread::sleep_for(std::chrono::seconds(2));
  17379. stop = true;
  17380. client->stop();
  17381. t.join();
  17382. // Reset client after thread has finished
  17383. client.reset();
  17384. }
  17385. }
  17386. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17387. auto handled = false;
  17388. Server svr;
  17389. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17390. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. t.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. ASSERT_FALSE(handled);
  17396. });
  17397. svr.wait_until_ready();
  17398. // Two Content-Length headers with different values — must be rejected
  17399. auto req = "POST /test HTTP/1.1\r\n"
  17400. "Content-Length: 5\r\n"
  17401. "Content-Length: 10\r\n"
  17402. "\r\n"
  17403. "hello";
  17404. std::string response;
  17405. ASSERT_TRUE(send_request(1, req, &response));
  17406. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17407. response.substr(0, response.find("\r\n")));
  17408. }
  17409. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17410. auto handled = false;
  17411. Server svr;
  17412. svr.Post("/test", [&](const Request &, Response &res) {
  17413. handled = true;
  17414. res.set_content("ok", "text/plain");
  17415. });
  17416. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17417. auto se = detail::scope_exit([&] {
  17418. svr.stop();
  17419. t.join();
  17420. ASSERT_FALSE(svr.is_running());
  17421. ASSERT_TRUE(handled);
  17422. });
  17423. svr.wait_until_ready();
  17424. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17425. auto req = "POST /test HTTP/1.1\r\n"
  17426. "Host: localhost\r\n"
  17427. "Content-Length: 5\r\n"
  17428. "Content-Length: 5\r\n"
  17429. "\r\n"
  17430. "hello";
  17431. std::string response;
  17432. ASSERT_TRUE(send_request(1, req, &response));
  17433. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17434. }
  17435. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17436. Server svr;
  17437. svr.Get("/test", [](const Request &, Response &res) {
  17438. res.set_content("ok", "text/plain");
  17439. });
  17440. auto port = svr.bind_to_any_port(HOST);
  17441. thread t = thread([&] { svr.listen_after_bind(); });
  17442. auto se = detail::scope_exit([&] {
  17443. svr.stop();
  17444. t.join();
  17445. ASSERT_FALSE(svr.is_running());
  17446. });
  17447. svr.wait_until_ready();
  17448. auto status_line = [&](const std::string &host_lines) {
  17449. std::string res;
  17450. send_request(
  17451. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17452. &res, port);
  17453. return res.substr(0, res.find("\r\n"));
  17454. };
  17455. const char *accepted[] = {
  17456. "Host: localhost\r\n",
  17457. "Host: a.example:8080\r\n",
  17458. "Host: my_service\r\n",
  17459. "Host: [::1]:8080\r\n",
  17460. "Host: [fe80::1%25eth0]\r\n",
  17461. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17462. };
  17463. for (auto host_lines : accepted) {
  17464. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17465. }
  17466. const char *rejected[] = {
  17467. "Host: a.example\r\nHost: b.example\r\n",
  17468. "Host: a.example\r\nHost: a.example\r\n",
  17469. "Host: a@b.example\r\n",
  17470. "Host: a.example/b\r\n",
  17471. "Host: a.example\\b\r\n",
  17472. "Host: a.example?b\r\n",
  17473. "Host: a.example#b\r\n",
  17474. "Host: a.example b.example\r\n",
  17475. };
  17476. for (auto host_lines : rejected) {
  17477. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17478. << host_lines;
  17479. }
  17480. }
  17481. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17482. Server svr;
  17483. svr.Get("/", [](const Request &req, Response &res) {
  17484. EXPECT_EQ(2U, req.trailers.size());
  17485. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17486. // Denied
  17487. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17488. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17489. // Accepted
  17490. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17491. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17492. EXPECT_TRUE(req.has_trailer("X-World"));
  17493. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17494. res.set_content("ok", "text/plain");
  17495. });
  17496. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17497. auto se = detail::scope_exit([&] {
  17498. svr.stop();
  17499. t.join();
  17500. ASSERT_FALSE(svr.is_running());
  17501. });
  17502. svr.wait_until_ready();
  17503. const std::string req = "GET / HTTP/1.1\r\n"
  17504. "Transfer-Encoding: chunked\r\n"
  17505. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17506. "\r\n"
  17507. "0\r\n"
  17508. "Content-Length: 10\r\n"
  17509. "Host: internal.local\r\n"
  17510. "Content-Type: malicious/content\r\n"
  17511. "Cookie: any\r\n"
  17512. "Set-Cookie: any\r\n"
  17513. "X-Forwarded-For: attacker.com\r\n"
  17514. "X-Real-Ip: 1.1.1.1\r\n"
  17515. "X-Hello: hello\r\n"
  17516. "X-World: world\r\n"
  17517. "\r\n";
  17518. std::string res;
  17519. ASSERT_TRUE(send_request(1, req, &res));
  17520. }
  17521. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17522. // several field lines, and the combined value is what has to be parsed. A
  17523. // Trailer field split across lines therefore declares every name it lists;
  17524. // reading only the first line silently drops the trailers the later lines
  17525. // declare. The prohibited-trailer filter still applies to every line.
  17526. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17527. Server svr;
  17528. size_t observed_trailer_count = 0;
  17529. std::string observed_hello;
  17530. std::string observed_world;
  17531. bool observed_content_length = true;
  17532. svr.Get("/", [&](const Request &req, Response &res) {
  17533. observed_trailer_count = req.trailers.size();
  17534. observed_hello = req.get_trailer_value("X-Hello");
  17535. observed_world = req.get_trailer_value("X-World");
  17536. observed_content_length = req.has_trailer("Content-Length");
  17537. res.set_content("ok", "text/plain");
  17538. });
  17539. auto port = svr.bind_to_any_port(HOST);
  17540. thread t = thread([&]() { svr.listen_after_bind(); });
  17541. auto se = detail::scope_exit([&] {
  17542. svr.stop();
  17543. t.join();
  17544. ASSERT_FALSE(svr.is_running());
  17545. });
  17546. svr.wait_until_ready();
  17547. const std::string req = "GET / HTTP/1.1\r\n"
  17548. "Host: localhost\r\n"
  17549. "Transfer-Encoding: chunked\r\n"
  17550. "Trailer: X-Hello\r\n"
  17551. "Trailer: X-World, Content-Length\r\n"
  17552. "\r\n"
  17553. "0\r\n"
  17554. "X-Hello: hello\r\n"
  17555. "X-World: world\r\n"
  17556. "Content-Length: 10\r\n"
  17557. "\r\n";
  17558. std::string res;
  17559. ASSERT_TRUE(send_request(1, req, &res, port));
  17560. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17561. // Accepted: both field lines contribute to the declared set
  17562. EXPECT_EQ(2U, observed_trailer_count);
  17563. EXPECT_EQ(observed_hello, "hello");
  17564. EXPECT_EQ(observed_world, "world");
  17565. // Denied: a prohibited name stays prohibited on a later field line
  17566. EXPECT_FALSE(observed_content_length);
  17567. }
  17568. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17569. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17570. // unbounded run of fields that are never declared, because the counter would
  17571. // only advance for declared fields.
  17572. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17573. Server svr;
  17574. bool handler_called = false;
  17575. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17576. handler_called = true;
  17577. res.set_content("ok", "text/plain");
  17578. });
  17579. auto port = svr.bind_to_any_port(HOST);
  17580. thread t = thread([&]() { svr.listen_after_bind(); });
  17581. auto se = detail::scope_exit([&] {
  17582. svr.stop();
  17583. t.join();
  17584. ASSERT_FALSE(svr.is_running());
  17585. });
  17586. svr.wait_until_ready();
  17587. // Declare nothing, then send far more undeclared trailer fields than the
  17588. // header-count limit. Parsing must stop and reject the request rather than
  17589. // read every line.
  17590. std::string req = "GET / HTTP/1.1\r\n"
  17591. "Transfer-Encoding: chunked\r\n"
  17592. "\r\n"
  17593. "0\r\n";
  17594. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17595. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17596. }
  17597. req += "\r\n";
  17598. std::string res;
  17599. ASSERT_TRUE(send_request(1, req, &res, port));
  17600. // The request is rejected before the handler runs.
  17601. EXPECT_FALSE(handler_called);
  17602. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17603. }
  17604. // The set of declared trailer names is capped so a peer cannot grow it without
  17605. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17606. // declared past the cap is not honored, even if the field is actually sent.
  17607. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17608. Server svr;
  17609. // One name inside the cap and one past it, so the test tracks the cap rather
  17610. // than a fixed count.
  17611. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17612. const std::string within_cap_name = "X-T-0";
  17613. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17614. bool observed_within_cap = false;
  17615. bool observed_past_cap = false;
  17616. svr.Get("/", [&](const Request &req, Response &res) {
  17617. observed_within_cap = req.has_trailer(within_cap_name);
  17618. observed_past_cap = req.has_trailer(past_cap_name);
  17619. res.set_content("ok", "text/plain");
  17620. });
  17621. auto port = svr.bind_to_any_port(HOST);
  17622. thread t = thread([&]() { svr.listen_after_bind(); });
  17623. auto se = detail::scope_exit([&] {
  17624. svr.stop();
  17625. t.join();
  17626. ASSERT_FALSE(svr.is_running());
  17627. });
  17628. svr.wait_until_ready();
  17629. // Declare more trailer names than the cap in a single Trailer field, then
  17630. // actually send the first (within the cap) and the last (past it).
  17631. std::string trailer_decl = "Trailer: ";
  17632. for (int i = 0; i < declared_count; i++) {
  17633. if (i != 0) { trailer_decl += ", "; }
  17634. trailer_decl += "X-T-" + std::to_string(i);
  17635. }
  17636. trailer_decl += "\r\n";
  17637. const std::string req = "GET / HTTP/1.1\r\n"
  17638. "Host: localhost\r\n"
  17639. "Transfer-Encoding: chunked\r\n" +
  17640. trailer_decl +
  17641. "\r\n"
  17642. "0\r\n" +
  17643. within_cap_name + ": a\r\n" + past_cap_name +
  17644. ": b\r\n"
  17645. "\r\n";
  17646. std::string res;
  17647. ASSERT_TRUE(send_request(1, req, &res, port));
  17648. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17649. // A name within the cap is honored; one declared past the cap is dropped.
  17650. EXPECT_TRUE(observed_within_cap);
  17651. EXPECT_FALSE(observed_past_cap);
  17652. }
  17653. // A direct client that is not listed in trusted_proxies must not be able to
  17654. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17655. // the peer address on the actual TCP connection determines whether the
  17656. // header is honored.
  17657. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17658. Server svr;
  17659. // Deliberately does NOT include the loopback address the test client
  17660. // actually connects from, so the direct connection is not a trusted proxy.
  17661. svr.set_trusted_proxies({"203.0.113.66"});
  17662. std::string observed_remote_addr;
  17663. svr.Get("/ip", [&](const Request &req, Response &res) {
  17664. observed_remote_addr = req.remote_addr;
  17665. res.set_content("ok", "text/plain");
  17666. });
  17667. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17668. auto se = detail::scope_exit([&] {
  17669. svr.stop();
  17670. t.join();
  17671. ASSERT_FALSE(svr.is_running());
  17672. });
  17673. svr.wait_until_ready();
  17674. Client cli(HOST, PORT);
  17675. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17677. EXPECT_EQ(StatusCode::OK_200, res->status);
  17678. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17679. // ignored entirely and the real connection-level address retained.
  17680. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17681. observed_remote_addr == "127.0.0.1");
  17682. }
  17683. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17684. Server svr;
  17685. std::string observed_remote_addr;
  17686. std::string observed_xff;
  17687. svr.Get("/ip", [&](const Request &req, Response &res) {
  17688. observed_remote_addr = req.remote_addr;
  17689. observed_xff = req.get_header_value("X-Forwarded-For");
  17690. res.set_content("ok", "text/plain");
  17691. });
  17692. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17693. auto se = detail::scope_exit([&] {
  17694. svr.stop();
  17695. t.join();
  17696. ASSERT_FALSE(svr.is_running());
  17697. });
  17698. svr.wait_until_ready();
  17699. Client cli(HOST, PORT);
  17700. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17702. EXPECT_EQ(StatusCode::OK_200, res->status);
  17703. EXPECT_EQ(observed_xff, "203.0.113.66");
  17704. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17705. observed_remote_addr == "127.0.0.1");
  17706. }
  17707. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17708. Server svr;
  17709. svr.set_trusted_proxies({"203.0.113.66"});
  17710. std::string observed_remote_addr;
  17711. std::string observed_xff;
  17712. svr.Get("/ip", [&](const Request &req, Response &res) {
  17713. observed_remote_addr = req.remote_addr;
  17714. observed_xff = req.get_header_value("X-Forwarded-For");
  17715. res.set_content("ok", "text/plain");
  17716. });
  17717. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17718. auto se = detail::scope_exit([&] {
  17719. svr.stop();
  17720. t.join();
  17721. ASSERT_FALSE(svr.is_running());
  17722. });
  17723. svr.wait_until_ready();
  17724. Client cli(HOST, PORT);
  17725. auto res = cli.Get("/ip");
  17726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17727. EXPECT_EQ(StatusCode::OK_200, res->status);
  17728. EXPECT_EQ(observed_xff, "");
  17729. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17730. observed_remote_addr == "127.0.0.1");
  17731. }
  17732. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17733. Server svr;
  17734. // Include the loopback address the test client actually connects from, so
  17735. // the direct connection itself is recognized as the trusted proxy hop.
  17736. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17737. std::string observed_remote_addr;
  17738. std::string observed_xff;
  17739. svr.Get("/ip", [&](const Request &req, Response &res) {
  17740. observed_remote_addr = req.remote_addr;
  17741. observed_xff = req.get_header_value("X-Forwarded-For");
  17742. res.set_content("ok", "text/plain");
  17743. });
  17744. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17745. auto se = detail::scope_exit([&] {
  17746. svr.stop();
  17747. t.join();
  17748. ASSERT_FALSE(svr.is_running());
  17749. });
  17750. svr.wait_until_ready();
  17751. Client cli(HOST, PORT);
  17752. auto res = cli.Get(
  17753. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17755. EXPECT_EQ(StatusCode::OK_200, res->status);
  17756. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17757. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17758. }
  17759. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17760. Server svr;
  17761. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17762. std::string observed_remote_addr;
  17763. std::string observed_xff;
  17764. svr.Get("/ip", [&](const Request &req, Response &res) {
  17765. observed_remote_addr = req.remote_addr;
  17766. observed_xff = req.get_header_value("X-Forwarded-For");
  17767. res.set_content("ok", "text/plain");
  17768. });
  17769. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17770. auto se = detail::scope_exit([&] {
  17771. svr.stop();
  17772. t.join();
  17773. ASSERT_FALSE(svr.is_running());
  17774. });
  17775. svr.wait_until_ready();
  17776. Client cli(HOST, PORT);
  17777. auto res = cli.Get(
  17778. "/ip",
  17779. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17781. EXPECT_EQ(StatusCode::OK_200, res->status);
  17782. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17783. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17784. }
  17785. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17786. Server svr;
  17787. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17788. std::string observed_remote_addr;
  17789. std::string observed_xff;
  17790. svr.Get("/ip", [&](const Request &req, Response &res) {
  17791. observed_remote_addr = req.remote_addr;
  17792. observed_xff = req.get_header_value("X-Forwarded-For");
  17793. res.set_content("ok", "text/plain");
  17794. });
  17795. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17796. auto se = detail::scope_exit([&] {
  17797. svr.stop();
  17798. t.join();
  17799. ASSERT_FALSE(svr.is_running());
  17800. });
  17801. svr.wait_until_ready();
  17802. Client cli(HOST, PORT);
  17803. auto res = cli.Get(
  17804. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17806. EXPECT_EQ(StatusCode::OK_200, res->status);
  17807. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17808. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17809. // and must not be selected.
  17810. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17811. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17812. }
  17813. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17814. Server svr;
  17815. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17816. std::string observed_remote_addr;
  17817. svr.Get("/ip", [&](const Request &req, Response &res) {
  17818. observed_remote_addr = req.remote_addr;
  17819. res.set_content("ok", "text/plain");
  17820. });
  17821. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17822. auto se = detail::scope_exit([&] {
  17823. svr.stop();
  17824. t.join();
  17825. ASSERT_FALSE(svr.is_running());
  17826. });
  17827. svr.wait_until_ready();
  17828. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17829. // a forged address and the trusted proxy's own address; the forged value must
  17830. // not win over the address the trusted proxy actually recorded.
  17831. Client cli(HOST, PORT);
  17832. auto res = cli.Get(
  17833. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17835. EXPECT_EQ(StatusCode::OK_200, res->status);
  17836. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17837. }
  17838. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17839. Server svr;
  17840. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17841. std::string observed_remote_addr;
  17842. std::string observed_xff;
  17843. svr.Get("/ip", [&](const Request &req, Response &res) {
  17844. observed_remote_addr = req.remote_addr;
  17845. observed_xff = req.get_header_value("X-Forwarded-For");
  17846. res.set_content("ok", "text/plain");
  17847. });
  17848. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17849. auto se = detail::scope_exit([&] {
  17850. svr.stop();
  17851. t.join();
  17852. ASSERT_FALSE(svr.is_running());
  17853. });
  17854. svr.wait_until_ready();
  17855. Client cli(HOST, PORT);
  17856. auto res = cli.Get(
  17857. "/ip",
  17858. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17860. EXPECT_EQ(StatusCode::OK_200, res->status);
  17861. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17862. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17863. }
  17864. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17865. Server svr;
  17866. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17867. std::string observed_remote_addr;
  17868. std::string observed_xff;
  17869. svr.Get("/ip", [&](const Request &req, Response &res) {
  17870. observed_remote_addr = req.remote_addr;
  17871. observed_xff = req.get_header_value("X-Forwarded-For");
  17872. res.set_content("ok", "text/plain");
  17873. });
  17874. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17875. auto se = detail::scope_exit([&] {
  17876. svr.stop();
  17877. t.join();
  17878. ASSERT_FALSE(svr.is_running());
  17879. });
  17880. svr.wait_until_ready();
  17881. std::string raw_req =
  17882. "GET /ip HTTP/1.1\r\n"
  17883. "Host: localhost\r\n"
  17884. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17885. "Connection: close\r\n"
  17886. "\r\n";
  17887. std::string out;
  17888. ASSERT_TRUE(send_request(5, raw_req, &out));
  17889. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17890. // Header parser trims surrounding whitespace of the header value
  17891. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17892. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17893. }
  17894. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17895. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17896. // their own X-Forwarded-For as a separate field line rather than extending the
  17897. // one the client sent, so every occurrence has to be taken into account.
  17898. // Reading only the first one hands back the address the client chose.
  17899. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17900. Server svr;
  17901. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17902. std::string observed_remote_addr;
  17903. size_t observed_xff_count = 0;
  17904. svr.Get("/ip", [&](const Request &req, Response &res) {
  17905. observed_remote_addr = req.remote_addr;
  17906. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17907. res.set_content("ok", "text/plain");
  17908. });
  17909. auto port = svr.bind_to_any_port(HOST);
  17910. thread t = thread([&]() { svr.listen_after_bind(); });
  17911. auto se = detail::scope_exit([&] {
  17912. svr.stop();
  17913. t.join();
  17914. ASSERT_FALSE(svr.is_running());
  17915. });
  17916. svr.wait_until_ready();
  17917. // The client supplies the first field line; the trusted proxy appends the
  17918. // address it observed as a second one.
  17919. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17920. "Host: localhost\r\n"
  17921. "X-Forwarded-For: 1.2.3.4\r\n"
  17922. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17923. "Connection: close\r\n"
  17924. "\r\n";
  17925. std::string out;
  17926. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17927. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17928. EXPECT_EQ(observed_xff_count, 2U);
  17929. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17930. // The same chain spread over one field line per hop derives the same client
  17931. // address, i.e. the split and the comma-joined representations agree.
  17932. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17933. "Host: localhost\r\n"
  17934. "X-Forwarded-For: 1.2.3.4\r\n"
  17935. "X-Forwarded-For: 198.51.100.23\r\n"
  17936. "X-Forwarded-For: 192.0.2.45\r\n"
  17937. "Connection: close\r\n"
  17938. "\r\n";
  17939. out.clear();
  17940. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17941. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17942. EXPECT_EQ(observed_xff_count, 3U);
  17943. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17944. }
  17945. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17946. // crash the server (it used to call front() on an empty vector inside
  17947. // get_client_ip). The connection-level remote address must be retained instead.
  17948. static void run_malformed_xff_test(const std::string &xff_value) {
  17949. Server svr;
  17950. svr.set_trusted_proxies({"192.0.2.45"});
  17951. std::string observed_remote_addr;
  17952. svr.Get("/ip", [&](const Request &req, Response &res) {
  17953. observed_remote_addr = req.remote_addr;
  17954. res.set_content("ok", "text/plain");
  17955. });
  17956. int port = 0;
  17957. thread t = thread([&]() {
  17958. port = svr.bind_to_any_port(HOST);
  17959. svr.listen_after_bind();
  17960. });
  17961. auto se = detail::scope_exit([&] {
  17962. svr.stop();
  17963. t.join();
  17964. ASSERT_FALSE(svr.is_running());
  17965. });
  17966. svr.wait_until_ready();
  17967. Client cli(HOST, port);
  17968. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17970. EXPECT_EQ(StatusCode::OK_200, res->status);
  17971. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17972. observed_remote_addr == "127.0.0.1");
  17973. }
  17974. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17975. run_malformed_xff_test("");
  17976. }
  17977. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17978. run_malformed_xff_test(",");
  17979. }
  17980. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17981. run_malformed_xff_test(", , ,");
  17982. }
  17983. // The same rule applies to Accept: a request whose acceptable types are spread
  17984. // over several field lines must be negotiated against all of them.
  17985. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17986. // case-insensitive connection options. Comparing the whole field value against
  17987. // one option misses a client that sends several of them, and misses every
  17988. // casing but the one written in the comparison.
  17989. //
  17990. // Sends req, reads the response, then reuses the same socket for a second
  17991. // request to find out whether the server kept the connection.
  17992. static void probe_connection_reuse(int port, const std::string &req,
  17993. bool *announced_close, bool *reusable) {
  17994. auto error = Error::Success;
  17995. auto sock = detail::create_client_socket(
  17996. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17997. /*connection_timeout_sec=*/5, 0,
  17998. /*read_timeout_sec=*/1, 0,
  17999. /*write_timeout_sec=*/5, 0, std::string(), error);
  18000. ASSERT_NE(sock, INVALID_SOCKET);
  18001. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18002. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18003. "Host: localhost\r\n"
  18004. "Connection: close\r\n"
  18005. "\r\n";
  18006. std::string first_response;
  18007. std::string second_response;
  18008. detail::process_client_socket(
  18009. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18010. [&](Stream &strm) {
  18011. if (strm.write(req.data(), req.size()) !=
  18012. static_cast<ssize_t>(req.size())) {
  18013. return false;
  18014. }
  18015. char buf[512];
  18016. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18017. // Headers plus the two-byte body of the handler below
  18018. while (reader.getline()) {
  18019. first_response += reader.ptr();
  18020. if (first_response.find("ok") != std::string::npos) { break; }
  18021. }
  18022. if (strm.write(second.data(), second.size()) !=
  18023. static_cast<ssize_t>(second.size())) {
  18024. return true;
  18025. }
  18026. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18027. while (reader2.getline()) {
  18028. second_response += reader2.ptr();
  18029. if (second_response.find("ok") != std::string::npos) { break; }
  18030. }
  18031. return true;
  18032. });
  18033. *announced_close =
  18034. first_response.find("Connection: close") != std::string::npos;
  18035. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18036. }
  18037. class ConnectionTokenTest : public ::testing::Test {
  18038. protected:
  18039. void SetUp() override {
  18040. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18041. res.set_content("ok", "text/plain");
  18042. });
  18043. port_ = svr_.bind_to_any_port(HOST);
  18044. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18045. svr_.wait_until_ready();
  18046. }
  18047. void TearDown() override {
  18048. svr_.stop();
  18049. if (thread_.joinable()) { thread_.join(); }
  18050. }
  18051. Server svr_;
  18052. int port_ = 0;
  18053. thread thread_;
  18054. };
  18055. // "close" alongside another option still closes the connection, and the
  18056. // response says so rather than leaving the peer to discover it.
  18057. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18058. bool announced_close = false;
  18059. bool reusable = true;
  18060. probe_connection_reuse(port_,
  18061. "GET /keepalive HTTP/1.1\r\n"
  18062. "Host: localhost\r\n"
  18063. "Connection: keep-alive, close\r\n"
  18064. "\r\n",
  18065. &announced_close, &reusable);
  18066. EXPECT_TRUE(announced_close);
  18067. EXPECT_FALSE(reusable);
  18068. }
  18069. // "close" split over two field lines is the same list, so it is honored too.
  18070. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18071. bool announced_close = false;
  18072. bool reusable = true;
  18073. probe_connection_reuse(port_,
  18074. "GET /keepalive HTTP/1.1\r\n"
  18075. "Host: localhost\r\n"
  18076. "Connection: keep-alive\r\n"
  18077. "Connection: close\r\n"
  18078. "\r\n",
  18079. &announced_close, &reusable);
  18080. EXPECT_TRUE(announced_close);
  18081. EXPECT_FALSE(reusable);
  18082. }
  18083. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18084. // keep-alive in the spelling everyone actually sends keeps its connection.
  18085. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18086. bool announced_close = false;
  18087. bool reusable = false;
  18088. probe_connection_reuse(port_,
  18089. "GET /keepalive HTTP/1.0\r\n"
  18090. "Host: localhost\r\n"
  18091. "Connection: keep-alive\r\n"
  18092. "\r\n",
  18093. &announced_close, &reusable);
  18094. EXPECT_FALSE(announced_close);
  18095. EXPECT_TRUE(reusable);
  18096. }
  18097. // A token the value merely contains is not the token itself.
  18098. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18099. bool announced_close = false;
  18100. bool reusable = false;
  18101. probe_connection_reuse(port_,
  18102. "GET /keepalive HTTP/1.1\r\n"
  18103. "Host: localhost\r\n"
  18104. "Connection: notclose\r\n"
  18105. "\r\n",
  18106. &announced_close, &reusable);
  18107. EXPECT_FALSE(announced_close);
  18108. EXPECT_TRUE(reusable);
  18109. }
  18110. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18111. Server svr;
  18112. std::vector<std::string> observed_types;
  18113. svr.Get("/", [&](const Request &req, Response &res) {
  18114. observed_types = req.accept_content_types;
  18115. res.set_content("ok", "text/plain");
  18116. });
  18117. auto port = svr.bind_to_any_port(HOST);
  18118. thread t = thread([&]() { svr.listen_after_bind(); });
  18119. auto se = detail::scope_exit([&] {
  18120. svr.stop();
  18121. t.join();
  18122. ASSERT_FALSE(svr.is_running());
  18123. });
  18124. svr.wait_until_ready();
  18125. Client cli(HOST, port);
  18126. Headers headers;
  18127. headers.emplace("Accept", "text/plain;q=0.5");
  18128. headers.emplace("Accept", "application/json");
  18129. auto res = cli.Get("/", headers);
  18130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18131. EXPECT_EQ(StatusCode::OK_200, res->status);
  18132. // Sorted by q-value, so the second field line's type comes first
  18133. ASSERT_EQ(2U, observed_types.size());
  18134. EXPECT_EQ("application/json", observed_types[0]);
  18135. EXPECT_EQ("text/plain", observed_types[1]);
  18136. }
  18137. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18138. // empty field line must not contribute a bare comma to the combined value.
  18139. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18140. Server svr;
  18141. std::vector<std::string> observed_types;
  18142. svr.Get("/", [&](const Request &req, Response &res) {
  18143. observed_types = req.accept_content_types;
  18144. res.set_content("ok", "text/plain");
  18145. });
  18146. auto port = svr.bind_to_any_port(HOST);
  18147. thread t = thread([&]() { svr.listen_after_bind(); });
  18148. auto se = detail::scope_exit([&] {
  18149. svr.stop();
  18150. t.join();
  18151. ASSERT_FALSE(svr.is_running());
  18152. });
  18153. svr.wait_until_ready();
  18154. // Empty first field line, then a real one
  18155. std::string raw_req = "GET / HTTP/1.1\r\n"
  18156. "Host: localhost\r\n"
  18157. "Accept:\r\n"
  18158. "Accept: application/json\r\n"
  18159. "Connection: close\r\n"
  18160. "\r\n";
  18161. std::string out;
  18162. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18163. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18164. ASSERT_EQ(1U, observed_types.size());
  18165. EXPECT_EQ("application/json", observed_types[0]);
  18166. }
  18167. // The skip in get_combined_header_value() is what keeps an empty field line
  18168. // from contributing a bare comma. Only a trailing empty field line exercises
  18169. // it: a leading one is already covered by the "combined is still empty" check,
  18170. // and parse_accept_header() now ignores the empty element either way, so the
  18171. // request-level test above can no longer tell the two apart.
  18172. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18173. Headers headers;
  18174. headers.emplace("Accept", "text/html");
  18175. headers.emplace("Accept", "");
  18176. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18177. headers.clear();
  18178. headers.emplace("Accept", "");
  18179. headers.emplace("Accept", "application/json");
  18180. EXPECT_EQ("application/json",
  18181. detail::get_combined_header_value(headers, "Accept"));
  18182. }
  18183. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18184. // An encoding offered on a later Accept-Encoding field line is still offered.
  18185. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18186. Server svr;
  18187. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18188. res.set_content(std::string(1024, 'x'), "text/plain");
  18189. });
  18190. auto port = svr.bind_to_any_port(HOST);
  18191. thread t = thread([&]() { svr.listen_after_bind(); });
  18192. auto se = detail::scope_exit([&] {
  18193. svr.stop();
  18194. t.join();
  18195. ASSERT_FALSE(svr.is_running());
  18196. });
  18197. svr.wait_until_ready();
  18198. Client cli(HOST, port);
  18199. cli.set_decompress(false);
  18200. Headers headers;
  18201. headers.emplace("Accept-Encoding", "identity");
  18202. headers.emplace("Accept-Encoding", "gzip");
  18203. auto res = cli.Get("/", headers);
  18204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18205. EXPECT_EQ(StatusCode::OK_200, res->status);
  18206. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18207. }
  18208. #endif
  18209. #ifndef _WIN32
  18210. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18211. Server svr;
  18212. svr.Post("/post", [&](const Request &req, Response &res) {
  18213. res.set_content(req.body, "text/plain");
  18214. });
  18215. svr.Put("/put", [&](const Request &req, Response &res) {
  18216. res.set_content(req.body, "text/plain");
  18217. });
  18218. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18219. res.set_content(req.body, "text/plain");
  18220. });
  18221. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18222. res.set_content(req.body, "text/plain");
  18223. });
  18224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18225. auto se = detail::scope_exit([&] {
  18226. svr.stop();
  18227. t.join();
  18228. ASSERT_FALSE(svr.is_running());
  18229. });
  18230. svr.wait_until_ready();
  18231. std::string resp;
  18232. // POST without Content-Length
  18233. ASSERT_TRUE(send_request(5,
  18234. "POST /post HTTP/1.1\r\n"
  18235. "Host: localhost\r\n"
  18236. "Connection: close\r\n"
  18237. "\r\n",
  18238. &resp));
  18239. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18240. // PUT without Content-Length
  18241. resp.clear();
  18242. ASSERT_TRUE(send_request(5,
  18243. "PUT /put HTTP/1.1\r\n"
  18244. "Host: localhost\r\n"
  18245. "Connection: close\r\n"
  18246. "\r\n",
  18247. &resp));
  18248. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18249. // PATCH without Content-Length
  18250. resp.clear();
  18251. ASSERT_TRUE(send_request(5,
  18252. "PATCH /patch HTTP/1.1\r\n"
  18253. "Host: localhost\r\n"
  18254. "Connection: close\r\n"
  18255. "\r\n",
  18256. &resp));
  18257. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18258. // DELETE without Content-Length
  18259. resp.clear();
  18260. ASSERT_TRUE(send_request(5,
  18261. "DELETE /delete HTTP/1.1\r\n"
  18262. "Host: localhost\r\n"
  18263. "Connection: close\r\n"
  18264. "\r\n",
  18265. &resp));
  18266. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18267. }
  18268. #endif
  18269. //==============================================================================
  18270. // open_stream() Tests
  18271. //==============================================================================
  18272. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18273. std::string result;
  18274. char buf[8192];
  18275. ssize_t n;
  18276. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18277. result.append(buf, static_cast<size_t>(n));
  18278. }
  18279. return result;
  18280. }
  18281. // Mock stream for unit tests
  18282. class MockStream : public Stream {
  18283. public:
  18284. std::string data;
  18285. size_t pos = 0;
  18286. ssize_t error_after = -1; // -1 = no error
  18287. explicit MockStream(const std::string &d, ssize_t err = -1)
  18288. : data(d), error_after(err) {}
  18289. bool is_readable() const override { return true; }
  18290. bool wait_readable() const override { return true; }
  18291. bool wait_writable() const override { return true; }
  18292. ssize_t read(char *ptr, size_t size) override {
  18293. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18294. if (pos >= data.size()) return 0;
  18295. size_t limit =
  18296. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18297. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18298. std::memcpy(ptr, data.data() + pos, to_read);
  18299. pos += to_read;
  18300. return static_cast<ssize_t>(to_read);
  18301. }
  18302. ssize_t write(const char *, size_t) override { return -1; }
  18303. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18304. ip = "127.0.0.1";
  18305. port = 0;
  18306. }
  18307. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18308. ip = "127.0.0.1";
  18309. port = 0;
  18310. }
  18311. socket_t socket() const override { return INVALID_SOCKET; }
  18312. time_t duration() const override { return 0; }
  18313. };
  18314. TEST(StreamHandleTest, Basic) {
  18315. ClientImpl::StreamHandle handle;
  18316. EXPECT_FALSE(handle.is_valid());
  18317. handle.response = detail::make_unique<Response>();
  18318. handle.error = Error::Connection;
  18319. EXPECT_FALSE(handle.is_valid());
  18320. handle.error = Error::Success;
  18321. EXPECT_TRUE(handle.is_valid());
  18322. }
  18323. TEST(BodyReaderTest, Basic) {
  18324. MockStream stream("Hello, World!");
  18325. detail::BodyReader reader;
  18326. reader.stream = &stream;
  18327. reader.content_length = 13;
  18328. char buf[32];
  18329. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18330. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18331. EXPECT_TRUE(reader.eof);
  18332. }
  18333. TEST(BodyReaderTest, NoStream) {
  18334. detail::BodyReader reader;
  18335. char buf[32];
  18336. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18337. EXPECT_EQ(Error::Connection, reader.last_error);
  18338. }
  18339. TEST(BodyReaderTest, Error) {
  18340. MockStream stream("Hello, World!", 5);
  18341. detail::BodyReader reader;
  18342. reader.stream = &stream;
  18343. reader.content_length = 13;
  18344. char buf[32];
  18345. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18346. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18347. EXPECT_EQ(Error::Read, reader.last_error);
  18348. }
  18349. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18350. // Mock-based StreamHandle tests relying on private internals are removed.
  18351. class OpenStreamTest : public ::testing::Test {
  18352. protected:
  18353. void SetUp() override {
  18354. svr_.Get("/hello", [](const Request &, Response &res) {
  18355. res.set_content("Hello World!", "text/plain");
  18356. });
  18357. svr_.Get("/large", [](const Request &, Response &res) {
  18358. res.set_content(std::string(10000, 'X'), "text/plain");
  18359. });
  18360. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18361. res.set_content("Hello World!", "image/jpeg");
  18362. res.set_header("Content-Encoding", "UTF-8");
  18363. });
  18364. svr_.Get("/chunked", [](const Request &, Response &res) {
  18365. res.set_chunked_content_provider("text/plain",
  18366. [](size_t offset, DataSink &sink) {
  18367. if (offset < 15) {
  18368. sink.write("chunk", 5);
  18369. return true;
  18370. }
  18371. sink.done();
  18372. return true;
  18373. });
  18374. });
  18375. svr_.Get("/compressible", [](const Request &, Response &res) {
  18376. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18377. DataSink &sink) {
  18378. if (offset < 100 * 1024) {
  18379. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18380. sink.write(chunk.data(), chunk.size());
  18381. return true;
  18382. }
  18383. sink.done();
  18384. return true;
  18385. });
  18386. });
  18387. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18388. [](const Request & /*req*/, Response &res) {
  18389. auto i = new int(0);
  18390. res.set_header("Trailer", "Content-Length, X-Allowed");
  18391. res.set_chunked_content_provider(
  18392. "text/plain",
  18393. [i](size_t /*offset*/, DataSink &sink) {
  18394. switch (*i) {
  18395. case 0: sink.os << "123"; break;
  18396. case 1: sink.os << "456"; break;
  18397. case 2: sink.os << "789"; break;
  18398. case 3: {
  18399. sink.done_with_trailer(
  18400. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18401. } break;
  18402. }
  18403. (*i)++;
  18404. return true;
  18405. },
  18406. [i](bool success) {
  18407. EXPECT_TRUE(success);
  18408. delete i;
  18409. });
  18410. });
  18411. // Echo headers endpoint for header-related tests
  18412. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18413. std::string body;
  18414. for (const auto &h : req.headers) {
  18415. body.append(h.first);
  18416. body.push_back(':');
  18417. body.append(h.second);
  18418. body.push_back('\n');
  18419. }
  18420. res.set_content(body, "text/plain");
  18421. });
  18422. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18423. std::string body;
  18424. for (const auto &h : req.headers) {
  18425. body.append(h.first);
  18426. body.push_back(':');
  18427. body.append(h.second);
  18428. body.push_back('\n');
  18429. }
  18430. res.set_content(body, "text/plain");
  18431. });
  18432. port_ = svr_.bind_to_any_port("127.0.0.1");
  18433. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18434. svr_.wait_until_ready();
  18435. }
  18436. void TearDown() override {
  18437. svr_.stop();
  18438. if (thread_.joinable()) thread_.join();
  18439. }
  18440. Server svr_;
  18441. std::thread thread_;
  18442. int port_ = 0;
  18443. };
  18444. TEST_F(OpenStreamTest, Basic) {
  18445. Client cli("127.0.0.1", port_);
  18446. auto handle = cli.open_stream("GET", "/hello");
  18447. EXPECT_TRUE(handle.is_valid());
  18448. EXPECT_EQ("Hello World!", read_all(handle));
  18449. }
  18450. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18451. Client cli("127.0.0.1", port_);
  18452. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18453. ASSERT_TRUE(handle.is_valid());
  18454. EXPECT_EQ("Hello World!", read_all(handle));
  18455. }
  18456. TEST_F(OpenStreamTest, SmallBuffer) {
  18457. Client cli("127.0.0.1", port_);
  18458. auto handle = cli.open_stream("GET", "/hello");
  18459. std::string result;
  18460. char buf[4];
  18461. ssize_t n;
  18462. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18463. result.append(buf, static_cast<size_t>(n));
  18464. EXPECT_EQ("Hello World!", result);
  18465. }
  18466. TEST_F(OpenStreamTest, DefaultHeaders) {
  18467. Client cli("127.0.0.1", port_);
  18468. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18469. {
  18470. auto handle = cli.open_stream("GET", "/echo-headers");
  18471. ASSERT_TRUE(handle.is_valid());
  18472. auto body = read_all(handle);
  18473. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18474. std::string::npos);
  18475. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18476. std::string::npos);
  18477. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18478. }
  18479. // open_stream POST with body and no explicit content_type should NOT add
  18480. // text/plain Content-Type (behavior differs from non-streaming path), but
  18481. // should include Content-Length
  18482. {
  18483. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18484. ASSERT_TRUE(handle.is_valid());
  18485. auto body = read_all(handle);
  18486. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18487. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18488. }
  18489. // open_stream POST with explicit Content-Type should preserve it
  18490. {
  18491. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18492. {{"Content-Type", "application/custom"}},
  18493. "{}", "application/custom");
  18494. ASSERT_TRUE(handle.is_valid());
  18495. auto body = read_all(handle);
  18496. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18497. }
  18498. // User-specified User-Agent must not be overwritten for stream API
  18499. {
  18500. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18501. {{"User-Agent", "MyAgent/1.2"}});
  18502. ASSERT_TRUE(handle.is_valid());
  18503. auto body = read_all(handle);
  18504. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18505. }
  18506. }
  18507. TEST_F(OpenStreamTest, Large) {
  18508. Client cli("127.0.0.1", port_);
  18509. auto handle = cli.open_stream("GET", "/large");
  18510. EXPECT_EQ(10000u, read_all(handle).size());
  18511. }
  18512. TEST_F(OpenStreamTest, ConnectionError) {
  18513. Client cli("127.0.0.1", 9999);
  18514. auto handle = cli.open_stream("GET", "/hello");
  18515. EXPECT_FALSE(handle.is_valid());
  18516. }
  18517. TEST_F(OpenStreamTest, Chunked) {
  18518. Client cli("127.0.0.1", port_);
  18519. auto handle = cli.open_stream("GET", "/chunked");
  18520. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18521. "Transfer-Encoding") == "chunked");
  18522. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18523. }
  18524. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18525. Client cli("127.0.0.1", port_);
  18526. auto handle =
  18527. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18528. ASSERT_TRUE(handle.is_valid());
  18529. // Consume body to allow trailers to be received/parsed
  18530. auto body = read_all(handle);
  18531. // Explicitly parse trailers (ensure trailers are available for assertion)
  18532. handle.parse_trailers_if_needed();
  18533. EXPECT_EQ(std::string("123456789"), body);
  18534. // The response should include a Trailer header declaring both names
  18535. ASSERT_TRUE(handle.response);
  18536. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18537. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18538. handle.response->get_header_value("Trailer"));
  18539. // Prohibited trailer must not be present
  18540. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18541. // Allowed trailer should be present
  18542. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18543. EXPECT_EQ(std::string("yes"),
  18544. handle.response->get_trailer_value("X-Allowed"));
  18545. // Verify trailers are NOT present as regular headers
  18546. EXPECT_EQ(std::string(""),
  18547. handle.response->get_header_value("Content-Length"));
  18548. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18549. }
  18550. // Accepts one connection on an OS-assigned port, which it hands over through
  18551. // port_promise, reads the request head and sends back response. after_send,
  18552. // if given, runs on the connection before it is closed.
  18553. static std::thread
  18554. serve_single_response(std::promise<int> &port_promise,
  18555. const std::string &response,
  18556. std::function<void(socket_t)> after_send = nullptr) {
  18557. return std::thread([&port_promise, response, after_send] {
  18558. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18559. default_socket_options(srv);
  18560. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18561. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18562. sockaddr_in addr{};
  18563. addr.sin_family = AF_INET;
  18564. addr.sin_port = htons(0); // Let OS assign a free port
  18565. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18566. int opt = 1;
  18567. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18568. #ifdef _WIN32
  18569. reinterpret_cast<const char *>(&opt),
  18570. #else
  18571. &opt,
  18572. #endif
  18573. sizeof(opt));
  18574. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18575. ::listen(srv, 1) != 0) {
  18576. port_promise.set_value(-1);
  18577. detail::close_socket(srv);
  18578. return;
  18579. }
  18580. socklen_t addr_len = sizeof(addr);
  18581. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18582. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18583. sockaddr_in cli_addr{};
  18584. socklen_t cli_len = sizeof(cli_addr);
  18585. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18586. if (cli != INVALID_SOCKET) {
  18587. // Read the complete HTTP request (until the blank line that terminates
  18588. // headers) before sending the response. If the server closes the socket
  18589. // while the client's request data is still unread in the kernel receive
  18590. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18591. // connection on both sides: it discards the client's receive buffer
  18592. // (which already holds our response) and causes any in-progress write on
  18593. // the client to fail with ECONNRESET. Reading all request data first
  18594. // ensures close() emits a graceful FIN.
  18595. {
  18596. char rbuf[256];
  18597. std::string req;
  18598. while (req.find("\r\n\r\n") == std::string::npos) {
  18599. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18600. if (n <= 0) { break; }
  18601. req.append(rbuf, static_cast<size_t>(n));
  18602. }
  18603. }
  18604. ::send(cli,
  18605. #ifdef _WIN32
  18606. static_cast<const char *>(response.c_str()),
  18607. static_cast<int>(response.size()),
  18608. #else
  18609. response.c_str(), response.size(),
  18610. #endif
  18611. 0);
  18612. if (after_send) { after_send(cli); }
  18613. detail::close_socket(cli);
  18614. }
  18615. detail::close_socket(srv);
  18616. });
  18617. }
  18618. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18619. #ifndef _WIN32
  18620. signal(SIGPIPE, SIG_IGN);
  18621. #endif
  18622. std::promise<int> port_promise;
  18623. auto port_future = port_promise.get_future();
  18624. auto server_thread =
  18625. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18626. "Content-Type: text/plain\r\n"
  18627. "Content-Length: not-a-number\r\n"
  18628. "Connection: close\r\n"
  18629. "\r\n"
  18630. "hello");
  18631. auto port = port_future.get();
  18632. ASSERT_GT(port, 0);
  18633. Client cli("127.0.0.1", port);
  18634. auto handle = cli.open_stream("GET", "/");
  18635. EXPECT_FALSE(handle.is_valid());
  18636. server_thread.join();
  18637. }
  18638. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18639. #ifndef _WIN32
  18640. signal(SIGPIPE, SIG_IGN);
  18641. #endif
  18642. std::promise<int> port_promise;
  18643. auto port_future = port_promise.get_future();
  18644. auto server_thread = serve_single_response(
  18645. port_promise, "HTTP/1.1 200 OK\r\n"
  18646. "Content-Type: text/plain\r\n"
  18647. "Content-Length: 99999999999999999999999999\r\n"
  18648. "Connection: close\r\n"
  18649. "\r\n"
  18650. "hello");
  18651. auto port = port_future.get();
  18652. ASSERT_GT(port, 0);
  18653. // Historically std::stoull would throw std::out_of_range here and crash
  18654. // the process, then parsing silently clamped to a bogus framing length and
  18655. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18656. // so the stream fails to open, matching the not-a-number case above. The
  18657. // process still must NOT terminate.
  18658. Client cli("127.0.0.1", port);
  18659. auto handle = cli.open_stream("GET", "/");
  18660. EXPECT_FALSE(handle.is_valid());
  18661. server_thread.join();
  18662. }
  18663. // Serves `response` to the single request `fn` makes with a fresh client.
  18664. template <typename Fn>
  18665. static void with_single_response(const std::string &response, Fn fn) {
  18666. #ifndef _WIN32
  18667. signal(SIGPIPE, SIG_IGN);
  18668. #endif
  18669. std::promise<int> port_promise;
  18670. auto port_future = port_promise.get_future();
  18671. auto server_thread = serve_single_response(port_promise, response);
  18672. auto se = detail::scope_exit([&] { server_thread.join(); });
  18673. auto port = port_future.get();
  18674. ASSERT_GT(port, 0);
  18675. Client cli("127.0.0.1", port);
  18676. fn(cli);
  18677. }
  18678. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18679. const char *responses[] = {
  18680. "HTTP/1.1 103 Early Hints\r\n"
  18681. "Link: </style.css>; rel=preload\r\n"
  18682. "\r\n"
  18683. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18684. "HTTP/1.1 100 Continue\r\n"
  18685. "X-Note: interim\r\n"
  18686. "\r\n"
  18687. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18688. };
  18689. for (auto response : responses) {
  18690. with_single_response(response, [](Client &cli) {
  18691. auto res = cli.Get("/");
  18692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18693. EXPECT_EQ(StatusCode::OK_200, res->status);
  18694. EXPECT_EQ("ok", res->body);
  18695. });
  18696. }
  18697. }
  18698. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  18699. #ifndef _WIN32
  18700. signal(SIGPIPE, SIG_IGN);
  18701. #endif
  18702. // The server answers the head without asking for the body. Bytes it then
  18703. // reads on the connection would be taken for the body the request declared.
  18704. auto closed_by_client = false;
  18705. std::promise<int> port_promise;
  18706. auto server_thread = serve_single_response(
  18707. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  18708. [&](socket_t sock) {
  18709. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18710. char buf[256];
  18711. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  18712. });
  18713. Client cli("127.0.0.1", port_promise.get_future().get());
  18714. cli.set_keep_alive(true);
  18715. cli.set_read_timeout(1, 0);
  18716. // Long enough for the client to send Expect: 100-continue.
  18717. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18719. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18720. cli.Get("/second");
  18721. server_thread.join();
  18722. EXPECT_TRUE(closed_by_client);
  18723. }
  18724. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  18725. // Long enough for the client to send Expect: 100-continue
  18726. with_single_response(
  18727. "HTTP/1.1 103 Early Hints\r\n"
  18728. "Link: </style.css>; rel=preload\r\n"
  18729. "\r\n"
  18730. "HTTP/1.1 401 Unauthorized\r\n"
  18731. "Content-Length: 0\r\n\r\n",
  18732. [](Client &cli) {
  18733. cli.set_read_timeout(2, 0);
  18734. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18736. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18737. });
  18738. }
  18739. #ifdef CPPHTTPLIB_SSL_ENABLED
  18740. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  18741. #ifndef _WIN32
  18742. signal(SIGPIPE, SIG_IGN);
  18743. #endif
  18744. auto reused = false;
  18745. std::promise<int> port_promise;
  18746. auto server_thread = serve_single_response(
  18747. port_promise,
  18748. "HTTP/1.1 401 Unauthorized\r\n"
  18749. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  18750. "Content-Length: 0\r\n\r\n",
  18751. [&](socket_t sock) {
  18752. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18753. char buf[256];
  18754. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  18755. });
  18756. Client cli("127.0.0.1", port_promise.get_future().get());
  18757. cli.set_keep_alive(true);
  18758. cli.set_digest_auth("user", "pass");
  18759. cli.set_read_timeout(1, 0);
  18760. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18761. server_thread.join();
  18762. EXPECT_FALSE(reused);
  18763. }
  18764. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  18765. // Any other answer to CONNECT would read as the origin's response.
  18766. struct {
  18767. const char *response;
  18768. bool passed_on;
  18769. } cases[] = {
  18770. {"HTTP/1.1 201 Created\r\n"
  18771. "Set-Cookie: session=from-proxy\r\n"
  18772. "Content-Length: 0\r\n\r\n",
  18773. false},
  18774. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  18775. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  18776. "Content-Length: 0\r\n\r\n",
  18777. true},
  18778. };
  18779. for (const auto &c : cases) {
  18780. std::promise<int> port_promise;
  18781. auto server_thread = serve_single_response(port_promise, c.response);
  18782. SSLClient cli("example.com", 443);
  18783. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  18784. auto res = cli.Get("/");
  18785. server_thread.join();
  18786. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  18787. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  18788. if (res) {
  18789. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18790. }
  18791. }
  18792. }
  18793. #endif
  18794. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18795. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18796. // the chunked coding and drop Content-Length, so a front-end that trusts
  18797. // Content-Length would disagree about where the body ends (response
  18798. // smuggling). The client must reject such a response.
  18799. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18800. for (const char *te : {"chunked", "gzip, chunked"}) {
  18801. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18802. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18803. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18804. "5\r\nhello\r\n0\r\n\r\n";
  18805. with_single_response(response, [&](Client &cli) {
  18806. auto res = cli.Get("/");
  18807. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18808. EXPECT_EQ(Error::Read, res.error()) << te;
  18809. });
  18810. with_single_response(response, [&](Client &cli) {
  18811. auto handle = cli.open_stream("GET", "/");
  18812. EXPECT_FALSE(handle.is_valid()) << te;
  18813. EXPECT_EQ(Error::Read, handle.error) << te;
  18814. });
  18815. }
  18816. }
  18817. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18818. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18819. // closing the connection (unlike a request, which must be rejected).
  18820. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18821. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18822. "Transfer-Encoding: chunked\r\n"
  18823. "Connection: close\r\n"
  18824. "\r\n"
  18825. "5\r\nhello\r\n0\r\n\r\n",
  18826. "HTTP/1.1 200 OK\r\n"
  18827. "Transfer-Encoding: gzip\r\n"
  18828. "Connection: close\r\n"
  18829. "\r\n"
  18830. "hello"}) {
  18831. with_single_response(response, [&](Client &cli) {
  18832. auto res = cli.Get("/");
  18833. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18834. EXPECT_EQ("hello", res->body);
  18835. });
  18836. with_single_response(response, [&](Client &cli) {
  18837. auto handle = cli.open_stream("GET", "/");
  18838. ASSERT_TRUE(handle.is_valid()) << response;
  18839. EXPECT_EQ("hello", read_all(handle));
  18840. });
  18841. }
  18842. }
  18843. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18844. // framing headers describe nothing to read and must not be rejected.
  18845. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18846. const std::string framing = "Content-Length: 5\r\n"
  18847. "Transfer-Encoding: chunked\r\n"
  18848. "Connection: close\r\n"
  18849. "\r\n";
  18850. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18851. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18852. });
  18853. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18854. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18855. });
  18856. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18857. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18858. with_single_response(response, [&](Client &cli) {
  18859. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18860. });
  18861. with_single_response(response, [&](Client &cli) {
  18862. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18863. });
  18864. }
  18865. }
  18866. // A payload max length of 0 means no limit, however the body is framed.
  18867. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18868. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18869. "Transfer-Encoding: chunked\r\n"
  18870. "\r\n"
  18871. "5\r\nhello\r\n0\r\n\r\n",
  18872. "HTTP/1.1 200 OK\r\n"
  18873. "Connection: close\r\n"
  18874. "\r\n"
  18875. "hello"}) {
  18876. with_single_response(response, [&](Client &cli) {
  18877. cli.set_payload_max_length(0);
  18878. auto res = cli.Get("/");
  18879. ASSERT_TRUE(res) << response;
  18880. EXPECT_EQ("hello", res->body) << response;
  18881. });
  18882. }
  18883. }
  18884. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18885. Server svr;
  18886. svr.set_payload_max_length(0);
  18887. svr.Post("/echo", [](const Request &req, Response &res) {
  18888. res.set_content(req.body, "text/plain");
  18889. });
  18890. auto port = svr.bind_to_any_port(HOST);
  18891. thread t = thread([&] { svr.listen_after_bind(); });
  18892. auto se = detail::scope_exit([&] {
  18893. svr.stop();
  18894. t.join();
  18895. ASSERT_FALSE(svr.is_running());
  18896. });
  18897. svr.wait_until_ready();
  18898. Client cli(HOST, port);
  18899. auto res = cli.Post(
  18900. "/echo",
  18901. [](size_t /*offset*/, DataSink &sink) {
  18902. sink.write("hello", 5);
  18903. sink.done();
  18904. return true;
  18905. },
  18906. "text/plain");
  18907. ASSERT_TRUE(res);
  18908. EXPECT_EQ(StatusCode::OK_200, res->status);
  18909. EXPECT_EQ("hello", res->body);
  18910. }
  18911. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18912. TEST_F(OpenStreamTest, Gzip) {
  18913. Client cli("127.0.0.1", port_);
  18914. auto handle = cli.open_stream("GET", "/compressible", {},
  18915. {{"Accept-Encoding", "gzip"}});
  18916. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18917. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18918. }
  18919. #endif
  18920. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18921. TEST_F(OpenStreamTest, Brotli) {
  18922. Client cli("127.0.0.1", port_);
  18923. auto handle =
  18924. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18925. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18926. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18927. }
  18928. #endif
  18929. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18930. TEST_F(OpenStreamTest, Zstd) {
  18931. Client cli("127.0.0.1", port_);
  18932. auto handle = cli.open_stream("GET", "/compressible", {},
  18933. {{"Accept-Encoding", "zstd"}});
  18934. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18935. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18936. }
  18937. #endif
  18938. #ifdef CPPHTTPLIB_SSL_ENABLED
  18939. class SSLOpenStreamTest : public ::testing::Test {
  18940. protected:
  18941. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18942. void SetUp() override {
  18943. svr_.Get("/hello", [](const Request &, Response &res) {
  18944. res.set_content("Hello SSL World!", "text/plain");
  18945. });
  18946. svr_.Get("/chunked", [](const Request &, Response &res) {
  18947. res.set_chunked_content_provider("text/plain",
  18948. [](size_t offset, DataSink &sink) {
  18949. if (offset < 15) {
  18950. sink.write("chunk", 5);
  18951. return true;
  18952. }
  18953. sink.done();
  18954. return true;
  18955. });
  18956. });
  18957. svr_.Post("/echo", [](const Request &req, Response &res) {
  18958. res.set_content(req.body, req.get_header_value("Content-Type"));
  18959. });
  18960. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18961. std::string body = req.body;
  18962. res.set_chunked_content_provider(
  18963. "text/plain", [body](size_t offset, DataSink &sink) {
  18964. if (offset < body.size()) {
  18965. sink.write(body.data() + offset, body.size() - offset);
  18966. }
  18967. sink.done();
  18968. return true;
  18969. });
  18970. });
  18971. port_ = svr_.bind_to_any_port("127.0.0.1");
  18972. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18973. svr_.wait_until_ready();
  18974. }
  18975. void TearDown() override {
  18976. svr_.stop();
  18977. if (thread_.joinable()) thread_.join();
  18978. }
  18979. SSLServer svr_;
  18980. std::thread thread_;
  18981. int port_ = 0;
  18982. };
  18983. TEST_F(SSLOpenStreamTest, Basic) {
  18984. SSLClient cli("127.0.0.1", port_);
  18985. cli.enable_server_certificate_verification(false);
  18986. auto handle = cli.open_stream("GET", "/hello");
  18987. ASSERT_TRUE(handle.is_valid());
  18988. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18989. }
  18990. TEST_F(SSLOpenStreamTest, Chunked) {
  18991. SSLClient cli("127.0.0.1", port_);
  18992. cli.enable_server_certificate_verification(false);
  18993. auto handle = cli.open_stream("GET", "/chunked");
  18994. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18995. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18996. "Transfer-Encoding") == "chunked");
  18997. auto body = read_all(handle);
  18998. EXPECT_EQ("chunkchunkchunk", body);
  18999. }
  19000. TEST_F(SSLOpenStreamTest, Post) {
  19001. SSLClient cli("127.0.0.1", port_);
  19002. cli.enable_server_certificate_verification(false);
  19003. auto handle =
  19004. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19005. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19006. EXPECT_EQ(200, handle.response->status);
  19007. auto body = read_all(handle);
  19008. EXPECT_EQ("Hello SSL POST", body);
  19009. }
  19010. TEST_F(SSLOpenStreamTest, PostChunked) {
  19011. SSLClient cli("127.0.0.1", port_);
  19012. cli.enable_server_certificate_verification(false);
  19013. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19014. "Chunked SSL Data", "text/plain");
  19015. ASSERT_TRUE(handle.is_valid());
  19016. EXPECT_EQ(200, handle.response->status);
  19017. auto body = read_all(handle);
  19018. EXPECT_EQ("Chunked SSL Data", body);
  19019. }
  19020. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19021. // Content-Length is terminated by the server closing the connection. When the
  19022. // SSL peer sends a close_notify after the body, the client must treat it as a
  19023. // clean EOF and return a successful response rather than an error.
  19024. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19026. ASSERT_TRUE(svr.is_valid());
  19027. svr.set_keep_alive_max_count(1);
  19028. const std::string expected_body = "Hello from connection-close response!";
  19029. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19030. res.set_content_provider("text/plain",
  19031. [&](size_t offset, DataSink &sink) -> bool {
  19032. if (offset < expected_body.size()) {
  19033. sink.write(expected_body.data() + offset,
  19034. expected_body.size() - offset);
  19035. }
  19036. sink.done();
  19037. return true;
  19038. });
  19039. });
  19040. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19041. auto se = detail::scope_exit([&] {
  19042. svr.stop();
  19043. listen_thread.join();
  19044. ASSERT_FALSE(svr.is_running());
  19045. });
  19046. svr.wait_until_ready();
  19047. SSLClient cli(HOST, PORT);
  19048. cli.enable_server_certificate_verification(false);
  19049. auto res = cli.Get("/no-content-length");
  19050. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19051. EXPECT_EQ(StatusCode::OK_200, res->status);
  19052. EXPECT_EQ(expected_body, res->body);
  19053. }
  19054. #endif // CPPHTTPLIB_SSL_ENABLED
  19055. //==============================================================================
  19056. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19057. // results for various scenarios.
  19058. //==============================================================================
  19059. TEST(ParityTest, GetVsOpenStream) {
  19060. Server svr;
  19061. const std::string path = "/parity";
  19062. const std::string content = "Parity test content: hello world";
  19063. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19064. res.set_content(content, "text/plain");
  19065. });
  19066. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19067. auto se = detail::scope_exit([&] {
  19068. svr.stop();
  19069. t.join();
  19070. ASSERT_FALSE(svr.is_running());
  19071. });
  19072. svr.wait_until_ready();
  19073. Client cli(HOST, PORT);
  19074. // Non-stream path
  19075. auto r1 = cli.Get(path);
  19076. ASSERT_TRUE(r1);
  19077. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19078. // Stream path
  19079. auto h = cli.open_stream("GET", path);
  19080. ASSERT_TRUE(h.is_valid());
  19081. EXPECT_EQ(r1->body, read_all(h));
  19082. }
  19083. // Helper to compress data with provided compressor type T
  19084. template <typename Compressor>
  19085. static std::string compress_payload_for_parity(const std::string &in) {
  19086. std::string out;
  19087. Compressor compressor;
  19088. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19089. [&](const char *data, size_t n) {
  19090. out.append(data, n);
  19091. return true;
  19092. });
  19093. EXPECT_TRUE(ok);
  19094. return out;
  19095. }
  19096. // Helper function for compression parity tests
  19097. template <typename Compressor>
  19098. static void test_compression_parity(const std::string &original,
  19099. const std::string &path,
  19100. const std::string &encoding) {
  19101. const std::string compressed =
  19102. compress_payload_for_parity<Compressor>(original);
  19103. Server svr;
  19104. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19105. res.set_content(compressed, "application/octet-stream");
  19106. res.set_header("Content-Encoding", encoding);
  19107. });
  19108. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19109. auto se = detail::scope_exit([&] {
  19110. svr.stop();
  19111. t.join();
  19112. ASSERT_FALSE(svr.is_running());
  19113. });
  19114. svr.wait_until_ready();
  19115. Client cli(HOST, PORT);
  19116. // Non-streaming
  19117. {
  19118. auto res = cli.Get(path);
  19119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19120. EXPECT_EQ(StatusCode::OK_200, res->status);
  19121. EXPECT_EQ(original, res->body);
  19122. }
  19123. // Streaming
  19124. {
  19125. auto h = cli.open_stream("GET", path);
  19126. ASSERT_TRUE(h.is_valid());
  19127. EXPECT_EQ(original, read_all(h));
  19128. }
  19129. }
  19130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19131. TEST(ParityTest, Gzip) {
  19132. test_compression_parity<detail::gzip_compressor>(
  19133. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19134. }
  19135. #endif
  19136. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19137. TEST(ParityTest, Brotli) {
  19138. test_compression_parity<detail::brotli_compressor>(
  19139. "Hello, brotli parity test payload", "/parity-br", "br");
  19140. }
  19141. #endif
  19142. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19143. TEST(ParityTest, Zstd) {
  19144. test_compression_parity<detail::zstd_compressor>(
  19145. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19146. }
  19147. #endif
  19148. //==============================================================================
  19149. // New Stream API Tests
  19150. //==============================================================================
  19151. inline std::string read_body(httplib::stream::Result &result) {
  19152. std::string body;
  19153. while (result.next()) {
  19154. body.append(result.data(), result.size());
  19155. }
  19156. return body;
  19157. }
  19158. TEST(ClientConnectionTest, Basic) {
  19159. httplib::ClientConnection conn;
  19160. EXPECT_FALSE(conn.is_open());
  19161. conn.sock = 1;
  19162. EXPECT_TRUE(conn.is_open());
  19163. httplib::ClientConnection conn2(std::move(conn));
  19164. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19165. conn2.sock = INVALID_SOCKET;
  19166. }
  19167. // Unified test server for all stream::* tests
  19168. class StreamApiTest : public ::testing::Test {
  19169. protected:
  19170. void SetUp() override {
  19171. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19172. res.set_content("Hello World!", "text/plain");
  19173. });
  19174. svr_.Get("/echo-params",
  19175. [](const httplib::Request &req, httplib::Response &res) {
  19176. std::string r;
  19177. for (const auto &p : req.params) {
  19178. if (!r.empty()) r += "&";
  19179. r += p.first + "=" + p.second;
  19180. }
  19181. res.set_content(r, "text/plain");
  19182. });
  19183. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19184. res.set_content(req.body, req.get_header_value("Content-Type"));
  19185. });
  19186. svr_.Post("/echo-headers",
  19187. [](const httplib::Request &req, httplib::Response &res) {
  19188. std::string r;
  19189. for (const auto &h : req.headers)
  19190. r += h.first + ": " + h.second + "\n";
  19191. res.set_content(r, "text/plain");
  19192. });
  19193. svr_.Post("/echo-params",
  19194. [](const httplib::Request &req, httplib::Response &res) {
  19195. std::string r = "params:";
  19196. for (const auto &p : req.params)
  19197. r += p.first + "=" + p.second + ";";
  19198. res.set_content(r + " body:" + req.body, "text/plain");
  19199. });
  19200. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19201. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19202. });
  19203. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19204. res.set_content("PUT:" + req.body, "text/plain");
  19205. });
  19206. svr_.Patch("/echo",
  19207. [](const httplib::Request &req, httplib::Response &res) {
  19208. res.set_content("PATCH:" + req.body, "text/plain");
  19209. });
  19210. svr_.Delete(
  19211. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19212. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19213. "text/plain");
  19214. });
  19215. svr_.Get("/head-test",
  19216. [](const httplib::Request &, httplib::Response &res) {
  19217. res.set_content("body for HEAD", "text/plain");
  19218. });
  19219. svr_.Options("/options",
  19220. [](const httplib::Request &, httplib::Response &res) {
  19221. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19222. });
  19223. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19224. svr_.wait_until_ready();
  19225. }
  19226. void TearDown() override {
  19227. svr_.stop();
  19228. if (thread_.joinable()) thread_.join();
  19229. }
  19230. httplib::Server svr_;
  19231. std::thread thread_;
  19232. };
  19233. // stream::Get tests
  19234. TEST_F(StreamApiTest, GetBasic) {
  19235. httplib::Client cli(HOST, PORT);
  19236. auto result = httplib::stream::Get(cli, "/hello");
  19237. ASSERT_TRUE(result.is_valid());
  19238. EXPECT_EQ(200, result.status());
  19239. EXPECT_EQ("Hello World!", read_body(result));
  19240. }
  19241. TEST_F(StreamApiTest, GetWithParams) {
  19242. httplib::Client cli(HOST, PORT);
  19243. httplib::Params params{{"foo", "bar"}};
  19244. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19245. ASSERT_TRUE(result.is_valid());
  19246. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19247. }
  19248. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19249. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19250. httplib::Client cli(HOST, PORT);
  19251. cli.set_payload_max_length(0);
  19252. auto result = httplib::stream::Get(cli, "/hello");
  19253. ASSERT_TRUE(result.is_valid());
  19254. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19255. EXPECT_EQ("Hello World!", read_body(result));
  19256. }
  19257. #endif
  19258. TEST_F(StreamApiTest, GetConnectionError) {
  19259. httplib::Client cli(HOST, 9999);
  19260. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19261. }
  19262. TEST_F(StreamApiTest, Get404) {
  19263. httplib::Client cli(HOST, PORT);
  19264. auto result = httplib::stream::Get(cli, "/nonexistent");
  19265. EXPECT_TRUE(result.is_valid());
  19266. EXPECT_EQ(404, result.status());
  19267. }
  19268. // stream::Post tests
  19269. TEST_F(StreamApiTest, PostBasic) {
  19270. httplib::Client cli(HOST, PORT);
  19271. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19272. "application/json");
  19273. ASSERT_TRUE(result.is_valid());
  19274. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19275. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19276. }
  19277. TEST_F(StreamApiTest, PostWithHeaders) {
  19278. httplib::Client cli(HOST, PORT);
  19279. httplib::Headers headers{{"X-Custom", "value"}};
  19280. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19281. "text/plain");
  19282. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19283. }
  19284. TEST_F(StreamApiTest, PostWithParams) {
  19285. httplib::Client cli(HOST, PORT);
  19286. httplib::Params params{{"k", "v"}};
  19287. auto result =
  19288. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19289. auto body = read_body(result);
  19290. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19291. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19292. }
  19293. TEST_F(StreamApiTest, PostLarge) {
  19294. httplib::Client cli(HOST, PORT);
  19295. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19296. size_t total = 0;
  19297. while (result.next()) {
  19298. total += result.size();
  19299. }
  19300. EXPECT_EQ(100u * 1024u, total);
  19301. }
  19302. // stream::Put/Patch tests
  19303. TEST_F(StreamApiTest, PutAndPatch) {
  19304. httplib::Client cli(HOST, PORT);
  19305. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19306. EXPECT_EQ("PUT:test", read_body(put));
  19307. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19308. EXPECT_EQ("PATCH:test", read_body(patch));
  19309. }
  19310. // stream::Delete tests
  19311. TEST_F(StreamApiTest, Delete) {
  19312. httplib::Client cli(HOST, PORT);
  19313. auto del1 = httplib::stream::Delete(cli, "/resource");
  19314. EXPECT_EQ("Deleted", read_body(del1));
  19315. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19316. EXPECT_EQ("Deleted:data", read_body(del2));
  19317. }
  19318. // stream::Head/Options tests
  19319. TEST_F(StreamApiTest, HeadAndOptions) {
  19320. httplib::Client cli(HOST, PORT);
  19321. auto head = httplib::stream::Head(cli, "/head-test");
  19322. EXPECT_TRUE(head.is_valid());
  19323. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19324. auto opts = httplib::stream::Options(cli, "/options");
  19325. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19326. }
  19327. // SSL stream::* tests
  19328. #ifdef CPPHTTPLIB_SSL_ENABLED
  19329. class SSLStreamApiTest : public ::testing::Test {
  19330. protected:
  19331. void SetUp() override {
  19332. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19333. res.set_content("Hello SSL!", "text/plain");
  19334. });
  19335. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19336. res.set_content(req.body, "text/plain");
  19337. });
  19338. port_ = svr_.bind_to_any_port("127.0.0.1");
  19339. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19340. svr_.wait_until_ready();
  19341. }
  19342. void TearDown() override {
  19343. svr_.stop();
  19344. if (thread_.joinable()) thread_.join();
  19345. }
  19346. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19347. std::thread thread_;
  19348. int port_ = 0;
  19349. };
  19350. TEST_F(SSLStreamApiTest, GetAndPost) {
  19351. httplib::SSLClient cli("127.0.0.1", port_);
  19352. cli.enable_server_certificate_verification(false);
  19353. auto get = httplib::stream::Get(cli, "/hello");
  19354. EXPECT_EQ("Hello SSL!", read_body(get));
  19355. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19356. EXPECT_EQ("test", read_body(post));
  19357. }
  19358. #endif
  19359. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19360. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19361. // BodyReader
  19362. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19363. // Test that read timeout during streaming is detected
  19364. // Use a large content-length response where server delays mid-stream
  19365. Server svr;
  19366. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19367. // Send a large response with delay in the middle
  19368. res.set_content_provider(
  19369. 1000, // content_length
  19370. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19371. if (offset < 100) {
  19372. // Send first 100 bytes immediately
  19373. std::string data(100, 'A');
  19374. sink.write(data.c_str(), data.size());
  19375. return true;
  19376. }
  19377. // Then delay longer than client timeout
  19378. std::this_thread::sleep_for(std::chrono::seconds(3));
  19379. std::string data(900, 'B');
  19380. sink.write(data.c_str(), data.size());
  19381. return true;
  19382. });
  19383. });
  19384. auto port = 8091;
  19385. std::thread t([&]() { svr.listen("localhost", port); });
  19386. svr.wait_until_ready();
  19387. Client cli("localhost", port);
  19388. cli.set_read_timeout(1, 0); // 1 second timeout
  19389. auto handle = cli.open_stream("GET", "/slow-stream");
  19390. ASSERT_TRUE(handle.is_valid());
  19391. char buf[256];
  19392. ssize_t total = 0;
  19393. ssize_t n;
  19394. bool got_error = false;
  19395. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19396. total += n;
  19397. }
  19398. if (n < 0) {
  19399. got_error = true;
  19400. // Should be timeout or read error
  19401. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19402. handle.get_read_error() == Error::Read)
  19403. << "Actual error: " << to_string(handle.get_read_error());
  19404. }
  19405. // Either we got an error, or we got less data than expected
  19406. EXPECT_TRUE(got_error || total < 1000)
  19407. << "Expected timeout but got all " << total << " bytes";
  19408. svr.stop();
  19409. t.join();
  19410. }
  19411. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19412. // Test connection closed detection via BodyReader
  19413. Server svr;
  19414. std::atomic<bool> close_now{false};
  19415. svr.Get("/will-close", [&](const Request &, Response &res) {
  19416. res.set_content_provider(
  19417. 10000, // Large content_length that we won't fully send
  19418. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19419. if (offset < 100) {
  19420. std::string data(100, 'X');
  19421. sink.write(data.c_str(), data.size());
  19422. return true;
  19423. }
  19424. // Wait for signal then abort
  19425. while (!close_now) {
  19426. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19427. }
  19428. return false; // Abort - server will close connection
  19429. });
  19430. });
  19431. auto port = 8092;
  19432. std::thread t([&]() { svr.listen("localhost", port); });
  19433. svr.wait_until_ready();
  19434. Client cli("localhost", port);
  19435. auto handle = cli.open_stream("GET", "/will-close");
  19436. ASSERT_TRUE(handle.is_valid());
  19437. char buf[256];
  19438. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19439. EXPECT_GT(n, 0) << "First read should succeed";
  19440. // Signal server to close
  19441. close_now = true;
  19442. // Keep reading until error or EOF
  19443. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19444. // Keep reading
  19445. }
  19446. // Should get an error since content_length wasn't satisfied
  19447. if (n < 0) {
  19448. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19449. handle.get_read_error() == Error::Read)
  19450. << "Actual error: " << to_string(handle.get_read_error());
  19451. }
  19452. svr.stop();
  19453. t.join();
  19454. }
  19455. #ifdef CPPHTTPLIB_SSL_ENABLED
  19456. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19457. // Test that read timeout during SSL streaming is detected
  19458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19459. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19460. res.set_content_provider(
  19461. 1000, "text/plain",
  19462. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19463. if (offset < 100) {
  19464. std::string data(100, 'A');
  19465. sink.write(data.c_str(), data.size());
  19466. return true;
  19467. }
  19468. std::this_thread::sleep_for(std::chrono::seconds(3));
  19469. std::string data(900, 'B');
  19470. sink.write(data.c_str(), data.size());
  19471. return true;
  19472. });
  19473. });
  19474. auto port = 8093;
  19475. std::thread t([&]() { svr.listen("localhost", port); });
  19476. svr.wait_until_ready();
  19477. SSLClient cli("localhost", port);
  19478. cli.enable_server_certificate_verification(false);
  19479. cli.set_read_timeout(1, 0); // 1 second timeout
  19480. auto handle = cli.open_stream("GET", "/slow-stream");
  19481. ASSERT_TRUE(handle.is_valid());
  19482. char buf[256];
  19483. ssize_t total = 0;
  19484. ssize_t n;
  19485. bool got_error = false;
  19486. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19487. total += n;
  19488. }
  19489. if (n < 0) {
  19490. got_error = true;
  19491. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19492. handle.get_read_error() == Error::Read)
  19493. << "Actual error: " << to_string(handle.get_read_error());
  19494. }
  19495. EXPECT_TRUE(got_error || total < 1000)
  19496. << "Expected timeout but got all " << total << " bytes";
  19497. svr.stop();
  19498. t.join();
  19499. }
  19500. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19501. // Test SSL connection closed detection
  19502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19503. std::atomic<bool> close_now{false};
  19504. svr.Get("/will-close", [&](const Request &, Response &res) {
  19505. res.set_content_provider(
  19506. 10000, "text/plain",
  19507. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19508. if (offset < 100) {
  19509. std::string data(100, 'X');
  19510. sink.write(data.c_str(), data.size());
  19511. return true;
  19512. }
  19513. while (!close_now) {
  19514. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19515. }
  19516. return false;
  19517. });
  19518. });
  19519. auto port = 8094;
  19520. std::thread t([&]() { svr.listen("localhost", port); });
  19521. svr.wait_until_ready();
  19522. SSLClient cli("localhost", port);
  19523. cli.enable_server_certificate_verification(false);
  19524. auto handle = cli.open_stream("GET", "/will-close");
  19525. ASSERT_TRUE(handle.is_valid());
  19526. char buf[256];
  19527. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19528. EXPECT_GT(n, 0);
  19529. // Signal server to close
  19530. close_now = true;
  19531. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19532. // Keep reading
  19533. }
  19534. if (n < 0) {
  19535. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19536. handle.get_read_error() == Error::Read)
  19537. << "Actual error: " << to_string(handle.get_read_error());
  19538. }
  19539. svr.stop();
  19540. t.join();
  19541. }
  19542. #endif
  19543. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19544. using namespace httplib;
  19545. // Create a test file
  19546. const char *fname = "etag_testfile.txt";
  19547. const char *content = "etag-content";
  19548. {
  19549. std::ofstream ofs(fname);
  19550. ofs << content;
  19551. ASSERT_TRUE(ofs.good());
  19552. }
  19553. Server svr;
  19554. svr.set_mount_point("/static", ".");
  19555. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19556. svr.wait_until_ready();
  19557. Client cli(HOST, PORT);
  19558. // First request: should get 200 with ETag header
  19559. auto res1 = cli.Get("/static/etag_testfile.txt");
  19560. ASSERT_TRUE(res1);
  19561. ASSERT_EQ(200, res1->status);
  19562. ASSERT_TRUE(res1->has_header("ETag"));
  19563. std::string etag = res1->get_header_value("ETag");
  19564. EXPECT_FALSE(etag.empty());
  19565. // Verify ETag format: W/"hex-hex"
  19566. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19567. EXPECT_EQ('W', etag[0]);
  19568. EXPECT_EQ('/', etag[1]);
  19569. EXPECT_EQ('"', etag[2]);
  19570. EXPECT_EQ('"', etag.back());
  19571. // Exact match: expect 304 Not Modified
  19572. Headers h2 = {{"If-None-Match", etag}};
  19573. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19574. ASSERT_TRUE(res2);
  19575. EXPECT_EQ(304, res2->status);
  19576. // Wildcard match: expect 304 Not Modified
  19577. Headers h3 = {{"If-None-Match", "*"}};
  19578. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19579. ASSERT_TRUE(res3);
  19580. EXPECT_EQ(304, res3->status);
  19581. // Non-matching ETag: expect 200
  19582. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19583. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19584. ASSERT_TRUE(res4);
  19585. EXPECT_EQ(200, res4->status);
  19586. // Multiple ETags with one matching: expect 304
  19587. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19588. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19589. ASSERT_TRUE(res5);
  19590. EXPECT_EQ(304, res5->status);
  19591. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19592. // that equivalent to the single comma-separated list above, so the match on
  19593. // the second line must still be found.
  19594. Headers h6;
  19595. h6.emplace("If-None-Match", "W/\"other\"");
  19596. h6.emplace("If-None-Match", etag);
  19597. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19598. ASSERT_TRUE(res6);
  19599. EXPECT_EQ(304, res6->status);
  19600. svr.stop();
  19601. t.join();
  19602. std::remove(fname);
  19603. }
  19604. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19605. using namespace httplib;
  19606. Server svr;
  19607. svr.set_mount_point("/static", ".");
  19608. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19609. svr.wait_until_ready();
  19610. Client cli(HOST, PORT);
  19611. // Send If-None-Match: * to a non-existent file
  19612. Headers h = {{"If-None-Match", "*"}};
  19613. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19615. EXPECT_EQ(404, res->status);
  19616. svr.stop();
  19617. t.join();
  19618. }
  19619. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19620. using namespace httplib;
  19621. // Create a test file
  19622. const char *fname = "etag_boundary_testfile.txt";
  19623. const char *content = "boundary-test";
  19624. {
  19625. std::ofstream ofs(fname);
  19626. ofs << content;
  19627. ASSERT_TRUE(ofs.good());
  19628. }
  19629. Server svr;
  19630. svr.set_mount_point("/static", ".");
  19631. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19632. svr.wait_until_ready();
  19633. Client cli(HOST, PORT);
  19634. // Get the actual ETag
  19635. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19636. ASSERT_TRUE(res1);
  19637. ASSERT_EQ(200, res1->status);
  19638. ASSERT_TRUE(res1->has_header("ETag"));
  19639. std::string etag = res1->get_header_value("ETag");
  19640. // Test 1: Very long ETag value (longer than actual ETag)
  19641. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19642. Headers h1 = {{"If-None-Match", "W/"
  19643. "\"very-long-etag-value-that-is-much-longer-"
  19644. "than-the-actual-etag-value\""}};
  19645. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19646. ASSERT_TRUE(res2);
  19647. EXPECT_EQ(200, res2->status); // Should not match
  19648. // Test 2: Long string followed by wildcard
  19649. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19650. // string)
  19651. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19652. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19653. ASSERT_TRUE(res3);
  19654. EXPECT_EQ(304, res3->status); // Should match on "*"
  19655. // Test 3: Wildcard followed by long string
  19656. // Should match on "*" immediately and return 304
  19657. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19658. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19659. ASSERT_TRUE(res4);
  19660. EXPECT_EQ(304, res4->status); // Should match on "*"
  19661. // Test 4: Multiple long non-matching values
  19662. // Should NOT match and return 200 (test that all comparisons are safe)
  19663. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19664. "W/\"second-long-non-matching-value\", "
  19665. "W/\"third-long-non-matching-value\""}};
  19666. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19667. ASSERT_TRUE(res5);
  19668. EXPECT_EQ(200, res5->status); // Should not match
  19669. // Test 5: Single character that is not "*" (edge case)
  19670. Headers h5 = {{"If-None-Match", "X"}};
  19671. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19672. ASSERT_TRUE(res6);
  19673. EXPECT_EQ(200, res6->status); // Should not match
  19674. svr.stop();
  19675. t.join();
  19676. std::remove(fname);
  19677. }
  19678. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19679. using namespace httplib;
  19680. // Create a test file
  19681. const char *fname = "ims_testfile.txt";
  19682. const char *content = "if-modified-since-test";
  19683. {
  19684. std::ofstream ofs(fname);
  19685. ofs << content;
  19686. ASSERT_TRUE(ofs.good());
  19687. }
  19688. Server svr;
  19689. svr.set_mount_point("/static", ".");
  19690. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19691. svr.wait_until_ready();
  19692. Client cli(HOST, PORT);
  19693. // First request: should get 200 with Last-Modified header
  19694. auto res1 = cli.Get("/static/ims_testfile.txt");
  19695. ASSERT_TRUE(res1);
  19696. ASSERT_EQ(200, res1->status);
  19697. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19698. std::string last_modified = res1->get_header_value("Last-Modified");
  19699. EXPECT_FALSE(last_modified.empty());
  19700. // If-Modified-Since with same time: expect 304
  19701. Headers h2 = {{"If-Modified-Since", last_modified}};
  19702. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19703. ASSERT_TRUE(res2);
  19704. EXPECT_EQ(304, res2->status);
  19705. // If-Modified-Since with future time: expect 304
  19706. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19707. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19708. ASSERT_TRUE(res3);
  19709. EXPECT_EQ(304, res3->status);
  19710. // If-Modified-Since with past time: expect 200
  19711. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19712. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19713. ASSERT_TRUE(res4);
  19714. EXPECT_EQ(200, res4->status);
  19715. // If-None-Match takes precedence over If-Modified-Since
  19716. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19717. ASSERT_TRUE(res1->has_header("ETag"));
  19718. std::string etag = res1->get_header_value("ETag");
  19719. Headers h5 = {{"If-None-Match", etag},
  19720. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19721. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19722. ASSERT_TRUE(res5);
  19723. EXPECT_EQ(304, res5->status);
  19724. svr.stop();
  19725. t.join();
  19726. std::remove(fname);
  19727. }
  19728. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19729. using namespace httplib;
  19730. Server svr;
  19731. // Endpoint that returns compressible content
  19732. svr.Get("/compressible", [](const Request &, Response &res) {
  19733. // Return a large enough body to trigger compression
  19734. std::string body(1000, 'a');
  19735. res.set_content(body, "text/plain");
  19736. });
  19737. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19738. svr.wait_until_ready();
  19739. Client cli(HOST, PORT);
  19740. // Request with gzip support: should get Vary header when compressed
  19741. cli.set_compress(true);
  19742. auto res1 = cli.Get("/compressible");
  19743. ASSERT_TRUE(res1);
  19744. EXPECT_EQ(200, res1->status);
  19745. // If Content-Encoding is set, Vary should also be set
  19746. if (res1->has_header("Content-Encoding")) {
  19747. EXPECT_TRUE(res1->has_header("Vary"));
  19748. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19749. }
  19750. // Request without Accept-Encoding header: should not have compression
  19751. Headers h_no_compress;
  19752. auto res2 = cli.Get("/compressible", h_no_compress);
  19753. ASSERT_TRUE(res2);
  19754. EXPECT_EQ(200, res2->status);
  19755. // Verify Vary header is present when compression is applied
  19756. // (the exact behavior depends on server configuration)
  19757. svr.stop();
  19758. t.join();
  19759. }
  19760. TEST(ETagTest, IfRangeWithETag) {
  19761. using namespace httplib;
  19762. // Create a test file with known content
  19763. const char *fname = "if_range_testfile.txt";
  19764. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19765. {
  19766. std::ofstream ofs(fname);
  19767. ofs << content;
  19768. ASSERT_TRUE(ofs.good());
  19769. }
  19770. Server svr;
  19771. svr.set_mount_point("/static", ".");
  19772. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19773. svr.wait_until_ready();
  19774. Client cli(HOST, PORT);
  19775. // First request: get ETag
  19776. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19777. ASSERT_TRUE(res1);
  19778. ASSERT_EQ(200, res1->status);
  19779. ASSERT_TRUE(res1->has_header("ETag"));
  19780. std::string etag = res1->get_header_value("ETag");
  19781. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19782. // Since our server generates weak ETags (W/"..."), If-Range with our
  19783. // ETag should NOT result in partial content - it should return full content.
  19784. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19785. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19786. ASSERT_TRUE(res2);
  19787. // Weak ETag in If-Range -> full content (200), not partial (206)
  19788. EXPECT_EQ(200, res2->status);
  19789. EXPECT_EQ(content, res2->body);
  19790. EXPECT_FALSE(res2->has_header("Content-Range"));
  19791. // Range request with non-matching If-Range (ETag): should get 200 (full
  19792. // content)
  19793. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19794. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19795. ASSERT_TRUE(res3);
  19796. EXPECT_EQ(200, res3->status);
  19797. EXPECT_EQ(content, res3->body);
  19798. EXPECT_FALSE(res3->has_header("Content-Range"));
  19799. // Range request with strong ETag (hypothetical - our server doesn't generate
  19800. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19801. // should return full content)
  19802. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19803. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19804. ASSERT_TRUE(res4);
  19805. EXPECT_EQ(200, res4->status);
  19806. EXPECT_EQ(content, res4->body);
  19807. EXPECT_FALSE(res4->has_header("Content-Range"));
  19808. svr.stop();
  19809. t.join();
  19810. std::remove(fname);
  19811. }
  19812. TEST(ETagTest, IfRangeWithDate) {
  19813. using namespace httplib;
  19814. // Create a test file
  19815. const char *fname = "if_range_date_testfile.txt";
  19816. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19817. {
  19818. std::ofstream ofs(fname);
  19819. ofs << content;
  19820. ASSERT_TRUE(ofs.good());
  19821. }
  19822. Server svr;
  19823. svr.set_mount_point("/static", ".");
  19824. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19825. svr.wait_until_ready();
  19826. Client cli(HOST, PORT);
  19827. // First request: get Last-Modified
  19828. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19829. ASSERT_TRUE(res1);
  19830. ASSERT_EQ(200, res1->status);
  19831. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19832. std::string last_modified = res1->get_header_value("Last-Modified");
  19833. // Range request with matching If-Range (date): should get 206
  19834. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19835. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19836. ASSERT_TRUE(res2);
  19837. EXPECT_EQ(206, res2->status);
  19838. EXPECT_EQ("FGHIJ", res2->body);
  19839. // Range request with old If-Range date: should get 200 (full content)
  19840. Headers h3 = {{"Range", "bytes=5-9"},
  19841. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19842. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19843. ASSERT_TRUE(res3);
  19844. EXPECT_EQ(200, res3->status);
  19845. EXPECT_EQ(content, res3->body);
  19846. // Range request with future If-Range date: should get 206
  19847. Headers h4 = {{"Range", "bytes=0-4"},
  19848. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19849. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19850. ASSERT_TRUE(res4);
  19851. EXPECT_EQ(206, res4->status);
  19852. EXPECT_EQ("ABCDE", res4->body);
  19853. svr.stop();
  19854. t.join();
  19855. std::remove(fname);
  19856. }
  19857. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19858. using namespace httplib;
  19859. const char *fname = "etag_malformed.txt";
  19860. const char *content = "malformed-etag";
  19861. {
  19862. std::ofstream ofs(fname);
  19863. ofs << content;
  19864. ASSERT_TRUE(ofs.good());
  19865. }
  19866. Server svr;
  19867. svr.set_mount_point("/static", ".");
  19868. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19869. svr.wait_until_ready();
  19870. Client cli(HOST, PORT);
  19871. // baseline: should get 200 and an ETag
  19872. auto res1 = cli.Get("/static/etag_malformed.txt");
  19873. ASSERT_TRUE(res1);
  19874. ASSERT_EQ(200, res1->status);
  19875. ASSERT_TRUE(res1->has_header("ETag"));
  19876. // Malformed ETag value (missing quotes) should be treated as non-matching
  19877. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19878. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19879. ASSERT_TRUE(res_bad);
  19880. EXPECT_EQ(200, res_bad->status);
  19881. // Whitespace-only header value should be considered invalid / non-matching
  19882. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19883. "Host: localhost\r\n"
  19884. "If-None-Match: \r\n"
  19885. "Connection: close\r\n"
  19886. "\r\n";
  19887. std::string out;
  19888. ASSERT_TRUE(send_request(5, raw_req, &out));
  19889. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19890. svr.stop();
  19891. t.join();
  19892. std::remove(fname);
  19893. }
  19894. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19895. using namespace httplib;
  19896. const char *fname = "ims_invalid_format.txt";
  19897. const char *content = "ims-bad-format";
  19898. {
  19899. std::ofstream ofs(fname);
  19900. ofs << content;
  19901. ASSERT_TRUE(ofs.good());
  19902. }
  19903. Server svr;
  19904. svr.set_mount_point("/static", ".");
  19905. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19906. svr.wait_until_ready();
  19907. Client cli(HOST, PORT);
  19908. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19909. ASSERT_TRUE(res1);
  19910. ASSERT_EQ(200, res1->status);
  19911. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19912. // If-Modified-Since with invalid format should not result in 304
  19913. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19914. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19915. ASSERT_TRUE(res_bad);
  19916. EXPECT_EQ(200, res_bad->status);
  19917. // If-Range with invalid date format should be treated as mismatch -> full
  19918. // content (200)
  19919. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19920. {"If-Range", "invalid-date"}};
  19921. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19922. ASSERT_TRUE(res_ifrange);
  19923. EXPECT_EQ(200, res_ifrange->status);
  19924. svr.stop();
  19925. t.join();
  19926. std::remove(fname);
  19927. }
  19928. TEST(ETagTest, IfRangeWithMalformedETag) {
  19929. using namespace httplib;
  19930. const char *fname = "ifrange_malformed.txt";
  19931. const std::string content = "0123456789";
  19932. {
  19933. std::ofstream ofs(fname);
  19934. ofs << content;
  19935. ASSERT_TRUE(ofs.good());
  19936. }
  19937. Server svr;
  19938. svr.set_mount_point("/static", ".");
  19939. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19940. svr.wait_until_ready();
  19941. Client cli(HOST, PORT);
  19942. // First request: get ETag
  19943. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19944. ASSERT_TRUE(res1);
  19945. ASSERT_EQ(200, res1->status);
  19946. ASSERT_TRUE(res1->has_header("ETag"));
  19947. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19948. // full content (200)
  19949. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19950. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19951. ASSERT_TRUE(res2);
  19952. EXPECT_EQ(200, res2->status);
  19953. EXPECT_EQ(content, res2->body);
  19954. svr.stop();
  19955. t.join();
  19956. std::remove(fname);
  19957. }
  19958. TEST(ETagTest, ExtremeLargeDateValues) {
  19959. using namespace httplib;
  19960. const char *fname = "ims_extreme_date.txt";
  19961. const char *content = "ims-extreme-date";
  19962. {
  19963. std::ofstream ofs(fname);
  19964. ofs << content;
  19965. ASSERT_TRUE(ofs.good());
  19966. }
  19967. Server svr;
  19968. svr.set_mount_point("/static", ".");
  19969. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19970. svr.wait_until_ready();
  19971. Client cli(HOST, PORT);
  19972. auto res1 = cli.Get(std::string("/static/") + fname);
  19973. ASSERT_TRUE(res1);
  19974. ASSERT_EQ(200, res1->status);
  19975. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19976. // Extremely large year that may overflow date parsing routines.
  19977. Headers h_large_date = {
  19978. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19979. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19980. ASSERT_TRUE(res_bad);
  19981. // Expect server to treat this as invalid/mismatch and return full content
  19982. EXPECT_EQ(200, res_bad->status);
  19983. // If-Range with extremely large date should be treated as mismatch -> full
  19984. // content (200)
  19985. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19986. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19987. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19988. ASSERT_TRUE(res_ifrange);
  19989. EXPECT_EQ(200, res_ifrange->status);
  19990. svr.stop();
  19991. t.join();
  19992. std::remove(fname);
  19993. }
  19994. TEST(ETagTest, NegativeFileModificationTime) {
  19995. using namespace httplib;
  19996. const char *fname = "ims_negative_mtime.txt";
  19997. const std::string content = "negative-mtime";
  19998. {
  19999. std::ofstream ofs(fname);
  20000. ofs << content;
  20001. ASSERT_TRUE(ofs.good());
  20002. }
  20003. // Try to set file mtime to a negative value. This may fail on some
  20004. // platforms/filesystems; if it fails, the test will still verify server
  20005. // behaves safely by performing a regular conditional request.
  20006. #if defined(__APPLE__) || defined(__linux__)
  20007. bool set_negative = false;
  20008. do {
  20009. struct timeval times[2];
  20010. // access time: now
  20011. times[0].tv_sec = time(nullptr);
  20012. times[0].tv_usec = 0;
  20013. // modification time: negative (e.g., -1)
  20014. times[1].tv_sec = -1;
  20015. times[1].tv_usec = 0;
  20016. if (utimes(fname, times) == 0) { set_negative = true; }
  20017. } while (0);
  20018. #else
  20019. bool set_negative = false;
  20020. #endif
  20021. Server svr;
  20022. svr.set_mount_point("/static", ".");
  20023. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20024. svr.wait_until_ready();
  20025. Client cli(HOST, PORT);
  20026. auto res1 = cli.Get(std::string("/static/") + fname);
  20027. ASSERT_TRUE(res1);
  20028. ASSERT_EQ(200, res1->status);
  20029. bool has_last_modified = res1->has_header("Last-Modified");
  20030. std::string last_modified;
  20031. if (has_last_modified) {
  20032. last_modified = res1->get_header_value("Last-Modified");
  20033. }
  20034. if (set_negative) {
  20035. // If we successfully set a negative mtime, ensure server returns a
  20036. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20037. // with an old date and ensure server handles it without crash.
  20038. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20039. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20040. ASSERT_TRUE(res2);
  20041. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20042. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20043. } else {
  20044. // Could not set negative mtime on this platform; fall back to verifying
  20045. // that normal invalid/malformed dates are treated safely (non-304).
  20046. Headers h_bad_date = {
  20047. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20048. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20049. ASSERT_TRUE(res_bad);
  20050. EXPECT_EQ(200, res_bad->status);
  20051. }
  20052. svr.stop();
  20053. t.join();
  20054. std::remove(fname);
  20055. }
  20056. //==============================================================================
  20057. // Integration Tests with Server
  20058. //==============================================================================
  20059. class SSEIntegrationTest : public ::testing::Test {
  20060. protected:
  20061. void SetUp() override {
  20062. stop_server_.store(false);
  20063. events_.clear();
  20064. server_ = httplib::detail::make_unique<Server>();
  20065. setup_server();
  20066. start_server();
  20067. }
  20068. void TearDown() override {
  20069. stop_server_.store(true);
  20070. event_cv_.notify_all();
  20071. server_->stop();
  20072. if (server_thread_.joinable()) { server_thread_.join(); }
  20073. }
  20074. void setup_server() {
  20075. // Simple SSE endpoint
  20076. server_->Get("/events", [this](const Request &req, Response &res) {
  20077. auto last_id = req.get_header_value("Last-Event-ID");
  20078. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20079. res.set_chunked_content_provider(
  20080. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20081. std::unique_lock<std::mutex> lock(event_mutex_);
  20082. if (event_cv_.wait_for(
  20083. lock, std::chrono::milliseconds(200), [this] {
  20084. return !events_.empty() || stop_server_.load();
  20085. })) {
  20086. if (stop_server_.load()) { return false; }
  20087. if (!events_.empty()) {
  20088. std::string event = events_.front();
  20089. events_.erase(events_.begin());
  20090. sink.write(event.data(), event.size());
  20091. return true;
  20092. }
  20093. }
  20094. return !stop_server_.load();
  20095. });
  20096. });
  20097. // Endpoint that returns error
  20098. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20099. res.status = 500;
  20100. res.set_content("Internal Server Error", "text/plain");
  20101. });
  20102. // Endpoint for custom event types
  20103. server_->Get("/custom-events", [](const Request &, Response &res) {
  20104. res.set_chunked_content_provider(
  20105. "text/event-stream", [](size_t offset, DataSink &sink) {
  20106. if (offset == 0) {
  20107. std::string event = "event: update\ndata: updated\n\n"
  20108. "event: delete\ndata: deleted\n\n";
  20109. sink.write(event.data(), event.size());
  20110. }
  20111. return false; // End stream after sending
  20112. });
  20113. });
  20114. }
  20115. void start_server() {
  20116. port_ = server_->bind_to_any_port(HOST);
  20117. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20118. // Wait for server to start
  20119. while (!server_->is_running()) {
  20120. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20121. }
  20122. }
  20123. int get_port() const { return port_; }
  20124. void send_event(const std::string &event) {
  20125. std::lock_guard<std::mutex> lock(event_mutex_);
  20126. events_.push_back(event);
  20127. event_cv_.notify_all();
  20128. }
  20129. std::unique_ptr<Server> server_;
  20130. std::thread server_thread_;
  20131. std::mutex event_mutex_;
  20132. std::condition_variable event_cv_;
  20133. std::vector<std::string> events_;
  20134. std::atomic<bool> stop_server_{false};
  20135. std::string last_received_event_id_;
  20136. int port_ = 0;
  20137. };
  20138. //==============================================================================
  20139. // SSE Parsing Tests
  20140. //==============================================================================
  20141. class SSEParsingTest : public SSEIntegrationTest {
  20142. protected:
  20143. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20144. // A trailing sentinel event tells when the whole stream has been parsed.
  20145. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20146. auto body = stream + "event: end\ndata: end\n\n";
  20147. server_->Get("/parse", [body](const Request &, Response &res) {
  20148. res.set_content(body, "text/event-stream");
  20149. });
  20150. return collect("/parse");
  20151. }
  20152. // Runs SSEClient against path until an "end" event arrives and returns the
  20153. // messages dispatched before it
  20154. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20155. Client client(HOST, get_port());
  20156. sse::SSEClient sse(client, path);
  20157. std::mutex mutex;
  20158. std::condition_variable cv;
  20159. std::vector<sse::SSEMessage> messages;
  20160. auto done = false;
  20161. sse.on_message([&](const sse::SSEMessage &msg) {
  20162. std::lock_guard<std::mutex> lock(mutex);
  20163. // Ignore a replay from a reconnect that races with stop()
  20164. if (!done) { messages.push_back(msg); }
  20165. });
  20166. sse.on_event("end", [&](const sse::SSEMessage &) {
  20167. std::lock_guard<std::mutex> lock(mutex);
  20168. done = true;
  20169. cv.notify_all();
  20170. });
  20171. sse.set_reconnect_interval(100);
  20172. sse.start_async();
  20173. {
  20174. std::unique_lock<std::mutex> lock(mutex);
  20175. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20176. }
  20177. sse.stop();
  20178. EXPECT_TRUE(done);
  20179. return messages;
  20180. }
  20181. };
  20182. TEST_F(SSEParsingTest, SingleLineData) {
  20183. auto msgs = parse("data: hello\n\n");
  20184. ASSERT_EQ(msgs.size(), 1u);
  20185. EXPECT_EQ(msgs[0].data, "hello");
  20186. EXPECT_EQ(msgs[0].event, "message");
  20187. }
  20188. TEST_F(SSEParsingTest, MultiLineData) {
  20189. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20190. ASSERT_EQ(msgs.size(), 1u);
  20191. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20192. }
  20193. TEST_F(SSEParsingTest, CustomEventType) {
  20194. auto msgs = parse("event: update\ndata: payload\n\n");
  20195. ASSERT_EQ(msgs.size(), 1u);
  20196. EXPECT_EQ(msgs[0].event, "update");
  20197. EXPECT_EQ(msgs[0].data, "payload");
  20198. }
  20199. TEST_F(SSEParsingTest, EventIdHandling) {
  20200. auto msgs = parse("id: 12345\ndata: test\n\n");
  20201. ASSERT_EQ(msgs.size(), 1u);
  20202. EXPECT_EQ(msgs[0].id, "12345");
  20203. }
  20204. TEST_F(SSEParsingTest, EmptyEventId) {
  20205. auto msgs = parse("id:\ndata: test\n\n");
  20206. ASSERT_EQ(msgs.size(), 1u);
  20207. EXPECT_EQ(msgs[0].id, "");
  20208. }
  20209. TEST_F(SSEParsingTest, CommentsIgnored) {
  20210. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20211. ASSERT_EQ(msgs.size(), 1u);
  20212. EXPECT_EQ(msgs[0].data, "hello");
  20213. EXPECT_EQ(msgs[0].event, "message");
  20214. }
  20215. TEST_F(SSEParsingTest, ColonInValue) {
  20216. auto msgs = parse("data: hello:world:test\n\n");
  20217. ASSERT_EQ(msgs.size(), 1u);
  20218. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20219. }
  20220. TEST_F(SSEParsingTest, FieldNameOnly) {
  20221. // A line without a colon is a field name with an empty value
  20222. auto msgs = parse("data\n\n");
  20223. ASSERT_EQ(msgs.size(), 1u);
  20224. EXPECT_EQ(msgs[0].data, "");
  20225. }
  20226. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20227. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20228. ASSERT_EQ(msgs.size(), 1u);
  20229. EXPECT_EQ(msgs[0].event, "update");
  20230. EXPECT_EQ(msgs[0].data, "hello");
  20231. }
  20232. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20233. auto msgs = parse("data\r\n\r\n");
  20234. ASSERT_EQ(msgs.size(), 1u);
  20235. EXPECT_EQ(msgs[0].data, "");
  20236. }
  20237. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20238. auto msgs = parse("event: update\rdata: hello\r\r");
  20239. ASSERT_EQ(msgs.size(), 1u);
  20240. EXPECT_EQ(msgs[0].event, "update");
  20241. EXPECT_EQ(msgs[0].data, "hello");
  20242. }
  20243. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20244. // Chunk boundaries fall inside every \r\n and right before the first one
  20245. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20246. "\n\r", "\nevent: end\ndata: end\n\n"};
  20247. server_->Get("/split", [chunks](const Request &, Response &res) {
  20248. auto i = std::make_shared<size_t>(0);
  20249. res.set_chunked_content_provider(
  20250. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20251. if (*i == chunks.size()) {
  20252. sink.done();
  20253. } else {
  20254. sink.write(chunks[*i].data(), chunks[*i].size());
  20255. (*i)++;
  20256. }
  20257. return true;
  20258. });
  20259. });
  20260. auto msgs = collect("/split");
  20261. ASSERT_EQ(msgs.size(), 1u);
  20262. EXPECT_EQ(msgs[0].event, "update");
  20263. EXPECT_EQ(msgs[0].data, "hello");
  20264. }
  20265. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20266. // Only a BOM at the start of the stream is ignored
  20267. auto msgs = parse("\xEF\xBB\xBF"
  20268. "data: first\n\n"
  20269. "\xEF\xBB\xBF"
  20270. "data: second\n\n");
  20271. ASSERT_EQ(msgs.size(), 1u);
  20272. EXPECT_EQ(msgs[0].data, "first");
  20273. }
  20274. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20275. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20276. ASSERT_EQ(msgs.size(), 1u);
  20277. EXPECT_EQ(msgs[0].data, "hello");
  20278. EXPECT_EQ(msgs[0].event, "message");
  20279. }
  20280. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20281. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20282. ASSERT_EQ(msgs.size(), 2u);
  20283. EXPECT_EQ(msgs[0].data, "hello");
  20284. EXPECT_EQ(msgs[1].data, "hello");
  20285. }
  20286. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20287. // An event without data is not dispatched, and its type must not leak
  20288. // into the next event
  20289. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20290. ASSERT_EQ(msgs.size(), 1u);
  20291. EXPECT_EQ(msgs[0].event, "message");
  20292. EXPECT_EQ(msgs[0].data, "hello");
  20293. }
  20294. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20295. // The first connection sends only an id; the second echoes back the
  20296. // Last-Event-ID it was reconnected with
  20297. std::atomic<int> connection_count{0};
  20298. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20299. if (connection_count++ == 0) {
  20300. res.set_content("id: 42\n\n", "text/event-stream");
  20301. } else {
  20302. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20303. "\n\nevent: end\ndata: end\n\n",
  20304. "text/event-stream");
  20305. }
  20306. });
  20307. auto msgs = collect("/id-only");
  20308. ASSERT_EQ(msgs.size(), 1u);
  20309. EXPECT_EQ(msgs[0].data, "42");
  20310. }
  20311. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20312. // The first connection sets an id and then clears it with an empty one; the
  20313. // second reports whether it was reconnected with a Last-Event-ID
  20314. std::atomic<int> connection_count{0};
  20315. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20316. if (connection_count++ == 0) {
  20317. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20318. "text/event-stream");
  20319. } else {
  20320. res.set_content(
  20321. std::string("data: ") +
  20322. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20323. "\n\nevent: end\ndata: end\n\n",
  20324. "text/event-stream");
  20325. }
  20326. });
  20327. auto msgs = collect("/id-clear");
  20328. ASSERT_EQ(msgs.size(), 3u);
  20329. EXPECT_EQ(msgs[0].id, "1");
  20330. EXPECT_EQ(msgs[1].id, "");
  20331. EXPECT_EQ(msgs[2].data, "not sent");
  20332. }
  20333. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20334. // The first connection sets an id and then sends ids that cannot be carried
  20335. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20336. // with
  20337. std::atomic<int> connection_count{0};
  20338. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20339. if (connection_count++ == 0) {
  20340. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20341. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20342. "text/event-stream");
  20343. } else {
  20344. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20345. "\n\nevent: end\ndata: end\n\n",
  20346. "text/event-stream");
  20347. }
  20348. });
  20349. auto msgs = collect("/id-unsendable");
  20350. ASSERT_EQ(msgs.size(), 1u);
  20351. EXPECT_EQ(msgs[0].data, "42");
  20352. }
  20353. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20354. auto msgs = parse("event: notification\nid: evt-42\n"
  20355. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20356. ASSERT_EQ(msgs.size(), 1u);
  20357. EXPECT_EQ(msgs[0].event, "notification");
  20358. EXPECT_EQ(msgs[0].id, "evt-42");
  20359. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20360. }
  20361. TEST(SSEMessageTest, Clear) {
  20362. sse::SSEMessage msg;
  20363. msg.event = "custom";
  20364. msg.data = "some data";
  20365. msg.id = "123";
  20366. msg.clear();
  20367. EXPECT_EQ(msg.event, "message");
  20368. EXPECT_EQ(msg.data, "");
  20369. EXPECT_EQ(msg.id, "");
  20370. }
  20371. //==============================================================================
  20372. // SSE Integration Tests
  20373. //==============================================================================
  20374. // Test: Successful connection and on_open callback
  20375. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20376. // Add a simple endpoint that sends one event and closes
  20377. server_->Get("/simple-event", [](const Request &, Response &res) {
  20378. res.set_chunked_content_provider(
  20379. "text/event-stream", [](size_t offset, DataSink &sink) {
  20380. if (offset == 0) {
  20381. std::string event = "data: hello\n\n";
  20382. sink.write(event.data(), event.size());
  20383. }
  20384. return false; // Close stream after sending
  20385. });
  20386. });
  20387. Client client("localhost", get_port());
  20388. sse::SSEClient sse(client, "/simple-event");
  20389. std::atomic<bool> open_called{false};
  20390. std::atomic<bool> message_received{false};
  20391. sse.on_open([&open_called]() { open_called.store(true); });
  20392. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20393. if (msg.data == "hello") { message_received.store(true); }
  20394. });
  20395. sse.set_reconnect_interval(100);
  20396. sse.set_max_reconnect_attempts(1);
  20397. // Start async
  20398. sse.start_async();
  20399. // Wait for message to be processed
  20400. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20401. sse.stop();
  20402. EXPECT_TRUE(open_called.load());
  20403. EXPECT_TRUE(message_received.load());
  20404. }
  20405. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20406. // A data line that never ends.
  20407. server_->Get("/endless-line", [](const Request &, Response &res) {
  20408. res.set_chunked_content_provider(
  20409. "text/event-stream", [](size_t offset, DataSink &sink) {
  20410. if (offset == 0) { sink.write("data: ", 6); }
  20411. std::string chunk(64 * 1024, 'A');
  20412. return sink.write(chunk.data(), chunk.size());
  20413. });
  20414. });
  20415. Client client("localhost", get_port());
  20416. // Lift the payload limit, so that only the event limit can end this endless
  20417. // stream.
  20418. client.set_payload_max_length(0);
  20419. sse::SSEClient sse(client, "/endless-line");
  20420. std::atomic<bool> too_long{false};
  20421. sse.on_error([&](Error err) {
  20422. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20423. });
  20424. sse.set_max_reconnect_attempts(1);
  20425. sse.start_async();
  20426. for (int i = 0; i < 500 && !too_long; i++) {
  20427. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20428. }
  20429. sse.stop();
  20430. EXPECT_TRUE(too_long);
  20431. }
  20432. // Test: on_message callback
  20433. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20434. // Endpoint that sends multiple events then closes
  20435. server_->Get("/multi-event", [](const Request &, Response &res) {
  20436. res.set_chunked_content_provider(
  20437. "text/event-stream", [](size_t offset, DataSink &sink) {
  20438. if (offset == 0) {
  20439. std::string events = "data: message1\n\ndata: message2\n\n";
  20440. sink.write(events.data(), events.size());
  20441. }
  20442. return false;
  20443. });
  20444. });
  20445. Client client("localhost", get_port());
  20446. sse::SSEClient sse(client, "/multi-event");
  20447. std::vector<std::string> received_messages;
  20448. std::mutex messages_mutex;
  20449. sse.on_message([&](const sse::SSEMessage &msg) {
  20450. std::lock_guard<std::mutex> lock(messages_mutex);
  20451. received_messages.push_back(msg.data);
  20452. });
  20453. sse.set_reconnect_interval(100);
  20454. sse.set_max_reconnect_attempts(1);
  20455. sse.start_async();
  20456. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20457. sse.stop();
  20458. std::lock_guard<std::mutex> lock(messages_mutex);
  20459. EXPECT_GE(received_messages.size(), 2u);
  20460. if (received_messages.size() >= 2) {
  20461. EXPECT_EQ(received_messages[0], "message1");
  20462. EXPECT_EQ(received_messages[1], "message2");
  20463. }
  20464. }
  20465. // Test: on_event for specific types
  20466. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20467. Client client("localhost", get_port());
  20468. sse::SSEClient sse(client, "/custom-events");
  20469. std::atomic<bool> update_received{false};
  20470. std::atomic<bool> delete_received{false};
  20471. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20472. if (msg.data == "updated") { update_received.store(true); }
  20473. });
  20474. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20475. if (msg.data == "deleted") { delete_received.store(true); }
  20476. });
  20477. sse.set_max_reconnect_attempts(1);
  20478. sse.start_async();
  20479. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20480. sse.stop();
  20481. EXPECT_TRUE(update_received.load());
  20482. EXPECT_TRUE(delete_received.load());
  20483. }
  20484. // Test: on_error callback on connection failure
  20485. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20486. // Connect to a non-existent port
  20487. Client client("localhost", 59999);
  20488. sse::SSEClient sse(client, "/events");
  20489. std::atomic<bool> error_called{false};
  20490. Error received_error = Error::Success;
  20491. sse.on_error([&](Error err) {
  20492. error_called.store(true);
  20493. received_error = err;
  20494. });
  20495. sse.set_reconnect_interval(50);
  20496. sse.set_max_reconnect_attempts(1);
  20497. sse.start_async();
  20498. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20499. sse.stop();
  20500. EXPECT_TRUE(error_called.load());
  20501. EXPECT_NE(received_error, Error::Success);
  20502. }
  20503. // Test: Last-Event-ID header sent on reconnect
  20504. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20505. // Endpoint that sends event with ID
  20506. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20507. res.set_chunked_content_provider(
  20508. "text/event-stream", [](size_t offset, DataSink &sink) {
  20509. if (offset == 0) {
  20510. std::string event = "id: evt-123\ndata: test\n\n";
  20511. sink.write(event.data(), event.size());
  20512. }
  20513. return false;
  20514. });
  20515. });
  20516. Client client("localhost", get_port());
  20517. sse::SSEClient sse(client, "/event-with-id");
  20518. std::atomic<bool> id_received{false};
  20519. sse.on_message([&](const sse::SSEMessage &msg) {
  20520. if (!msg.id.empty()) { id_received.store(true); }
  20521. });
  20522. sse.set_reconnect_interval(100);
  20523. sse.set_max_reconnect_attempts(1);
  20524. sse.start_async();
  20525. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20526. sse.stop();
  20527. EXPECT_TRUE(id_received.load());
  20528. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20529. }
  20530. // Test: Manual stop
  20531. TEST_F(SSEIntegrationTest, ManualStop) {
  20532. // Endpoint that sends one event and stays open briefly
  20533. std::atomic<bool> handler_running{true};
  20534. server_->Get("/stay-open", [&handler_running](const Request &,
  20535. Response &res) {
  20536. res.set_chunked_content_provider(
  20537. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20538. if (offset == 0) {
  20539. std::string event = "data: connected\n\n";
  20540. sink.write(event.data(), event.size());
  20541. }
  20542. // Keep connection open while handler_running is true
  20543. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20544. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20545. }
  20546. return false;
  20547. });
  20548. });
  20549. Client client("localhost", get_port());
  20550. sse::SSEClient sse(client, "/stay-open");
  20551. std::atomic<bool> connected{false};
  20552. sse.on_open([&connected]() { connected.store(true); });
  20553. sse.set_reconnect_interval(100);
  20554. sse.set_max_reconnect_attempts(1);
  20555. sse.start_async();
  20556. // Wait for connection to establish
  20557. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20558. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20559. }
  20560. EXPECT_TRUE(connected.load());
  20561. EXPECT_TRUE(sse.is_connected());
  20562. // Signal handler to stop
  20563. handler_running.store(false);
  20564. // Stop SSE client
  20565. sse.stop();
  20566. EXPECT_FALSE(sse.is_connected());
  20567. }
  20568. // Test: SSEClient with custom headers
  20569. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20570. // Setup a server endpoint that checks for custom header
  20571. std::atomic<bool> header_received{false};
  20572. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20573. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20574. header_received.store(true);
  20575. }
  20576. res.set_chunked_content_provider("text/event-stream",
  20577. [](size_t, DataSink &) { return false; });
  20578. });
  20579. Client client("localhost", get_port());
  20580. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20581. sse::SSEClient sse(client, "/header-check", headers);
  20582. sse.set_max_reconnect_attempts(1);
  20583. sse.start_async();
  20584. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20585. sse.stop();
  20586. EXPECT_TRUE(header_received.load());
  20587. }
  20588. // Test: Reconnect interval configuration
  20589. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20590. Client client("localhost", get_port());
  20591. sse::SSEClient sse(client, "/events");
  20592. auto &result = sse.set_reconnect_interval(500);
  20593. // Builder pattern should return reference to self
  20594. EXPECT_EQ(&result, &sse);
  20595. }
  20596. // Test: Max reconnect attempts
  20597. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20598. // Connect to non-existent port to force reconnects
  20599. Client client("localhost", 59998);
  20600. sse::SSEClient sse(client, "/events");
  20601. std::atomic<int> error_count{0};
  20602. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20603. sse.set_reconnect_interval(50);
  20604. sse.set_max_reconnect_attempts(2);
  20605. auto start = std::chrono::steady_clock::now();
  20606. sse.start(); // Blocking call
  20607. auto end = std::chrono::steady_clock::now();
  20608. // Should have stopped after 2 failed attempts
  20609. EXPECT_GE(error_count.load(), 2);
  20610. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20611. auto duration =
  20612. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20613. #ifdef _WIN32
  20614. // Windows is much slower for socket connection failures
  20615. EXPECT_LT(duration.count(), 7000);
  20616. #else
  20617. EXPECT_LT(duration.count(), 1000);
  20618. #endif
  20619. }
  20620. // Test: Multi-line data in integration
  20621. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20622. // Endpoint with multi-line data
  20623. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20624. res.set_chunked_content_provider(
  20625. "text/event-stream", [](size_t offset, DataSink &sink) {
  20626. if (offset == 0) {
  20627. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20628. sink.write(event.data(), event.size());
  20629. }
  20630. return false;
  20631. });
  20632. });
  20633. Client client("localhost", get_port());
  20634. sse::SSEClient sse(client, "/multiline-data");
  20635. std::string received_data;
  20636. std::mutex data_mutex;
  20637. sse.on_message([&](const sse::SSEMessage &msg) {
  20638. std::lock_guard<std::mutex> lock(data_mutex);
  20639. received_data = msg.data;
  20640. });
  20641. sse.set_reconnect_interval(100);
  20642. sse.set_max_reconnect_attempts(1);
  20643. sse.start_async();
  20644. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20645. sse.stop();
  20646. std::lock_guard<std::mutex> lock(data_mutex);
  20647. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20648. }
  20649. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20650. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20651. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20652. DataSink &sink) {
  20653. if (offset == 0) {
  20654. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20655. sink.write(events.data(), events.size());
  20656. }
  20657. return false;
  20658. });
  20659. });
  20660. Client client("localhost", get_port());
  20661. sse::SSEClient sse(client, "/empty-data-lines");
  20662. std::mutex mutex;
  20663. std::condition_variable cv;
  20664. std::vector<std::string> received;
  20665. sse.on_message([&](const sse::SSEMessage &msg) {
  20666. std::lock_guard<std::mutex> lock(mutex);
  20667. received.push_back(msg.data);
  20668. cv.notify_all();
  20669. });
  20670. sse.set_max_reconnect_attempts(1);
  20671. sse.start_async();
  20672. {
  20673. std::unique_lock<std::mutex> lock(mutex);
  20674. cv.wait_for(lock, std::chrono::seconds(2),
  20675. [&] { return received.size() >= 3; });
  20676. }
  20677. sse.stop();
  20678. ASSERT_GE(received.size(), 3u);
  20679. EXPECT_EQ(received[0], "");
  20680. EXPECT_EQ(received[1], "\nhello");
  20681. EXPECT_EQ(received[2], "");
  20682. }
  20683. // Test: Auto-reconnect after server disconnection
  20684. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20685. std::atomic<int> connection_count{0};
  20686. std::atomic<int> message_count{0};
  20687. // Endpoint that sends one event and closes, forcing reconnect
  20688. server_->Get("/reconnect-test",
  20689. [&connection_count](const Request &, Response &res) {
  20690. connection_count.fetch_add(1);
  20691. res.set_chunked_content_provider(
  20692. "text/event-stream", [](size_t offset, DataSink &sink) {
  20693. if (offset == 0) {
  20694. std::string event = "data: hello\n\n";
  20695. sink.write(event.data(), event.size());
  20696. }
  20697. return false; // Close connection after sending
  20698. });
  20699. });
  20700. Client client("localhost", get_port());
  20701. sse::SSEClient sse(client, "/reconnect-test");
  20702. sse.on_message([&message_count](const sse::SSEMessage &) {
  20703. message_count.fetch_add(1);
  20704. });
  20705. sse.set_reconnect_interval(100);
  20706. sse.set_max_reconnect_attempts(3);
  20707. sse.start_async();
  20708. // Wait long enough for multiple reconnects
  20709. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20710. sse.stop();
  20711. // Should have connected multiple times (initial + reconnects)
  20712. EXPECT_GE(connection_count.load(), 2);
  20713. // Should have received messages from multiple connections
  20714. EXPECT_GE(message_count.load(), 2);
  20715. }
  20716. // Test: A retry field that is not all ASCII digits is ignored
  20717. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20718. std::atomic<int> connection_count{0};
  20719. server_->Get("/bad-retry",
  20720. [&connection_count](const Request &, Response &res) {
  20721. connection_count.fetch_add(1);
  20722. res.set_chunked_content_provider(
  20723. "text/event-stream", [](size_t offset, DataSink &sink) {
  20724. if (offset == 0) {
  20725. std::string event = "retry: -1\ndata: hello\n\n";
  20726. sink.write(event.data(), event.size());
  20727. }
  20728. return false;
  20729. });
  20730. });
  20731. Client client("localhost", get_port());
  20732. sse::SSEClient sse(client, "/bad-retry");
  20733. sse.set_reconnect_interval(10000);
  20734. sse.start_async();
  20735. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20736. sse.stop();
  20737. EXPECT_EQ(connection_count.load(), 1);
  20738. }
  20739. // Test: A retry field of all ASCII digits sets the reconnection time
  20740. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20741. std::mutex mutex;
  20742. std::condition_variable cv;
  20743. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20744. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20745. {
  20746. std::lock_guard<std::mutex> lock(mutex);
  20747. connected_at.push_back(std::chrono::steady_clock::now());
  20748. cv.notify_all();
  20749. }
  20750. res.set_chunked_content_provider(
  20751. "text/event-stream", [](size_t offset, DataSink &sink) {
  20752. if (offset == 0) {
  20753. std::string event = "retry: 0\ndata: hello\n\n";
  20754. sink.write(event.data(), event.size());
  20755. }
  20756. return false;
  20757. });
  20758. });
  20759. Client client("localhost", get_port());
  20760. sse::SSEClient sse(client, "/zero-retry");
  20761. sse.set_reconnect_interval(10000);
  20762. sse.start_async();
  20763. {
  20764. std::unique_lock<std::mutex> lock(mutex);
  20765. cv.wait_for(lock, std::chrono::seconds(5),
  20766. [&] { return connected_at.size() >= 2; });
  20767. }
  20768. sse.stop();
  20769. // The server-supplied interval is applied, but never below 100ms, so
  20770. // "retry: 0" does not cause a busy reconnect loop
  20771. std::lock_guard<std::mutex> lock(mutex);
  20772. ASSERT_GE(connected_at.size(), 2u);
  20773. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20774. connected_at[1] - connected_at[0])
  20775. .count();
  20776. EXPECT_GE(interval_ms, 100);
  20777. }
  20778. // Test: Last-Event-ID sent on reconnect
  20779. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20780. std::atomic<int> connection_count{0};
  20781. std::vector<std::string> received_last_event_ids;
  20782. std::mutex id_mutex;
  20783. // Endpoint that checks Last-Event-ID header and sends event with ID
  20784. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20785. int conn = connection_count.fetch_add(1);
  20786. // Capture the Last-Event-ID header from each connection
  20787. {
  20788. std::lock_guard<std::mutex> lock(id_mutex);
  20789. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20790. }
  20791. res.set_chunked_content_provider(
  20792. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20793. if (offset == 0) {
  20794. std::string event =
  20795. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20796. sink.write(event.data(), event.size());
  20797. }
  20798. return false;
  20799. });
  20800. });
  20801. Client client("localhost", get_port());
  20802. sse::SSEClient sse(client, "/reconnect-with-id");
  20803. sse.set_reconnect_interval(100);
  20804. sse.set_max_reconnect_attempts(3);
  20805. sse.start_async();
  20806. // Wait for at least 2 connections
  20807. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20808. sse.stop();
  20809. // Verify behavior
  20810. std::lock_guard<std::mutex> lock(id_mutex);
  20811. EXPECT_GE(received_last_event_ids.size(), 2u);
  20812. // First connection should have no Last-Event-ID
  20813. if (!received_last_event_ids.empty()) {
  20814. EXPECT_EQ(received_last_event_ids[0], "");
  20815. }
  20816. // Second connection should have Last-Event-ID from first connection
  20817. if (received_last_event_ids.size() >= 2) {
  20818. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20819. }
  20820. }
  20821. // Test: set_headers updates headers used on reconnect
  20822. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20823. std::vector<std::string> received_tokens;
  20824. std::mutex token_mutex;
  20825. // Endpoint that captures Authorization header
  20826. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20827. {
  20828. std::lock_guard<std::mutex> lock(token_mutex);
  20829. received_tokens.push_back(req.get_header_value("Authorization"));
  20830. }
  20831. res.set_chunked_content_provider(
  20832. "text/event-stream", [](size_t offset, DataSink &sink) {
  20833. if (offset == 0) {
  20834. std::string event = "data: hello\n\n";
  20835. sink.write(event.data(), event.size());
  20836. }
  20837. return false; // Close connection to trigger reconnect
  20838. });
  20839. });
  20840. Client client("localhost", get_port());
  20841. Headers headers = {{"Authorization", "Bearer old-token"}};
  20842. sse::SSEClient sse(client, "/auth-check", headers);
  20843. // Update headers on each successful connection
  20844. sse.on_open(
  20845. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20846. sse.set_reconnect_interval(100);
  20847. sse.set_max_reconnect_attempts(3);
  20848. sse.start_async();
  20849. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20850. sse.stop();
  20851. std::lock_guard<std::mutex> lock(token_mutex);
  20852. ASSERT_GE(received_tokens.size(), 2u);
  20853. // First connection uses original header
  20854. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20855. // Second connection uses updated header from set_headers
  20856. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20857. }
  20858. // Test: 401 allows reconnection (so on_error can refresh headers)
  20859. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20860. std::atomic<int> connection_count{0};
  20861. // Endpoint: returns 401 on first attempt, 200 on second
  20862. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20863. int conn = connection_count.fetch_add(1);
  20864. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20865. res.status = StatusCode::Unauthorized_401;
  20866. res.set_content("Unauthorized", "text/plain");
  20867. return;
  20868. }
  20869. res.set_chunked_content_provider(
  20870. "text/event-stream", [](size_t offset, DataSink &sink) {
  20871. if (offset == 0) {
  20872. std::string event = "data: authenticated\n\n";
  20873. sink.write(event.data(), event.size());
  20874. }
  20875. return false;
  20876. });
  20877. });
  20878. Client client("localhost", get_port());
  20879. Headers headers = {{"Authorization", "Bearer expired"}};
  20880. sse::SSEClient sse(client, "/auth-retry", headers);
  20881. std::atomic<bool> message_received{false};
  20882. // Refresh token on error
  20883. sse.on_error(
  20884. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20885. sse.on_message([&](const sse::SSEMessage &msg) {
  20886. if (msg.data == "authenticated") { message_received.store(true); }
  20887. });
  20888. sse.set_reconnect_interval(100);
  20889. sse.set_max_reconnect_attempts(3);
  20890. sse.start_async();
  20891. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20892. sse.stop();
  20893. // Should have reconnected after 401 and succeeded with new token
  20894. EXPECT_GE(connection_count.load(), 2);
  20895. EXPECT_TRUE(message_received.load());
  20896. }
  20897. TEST(Issue2318Test, EmptyHostString) {
  20898. {
  20899. httplib::Client cli_empty("", PORT);
  20900. auto res = cli_empty.Get("/");
  20901. ASSERT_FALSE(res);
  20902. EXPECT_EQ(httplib::Error::Connection, res.error());
  20903. }
  20904. {
  20905. httplib::Client cli(" ", PORT);
  20906. auto res = cli.Get("/");
  20907. ASSERT_FALSE(res);
  20908. EXPECT_EQ(httplib::Error::Connection, res.error());
  20909. }
  20910. }
  20911. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20912. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20913. Server svr;
  20914. // Set a small payload limit (1KB)
  20915. svr.set_payload_max_length(1024);
  20916. svr.Post("/test", [&](const Request &req, Response &res) {
  20917. res.set_content("Body size: " + std::to_string(req.body.size()),
  20918. "text/plain");
  20919. });
  20920. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20921. auto se = detail::scope_exit([&] {
  20922. svr.stop();
  20923. listen_thread.join();
  20924. });
  20925. svr.wait_until_ready();
  20926. // Create data that compresses well but exceeds limit when decompressed
  20927. // 8KB of repeated null bytes compresses to a very small size
  20928. std::string original_data(8 * 1024, '\0');
  20929. // Compress the data using gzip
  20930. std::string compressed_data;
  20931. detail::gzip_compressor compressor;
  20932. compressor.compress(original_data.data(), original_data.size(), true,
  20933. [&](const char *data, size_t size) {
  20934. compressed_data.append(data, size);
  20935. return true;
  20936. });
  20937. // Verify compression worked (compressed should be much smaller)
  20938. ASSERT_LT(compressed_data.size(), original_data.size());
  20939. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20940. // Send compressed data with Content-Encoding: gzip
  20941. Client cli(HOST, PORT);
  20942. Headers headers = {{"Content-Encoding", "gzip"}};
  20943. auto res =
  20944. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20945. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20947. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20948. }
  20949. #endif
  20950. // ============================================================================
  20951. // OpenSSL-Specific Tests
  20952. // ============================================================================
  20953. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20954. X509 *readCertificate(const std::string &strFileName) {
  20955. std::ifstream inStream(strFileName);
  20956. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20957. std::istreambuf_iterator<char>());
  20958. if (strCertPEM.empty()) return (nullptr);
  20959. BIO *pbCert = BIO_new(BIO_s_mem());
  20960. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20961. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20962. BIO_free(pbCert);
  20963. return (pCert);
  20964. }
  20965. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20966. std::ifstream inStream(strFileName);
  20967. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20968. std::istreambuf_iterator<char>());
  20969. if (strPrivateKeyPEM.empty()) return (nullptr);
  20970. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20971. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20972. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20973. BIO_free(pbPrivKey);
  20974. return (pPrivateKey);
  20975. }
  20976. TEST(BindServerTest, UpdateCerts) {
  20977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20978. int port = svr.bind_to_any_port("0.0.0.0");
  20979. ASSERT_TRUE(svr.is_valid());
  20980. ASSERT_TRUE(port > 0);
  20981. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20982. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20983. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20984. ASSERT_TRUE(cert != nullptr);
  20985. ASSERT_TRUE(ca_cert != nullptr);
  20986. ASSERT_TRUE(key != nullptr);
  20987. X509_STORE *cert_store = X509_STORE_new();
  20988. X509_STORE_add_cert(cert_store, ca_cert);
  20989. // svr.update_certs(cert, key, cert_store); // deprecated
  20990. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20991. CLIENT_CA_CERT_FILE);
  20992. ASSERT_TRUE(svr.is_valid());
  20993. svr.stop();
  20994. X509_STORE_free(cert_store);
  20995. X509_free(cert);
  20996. X509_free(ca_cert);
  20997. EVP_PKEY_free(key);
  20998. }
  20999. // Test that update_certs() updates client CA list correctly
  21000. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21001. // Start with file-based constructor
  21002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21003. ASSERT_TRUE(svr.is_valid());
  21004. // Initially no client CA list should be set
  21005. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21006. ASSERT_TRUE(ssl_ctx != nullptr);
  21007. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21008. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21009. EXPECT_EQ(0, count_before);
  21010. // Now update with client CA (PEM string)
  21011. std::string cert_pem, key_pem, ca_pem;
  21012. read_file(SERVER_CERT_FILE, cert_pem);
  21013. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21014. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21015. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21016. ASSERT_TRUE(svr.is_valid());
  21017. // Now client CA list should be set
  21018. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21019. ASSERT_TRUE(ca_list_after != nullptr);
  21020. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21021. }
  21022. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21023. // Test that the file-path SSLServer constructor properly sets the client CA
  21024. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21026. ASSERT_TRUE(svr.is_valid());
  21027. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21028. ASSERT_TRUE(ssl_ctx != nullptr);
  21029. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21030. ASSERT_TRUE(ca_list != nullptr);
  21031. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21032. }
  21033. #endif
  21034. // ============================================================================
  21035. // MbedTLS-Specific Tests
  21036. // ============================================================================
  21037. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21038. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21039. using namespace httplib::tls;
  21040. // Track if callback was invoked
  21041. bool callback_invoked = false;
  21042. // The callback receives void* ctx which is actually MbedTlsContext*
  21043. // We can access the mbedtls_ssl_config via the context
  21044. auto setup_callback = [&callback_invoked](void *ctx) {
  21045. callback_invoked = true;
  21046. // Cast to MbedTlsContext* to access the ssl config
  21047. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21048. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21049. // Use static variables to hold certificate data (simplified for test)
  21050. static mbedtls_x509_crt own_cert;
  21051. static mbedtls_pk_context own_key;
  21052. static mbedtls_x509_crt ca_chain;
  21053. static bool initialized = false;
  21054. if (!initialized) {
  21055. mbedtls_x509_crt_init(&own_cert);
  21056. mbedtls_pk_init(&own_key);
  21057. mbedtls_x509_crt_init(&ca_chain);
  21058. // Load server certificate
  21059. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21060. return false;
  21061. }
  21062. // Load server private key.
  21063. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21064. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21065. #if MBEDTLS_VERSION_MAJOR == 3
  21066. ,
  21067. mbedtls_ctr_drbg_random, nullptr
  21068. #endif
  21069. ) != 0) {
  21070. return false;
  21071. }
  21072. // Load CA chain for client verification
  21073. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21074. return false;
  21075. }
  21076. initialized = true;
  21077. }
  21078. // Configure the SSL config
  21079. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21080. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21081. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21082. // Set minimum TLS version using mbedTLS native API
  21083. #if MBEDTLS_VERSION_MAJOR >= 3
  21084. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21085. #else
  21086. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21087. MBEDTLS_SSL_MINOR_VERSION_3);
  21088. #endif
  21089. return true;
  21090. };
  21091. SSLServer svr(setup_callback);
  21092. ASSERT_TRUE(svr.is_valid());
  21093. ASSERT_TRUE(callback_invoked);
  21094. svr.Get("/test", [&](const Request &req, Response &res) {
  21095. res.set_content("test", "text/plain");
  21096. auto cert = req.peer_cert();
  21097. ASSERT_TRUE(static_cast<bool>(cert));
  21098. auto common_name = cert.subject_cn();
  21099. EXPECT_EQ("Common Name", common_name);
  21100. });
  21101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21102. auto se = detail::scope_exit([&] {
  21103. svr.stop();
  21104. t.join();
  21105. ASSERT_FALSE(svr.is_running());
  21106. });
  21107. svr.wait_until_ready();
  21108. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21109. cli.enable_server_certificate_verification(false);
  21110. cli.set_connection_timeout(30);
  21111. auto res = cli.Get("/test");
  21112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21113. ASSERT_EQ(StatusCode::OK_200, res->status);
  21114. }
  21115. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21116. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21117. // keep-alive SSL session, which reads through that config in
  21118. // mbedtls_ssl_close_notify.
  21119. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21120. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21121. ASSERT_TRUE(svr.is_valid());
  21122. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21123. res.set_content("test", "text/plain");
  21124. });
  21125. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21126. auto se = detail::scope_exit([&] {
  21127. svr.stop();
  21128. t.join();
  21129. ASSERT_FALSE(svr.is_running());
  21130. });
  21131. svr.wait_until_ready();
  21132. {
  21133. SSLClient cli(HOST, PORT);
  21134. cli.enable_server_certificate_verification(false);
  21135. cli.set_keep_alive(true);
  21136. auto res = cli.Get("/test");
  21137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21138. ASSERT_EQ(StatusCode::OK_200, res->status);
  21139. // cli is destructed here with the keep-alive SSL session still open.
  21140. }
  21141. }
  21142. #endif
  21143. // WebSocket Tests
  21144. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21145. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21146. // defining the meaning of these bits has been negotiated.
  21147. auto make_frame = [](uint8_t first_byte) {
  21148. std::string frame;
  21149. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21150. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21151. frame += "Hello";
  21152. return frame;
  21153. };
  21154. // RSV1 set (0x40)
  21155. {
  21156. detail::BufferStream strm;
  21157. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21158. ws::Opcode opcode;
  21159. std::string payload;
  21160. bool fin;
  21161. EXPECT_EQ(
  21162. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21163. ws::impl::FrameRead::Fail);
  21164. }
  21165. // RSV2 set (0x20)
  21166. {
  21167. detail::BufferStream strm;
  21168. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21169. ws::Opcode opcode;
  21170. std::string payload;
  21171. bool fin;
  21172. EXPECT_EQ(
  21173. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21174. ws::impl::FrameRead::Fail);
  21175. }
  21176. // RSV3 set (0x10)
  21177. {
  21178. detail::BufferStream strm;
  21179. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21180. ws::Opcode opcode;
  21181. std::string payload;
  21182. bool fin;
  21183. EXPECT_EQ(
  21184. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21185. ws::impl::FrameRead::Fail);
  21186. }
  21187. // No RSV bits set - should succeed
  21188. {
  21189. detail::BufferStream strm;
  21190. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21191. ws::Opcode opcode;
  21192. std::string payload;
  21193. bool fin;
  21194. EXPECT_EQ(
  21195. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21196. ws::impl::FrameRead::Ok);
  21197. EXPECT_EQ(ws::Opcode::Text, opcode);
  21198. EXPECT_EQ("Hello", payload);
  21199. EXPECT_TRUE(fin);
  21200. }
  21201. }
  21202. TEST(WebSocketTest, ControlFrameValidation) {
  21203. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21204. // payload length <= 125.
  21205. // Ping with FIN=0 - must be rejected
  21206. {
  21207. detail::BufferStream strm;
  21208. std::string frame;
  21209. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21210. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21211. strm.write(frame.data(), frame.size());
  21212. ws::Opcode opcode;
  21213. std::string payload;
  21214. bool fin;
  21215. EXPECT_EQ(
  21216. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21217. ws::impl::FrameRead::Fail);
  21218. }
  21219. // Close with FIN=0 - must be rejected
  21220. {
  21221. detail::BufferStream strm;
  21222. std::string frame;
  21223. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21224. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21225. strm.write(frame.data(), frame.size());
  21226. ws::Opcode opcode;
  21227. std::string payload;
  21228. bool fin;
  21229. EXPECT_EQ(
  21230. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21231. ws::impl::FrameRead::Fail);
  21232. }
  21233. // Ping with payload_len=126 (extended length) - must be rejected
  21234. {
  21235. detail::BufferStream strm;
  21236. std::string frame;
  21237. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21238. frame += static_cast<char>(126); // payload_len=126 (>125)
  21239. frame += static_cast<char>(0x00); // extended length high byte
  21240. frame += static_cast<char>(126); // extended length low byte
  21241. frame += std::string(126, 'x');
  21242. strm.write(frame.data(), frame.size());
  21243. ws::Opcode opcode;
  21244. std::string payload;
  21245. bool fin;
  21246. EXPECT_EQ(
  21247. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21248. ws::impl::FrameRead::Fail);
  21249. }
  21250. // Ping with FIN=1 and payload_len=125 - should succeed
  21251. {
  21252. detail::BufferStream strm;
  21253. std::string frame;
  21254. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21255. frame += static_cast<char>(125); // payload_len=125
  21256. frame += std::string(125, 'x');
  21257. strm.write(frame.data(), frame.size());
  21258. ws::Opcode opcode;
  21259. std::string payload;
  21260. bool fin;
  21261. EXPECT_EQ(
  21262. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21263. ws::impl::FrameRead::Ok);
  21264. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21265. EXPECT_EQ(125u, payload.size());
  21266. EXPECT_TRUE(fin);
  21267. }
  21268. }
  21269. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21270. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21271. // length MUST be 0.
  21272. // MSB set - must be rejected
  21273. {
  21274. detail::BufferStream strm;
  21275. std::string frame;
  21276. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21277. frame += static_cast<char>(127); // 64-bit extended length
  21278. frame += static_cast<char>(0x80); // MSB set (invalid)
  21279. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21280. strm.write(frame.data(), frame.size());
  21281. ws::Opcode opcode;
  21282. std::string payload;
  21283. bool fin;
  21284. EXPECT_EQ(
  21285. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21286. ws::impl::FrameRead::Fail);
  21287. }
  21288. // MSB clear - should pass length parsing (will be rejected by max_len,
  21289. // but that's a different check; use a small length to verify)
  21290. {
  21291. detail::BufferStream strm;
  21292. std::string frame;
  21293. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21294. frame += static_cast<char>(127); // 64-bit extended length
  21295. frame += std::string(7, '\0'); // high bytes = 0
  21296. frame += static_cast<char>(0x03); // length = 3
  21297. frame += "abc";
  21298. strm.write(frame.data(), frame.size());
  21299. ws::Opcode opcode;
  21300. std::string payload;
  21301. bool fin;
  21302. EXPECT_EQ(
  21303. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21304. ws::impl::FrameRead::Ok);
  21305. EXPECT_EQ(ws::Opcode::Text, opcode);
  21306. EXPECT_EQ("abc", payload);
  21307. }
  21308. }
  21309. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21310. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21311. // Valid UTF-8
  21312. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21313. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21314. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21315. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21316. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21317. // Invalid UTF-8
  21318. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21319. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21320. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21321. EXPECT_FALSE(
  21322. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21323. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21324. }
  21325. TEST(WebSocketTest, ConnectAndDisconnect) {
  21326. Server svr;
  21327. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21328. std::string msg;
  21329. while (ws.read(msg)) {}
  21330. });
  21331. auto port = svr.bind_to_any_port(HOST);
  21332. std::thread t([&]() { svr.listen_after_bind(); });
  21333. svr.wait_until_ready();
  21334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21335. auto res = client.connect();
  21336. ASSERT_TRUE(res);
  21337. EXPECT_EQ(Error::Success, res.error());
  21338. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21339. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21340. EXPECT_TRUE(client.is_open());
  21341. client.close();
  21342. EXPECT_FALSE(client.is_open());
  21343. svr.stop();
  21344. t.join();
  21345. }
  21346. TEST(WebSocketTest, ValidURL) {
  21347. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21348. EXPECT_TRUE(ws1.is_valid());
  21349. ws::WebSocketClient ws2("ws://example.com/path");
  21350. EXPECT_TRUE(ws2.is_valid());
  21351. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21352. EXPECT_TRUE(ws3.is_valid());
  21353. #ifdef CPPHTTPLIB_SSL_ENABLED
  21354. ws::WebSocketClient wss1("wss://example.com/path");
  21355. EXPECT_TRUE(wss1.is_valid());
  21356. ws::WebSocketClient wss2("wss://example.com:443/path");
  21357. EXPECT_TRUE(wss2.is_valid());
  21358. #endif
  21359. }
  21360. TEST(WebSocketTest, InvalidURL) {
  21361. // No scheme
  21362. ws::WebSocketClient ws1("localhost:8080/path");
  21363. EXPECT_FALSE(ws1.is_valid());
  21364. // No path
  21365. ws::WebSocketClient ws2("ws://localhost:8080");
  21366. EXPECT_FALSE(ws2.is_valid());
  21367. // Empty string
  21368. ws::WebSocketClient ws3("");
  21369. EXPECT_FALSE(ws3.is_valid());
  21370. // Missing host
  21371. ws::WebSocketClient ws4("ws://:8080/path");
  21372. EXPECT_FALSE(ws4.is_valid());
  21373. // Port number overflow — should not crash
  21374. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21375. EXPECT_FALSE(ws5.is_valid());
  21376. // Port out of range
  21377. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21378. EXPECT_FALSE(ws6.is_valid());
  21379. }
  21380. TEST(WebSocketTest, UnsupportedScheme) {
  21381. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21382. ws::WebSocketClient ws1("http://localhost:8080/path");
  21383. EXPECT_FALSE(ws1.is_valid());
  21384. ws::WebSocketClient ws2("https://localhost:8080/path");
  21385. EXPECT_FALSE(ws2.is_valid());
  21386. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21387. EXPECT_FALSE(ws3.is_valid());
  21388. #else
  21389. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21390. std::invalid_argument);
  21391. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21392. std::invalid_argument);
  21393. #endif
  21394. }
  21395. TEST(WebSocketTest, ConnectWhenInvalid) {
  21396. ws::WebSocketClient ws("not a valid url");
  21397. EXPECT_FALSE(ws.is_valid());
  21398. auto res = ws.connect();
  21399. EXPECT_FALSE(res);
  21400. EXPECT_EQ(Error::Connection, res.error());
  21401. EXPECT_EQ(-1, res.status());
  21402. }
  21403. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21404. // Grab a port that is free, then close it again so nothing listens there
  21405. Server svr;
  21406. auto port = svr.bind_to_any_port(HOST);
  21407. svr.stop();
  21408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21409. auto res = client.connect();
  21410. ASSERT_FALSE(res);
  21411. EXPECT_EQ(Error::Connection, res.error());
  21412. EXPECT_EQ(-1, res.status());
  21413. }
  21414. TEST(WebSocketTest, DefaultPort) {
  21415. ws::WebSocketClient ws1("ws://example.com/path");
  21416. EXPECT_TRUE(ws1.is_valid());
  21417. // ws:// defaults to port 80 (verified by successful parse)
  21418. #ifdef CPPHTTPLIB_SSL_ENABLED
  21419. ws::WebSocketClient ws2("wss://example.com/path");
  21420. EXPECT_TRUE(ws2.is_valid());
  21421. // wss:// defaults to port 443 (verified by successful parse)
  21422. #endif
  21423. }
  21424. TEST(WebSocketTest, IPv6LiteralAddress) {
  21425. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21426. EXPECT_TRUE(ws1.is_valid());
  21427. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21428. EXPECT_TRUE(ws2.is_valid());
  21429. }
  21430. TEST(WebSocketTest, ComplexPath) {
  21431. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21432. EXPECT_TRUE(ws1.is_valid());
  21433. ws::WebSocketClient ws2("ws://localhost:8080/");
  21434. EXPECT_TRUE(ws2.is_valid());
  21435. }
  21436. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21437. Server svr;
  21438. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21439. std::string msg;
  21440. while (ws.read(msg)) {}
  21441. });
  21442. auto port = svr.bind_to_any_port(HOST);
  21443. std::thread t([&]() { svr.listen_after_bind(); });
  21444. svr.wait_until_ready();
  21445. auto another_host = "example.com";
  21446. auto wrong_ip = "192.0.2.1";
  21447. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21448. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21449. ASSERT_TRUE(client.connect());
  21450. EXPECT_TRUE(client.is_open());
  21451. client.close();
  21452. svr.stop();
  21453. t.join();
  21454. }
  21455. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21456. Server svr;
  21457. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21458. std::string msg;
  21459. while (ws.read(msg)) {}
  21460. });
  21461. auto port = svr.bind_to_any_port(HOST);
  21462. std::thread t([&]() { svr.listen_after_bind(); });
  21463. svr.wait_until_ready();
  21464. auto wrong_ip = "192.0.2.1";
  21465. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21466. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21467. client.set_connection_timeout(1);
  21468. client.set_read_timeout(1);
  21469. client.set_write_timeout(1);
  21470. EXPECT_FALSE(client.connect());
  21471. EXPECT_FALSE(client.is_open());
  21472. svr.stop();
  21473. t.join();
  21474. }
  21475. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21476. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21477. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21478. // (RFC 6761) is only a map key and the Host header value.
  21479. auto host = "target.invalid";
  21480. Server svr;
  21481. std::string received_host;
  21482. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21483. received_host = req.get_header_value("Host");
  21484. std::string msg;
  21485. while (ws.read(msg)) {}
  21486. });
  21487. auto port = svr.bind_to_any_port(HOST);
  21488. std::thread t([&]() { svr.listen_after_bind(); });
  21489. // ASSERT_* below returns from the test body, which would leave t joinable
  21490. // and make ~thread call std::terminate.
  21491. auto se = detail::scope_exit([&] {
  21492. svr.stop();
  21493. if (t.joinable()) { t.join(); }
  21494. });
  21495. svr.wait_until_ready();
  21496. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21497. std::to_string(port) + "/ws");
  21498. client.set_hostname_addr_map({{host, HOST}});
  21499. ASSERT_TRUE(client.connect());
  21500. EXPECT_TRUE(client.is_open());
  21501. client.close();
  21502. svr.stop();
  21503. t.join();
  21504. // The mapping only redirects the connection; the identity stays host_.
  21505. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21506. }
  21507. class WebSocketIntegrationTest : public ::testing::Test {
  21508. protected:
  21509. void SetUp() override {
  21510. server_ = httplib::detail::make_unique<Server>();
  21511. setup_server();
  21512. start_server();
  21513. }
  21514. void TearDown() override {
  21515. server_->stop();
  21516. if (server_thread_.joinable()) { server_thread_.join(); }
  21517. }
  21518. void setup_server() {
  21519. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21520. std::string msg;
  21521. ws::ReadResult ret;
  21522. while ((ret = ws.read(msg))) {
  21523. if (ret == ws::Binary) {
  21524. ws.send(msg.data(), msg.size());
  21525. } else {
  21526. ws.send(msg);
  21527. }
  21528. }
  21529. });
  21530. server_->WebSocket("/ws-echo-string",
  21531. [](const Request &, ws::WebSocket &ws) {
  21532. std::string msg;
  21533. while (ws.read(msg)) {
  21534. ws.send("echo: " + msg);
  21535. }
  21536. });
  21537. server_->WebSocket(
  21538. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21539. // Echo back request metadata
  21540. ws.send("path:" + req.path);
  21541. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21542. std::string msg;
  21543. while (ws.read(msg)) {}
  21544. });
  21545. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21546. std::string msg;
  21547. ws.read(msg); // wait for a message
  21548. ws.close();
  21549. });
  21550. server_->WebSocket("/ws-close-status",
  21551. [](const Request &, ws::WebSocket &ws) {
  21552. std::string msg;
  21553. ws.read(msg); // wait for a message
  21554. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21555. });
  21556. server_->WebSocket(
  21557. "/ws-subprotocol",
  21558. [](const Request &, ws::WebSocket &ws) {
  21559. std::string msg;
  21560. while (ws.read(msg)) {
  21561. ws.send(msg);
  21562. }
  21563. },
  21564. [](const std::vector<std::string> &protocols) -> std::string {
  21565. for (const auto &p : protocols) {
  21566. if (p == "graphql-ws") { return p; }
  21567. }
  21568. return "";
  21569. });
  21570. server_->WebSocket(
  21571. "/ws-subprotocol-unoffered",
  21572. [](const Request &, ws::WebSocket &ws) {
  21573. std::string msg;
  21574. while (ws.read(msg)) {
  21575. ws.send(msg);
  21576. }
  21577. },
  21578. [](const std::vector<std::string> &) -> std::string {
  21579. return "admin";
  21580. });
  21581. }
  21582. void start_server() {
  21583. port_ = server_->bind_to_any_port(HOST);
  21584. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21585. server_->wait_until_ready();
  21586. }
  21587. std::unique_ptr<Server> server_;
  21588. std::thread server_thread_;
  21589. int port_ = 0;
  21590. };
  21591. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21593. "/ws-echo");
  21594. ASSERT_TRUE(client.connect());
  21595. ASSERT_TRUE(client.is_open());
  21596. ASSERT_TRUE(client.send("Hello WebSocket"));
  21597. std::string msg;
  21598. EXPECT_EQ(ws::Text, client.read(msg));
  21599. EXPECT_EQ("Hello WebSocket", msg);
  21600. client.close();
  21601. }
  21602. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21603. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21604. "/ws-echo");
  21605. ASSERT_TRUE(client.connect());
  21606. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21607. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21608. std::string msg;
  21609. EXPECT_EQ(ws::Binary, client.read(msg));
  21610. EXPECT_EQ(binary_data, msg);
  21611. client.close();
  21612. }
  21613. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21614. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21615. "/ws-echo");
  21616. ASSERT_TRUE(client.connect());
  21617. for (int i = 0; i < 10; i++) {
  21618. auto text = "message " + std::to_string(i);
  21619. ASSERT_TRUE(client.send(text));
  21620. std::string msg;
  21621. ASSERT_TRUE(client.read(msg));
  21622. EXPECT_EQ(text, msg);
  21623. }
  21624. client.close();
  21625. }
  21626. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21627. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21628. "/ws-close");
  21629. ASSERT_TRUE(client.connect());
  21630. // Send a message to trigger the server to close
  21631. ASSERT_TRUE(client.send("trigger close"));
  21632. // The server will close, so read should return false
  21633. std::string msg;
  21634. EXPECT_FALSE(client.read(msg));
  21635. EXPECT_FALSE(client.is_open());
  21636. }
  21637. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21638. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21639. "/ws-echo");
  21640. ASSERT_TRUE(client.connect());
  21641. // 128KB message
  21642. std::string large_data(128 * 1024, 'X');
  21643. ASSERT_TRUE(client.send(large_data));
  21644. std::string msg;
  21645. ASSERT_TRUE(client.read(msg));
  21646. EXPECT_EQ(large_data, msg);
  21647. client.close();
  21648. }
  21649. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21650. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21651. "/ws-echo");
  21652. ASSERT_TRUE(client.connect());
  21653. const int num_threads = 4;
  21654. std::vector<std::thread> threads;
  21655. std::atomic<int> send_count{0};
  21656. for (int t = 0; t < num_threads; t++) {
  21657. threads.emplace_back([&client, &send_count, t]() {
  21658. for (int i = 0; i < 5; i++) {
  21659. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21660. if (client.send(text)) { send_count++; }
  21661. }
  21662. });
  21663. }
  21664. for (auto &th : threads) {
  21665. th.join();
  21666. }
  21667. int received = 0;
  21668. std::string msg;
  21669. while (received < send_count.load()) {
  21670. if (!client.read(msg)) { break; }
  21671. received++;
  21672. }
  21673. EXPECT_EQ(send_count.load(), received);
  21674. client.close();
  21675. }
  21676. TEST_F(WebSocketIntegrationTest, ReadString) {
  21677. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21678. "/ws-echo-string");
  21679. ASSERT_TRUE(client.connect());
  21680. ASSERT_TRUE(client.send("hello"));
  21681. std::string msg;
  21682. ASSERT_TRUE(client.read(msg));
  21683. EXPECT_EQ("echo: hello", msg);
  21684. ASSERT_TRUE(client.send("world"));
  21685. ASSERT_TRUE(client.read(msg));
  21686. EXPECT_EQ("echo: world", msg);
  21687. client.close();
  21688. }
  21689. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21690. Headers headers = {{"X-Test-Header", "test-value"}};
  21691. ws::WebSocketClient client(
  21692. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21693. ASSERT_TRUE(client.connect());
  21694. std::string msg;
  21695. ASSERT_TRUE(client.read(msg));
  21696. EXPECT_EQ("path:/ws-request-info", msg);
  21697. ASSERT_TRUE(client.read(msg));
  21698. EXPECT_EQ("header:test-value", msg);
  21699. client.close();
  21700. }
  21701. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21703. "/ws-echo");
  21704. client.set_read_timeout(1, 0); // 1 second
  21705. ASSERT_TRUE(client.connect());
  21706. // Don't send anything — server echo handler waits for a message, so read()
  21707. // should time out. The connection survives it: nothing was consumed.
  21708. std::string msg;
  21709. EXPECT_EQ(client.read(msg), ws::Timeout);
  21710. EXPECT_TRUE(client.is_open());
  21711. // And it is still usable afterwards.
  21712. EXPECT_TRUE(client.send("after timeout"));
  21713. EXPECT_EQ(client.read(msg), ws::Text);
  21714. EXPECT_EQ(msg, "after timeout");
  21715. }
  21716. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21717. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21718. "/ws-echo");
  21719. client.set_read_timeout(1, 0);
  21720. ASSERT_TRUE(client.connect());
  21721. ASSERT_TRUE(client.send("first"));
  21722. std::string msg;
  21723. ASSERT_EQ(client.read(msg), ws::Text);
  21724. ASSERT_EQ(msg, "first");
  21725. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21726. // not be used with a read timeout: it would reprocess the previous message.
  21727. EXPECT_EQ(client.read(msg), ws::Timeout);
  21728. EXPECT_EQ(msg, "first");
  21729. }
  21730. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21732. "/ws-echo");
  21733. ASSERT_TRUE(client.connect());
  21734. // Setting it once the connection is open reaches the live stream, not just
  21735. // the seed for the next connect().
  21736. client.set_read_timeout(1, 0);
  21737. std::string msg;
  21738. EXPECT_EQ(client.read(msg), ws::Timeout);
  21739. EXPECT_TRUE(client.is_open());
  21740. }
  21741. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21742. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21743. "/ws-echo");
  21744. client.set_read_timeout(5, 0);
  21745. ASSERT_TRUE(client.connect());
  21746. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21747. // The server should reject it and close the connection.
  21748. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21749. client.send(oversized);
  21750. // The server's read() should have failed due to payload limit,
  21751. // so our read() should return false (connection closed).
  21752. std::string msg;
  21753. EXPECT_FALSE(client.read(msg));
  21754. }
  21755. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21756. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21757. "/ws-echo");
  21758. client.set_read_timeout(10, 0);
  21759. ASSERT_TRUE(client.connect());
  21760. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21761. // This should succeed.
  21762. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21763. ASSERT_TRUE(client.send(at_limit));
  21764. std::string msg;
  21765. ASSERT_TRUE(client.read(msg));
  21766. EXPECT_EQ(at_limit.size(), msg.size());
  21767. client.close();
  21768. }
  21769. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21770. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21771. "/nonexistent");
  21772. auto res = client.connect();
  21773. EXPECT_FALSE(res);
  21774. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21775. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21776. EXPECT_FALSE(client.is_open());
  21777. }
  21778. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21779. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21780. "/ws-echo");
  21781. ASSERT_TRUE(client.connect());
  21782. ASSERT_TRUE(client.send(""));
  21783. std::string msg;
  21784. EXPECT_EQ(ws::Text, client.read(msg));
  21785. EXPECT_EQ("", msg);
  21786. client.close();
  21787. }
  21788. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21789. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21790. "/ws-echo");
  21791. // First connection
  21792. ASSERT_TRUE(client.connect());
  21793. ASSERT_TRUE(client.send("first"));
  21794. std::string msg;
  21795. ASSERT_TRUE(client.read(msg));
  21796. EXPECT_EQ("first", msg);
  21797. client.close();
  21798. EXPECT_FALSE(client.is_open());
  21799. // Reconnect using the same client object
  21800. ASSERT_TRUE(client.connect());
  21801. ASSERT_TRUE(client.is_open());
  21802. ASSERT_TRUE(client.send("second"));
  21803. ASSERT_TRUE(client.read(msg));
  21804. EXPECT_EQ("second", msg);
  21805. client.close();
  21806. }
  21807. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21808. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21809. "/ws-close-status");
  21810. ASSERT_TRUE(client.connect());
  21811. // Trigger the server to close with GoingAway status
  21812. ASSERT_TRUE(client.send("trigger"));
  21813. // read() should return false after receiving the close frame
  21814. std::string msg;
  21815. EXPECT_FALSE(client.read(msg));
  21816. EXPECT_FALSE(client.is_open());
  21817. }
  21818. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21820. "/ws-echo");
  21821. ASSERT_TRUE(client.connect());
  21822. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21823. EXPECT_FALSE(client.is_open());
  21824. }
  21825. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21826. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21827. ws::WebSocketClient client(
  21828. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21829. ASSERT_TRUE(client.connect());
  21830. // Server should have selected graphql-ws
  21831. EXPECT_EQ("graphql-ws", client.subprotocol());
  21832. client.close();
  21833. }
  21834. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21835. Headers headers;
  21836. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21837. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21838. ws::WebSocketClient client(
  21839. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21840. ASSERT_TRUE(client.connect());
  21841. // The offer on the second field line counts too, so graphql-ws is selected
  21842. EXPECT_EQ("graphql-ws", client.subprotocol());
  21843. client.close();
  21844. }
  21845. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21846. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21847. ws::WebSocketClient client(
  21848. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21849. ASSERT_TRUE(client.connect());
  21850. // Server should not have selected any subprotocol
  21851. EXPECT_TRUE(client.subprotocol().empty());
  21852. client.close();
  21853. }
  21854. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21855. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21857. "/ws-subprotocol-unoffered",
  21858. headers);
  21859. ASSERT_TRUE(client.connect());
  21860. EXPECT_TRUE(client.subprotocol().empty());
  21861. client.close();
  21862. }
  21863. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21864. // Connect without requesting any subprotocol
  21865. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21866. "/ws-subprotocol");
  21867. ASSERT_TRUE(client.connect());
  21868. EXPECT_TRUE(client.subprotocol().empty());
  21869. client.close();
  21870. }
  21871. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21872. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21873. "/ws-echo");
  21874. client.set_tcp_nodelay(true);
  21875. client.set_connection_timeout(3, 0);
  21876. bool socket_options_called = false;
  21877. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21878. ASSERT_TRUE(client.connect());
  21879. ASSERT_TRUE(client.is_open());
  21880. EXPECT_TRUE(socket_options_called);
  21881. ASSERT_TRUE(client.send("hello"));
  21882. std::string msg;
  21883. auto result = client.read(msg);
  21884. EXPECT_EQ(result, ws::ReadResult::Text);
  21885. EXPECT_EQ(msg, "hello");
  21886. client.close();
  21887. }
  21888. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21890. "/ws-echo");
  21891. client.set_connection_timeout(std::chrono::seconds(3));
  21892. client.set_write_timeout(std::chrono::seconds(3));
  21893. // A sub-second remainder exercises the seconds/microseconds split.
  21894. client.set_read_timeout(std::chrono::milliseconds(1500));
  21895. ASSERT_TRUE(client.connect());
  21896. auto start = std::chrono::steady_clock::now();
  21897. std::string msg;
  21898. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21899. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21900. std::chrono::steady_clock::now() - start)
  21901. .count();
  21902. // Above 1s so that dropping the microseconds half of the split fails here.
  21903. // Ignoring the setter altogether would not reach this line at all: a client
  21904. // waits forever by default.
  21905. EXPECT_GE(elapsed, 1400);
  21906. EXPECT_LT(elapsed, 30000);
  21907. }
  21908. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21909. Server svr;
  21910. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21911. if (!req.has_header("Authorization")) {
  21912. res.status = StatusCode::Unauthorized_401;
  21913. res.set_content("Unauthorized", "text/plain");
  21914. return Server::HandlerResponse::Handled;
  21915. }
  21916. return Server::HandlerResponse::Unhandled;
  21917. });
  21918. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21919. std::string msg;
  21920. while (ws.read(msg)) {
  21921. ws.send(msg);
  21922. }
  21923. });
  21924. auto port = svr.bind_to_any_port("localhost");
  21925. std::thread t([&]() { svr.listen_after_bind(); });
  21926. svr.wait_until_ready();
  21927. // Without Authorization header - should be rejected before upgrade
  21928. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21929. EXPECT_FALSE(client1.connect());
  21930. // The rejection is framed like any other HTTP response
  21931. {
  21932. Client cli("localhost", port);
  21933. Headers headers = {{"Upgrade", "websocket"},
  21934. {"Connection", "Upgrade"},
  21935. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21936. {"Sec-WebSocket-Version", "13"}};
  21937. auto res = cli.Get("/ws", headers);
  21938. ASSERT_TRUE(res);
  21939. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21940. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21941. EXPECT_EQ("Unauthorized", res->body);
  21942. }
  21943. // With Authorization header - should succeed
  21944. Headers headers = {{"Authorization", "Bearer token123"}};
  21945. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21946. headers);
  21947. ASSERT_TRUE(client2.connect());
  21948. ASSERT_TRUE(client2.send("hello"));
  21949. std::string msg;
  21950. ASSERT_TRUE(client2.read(msg));
  21951. EXPECT_EQ("hello", msg);
  21952. client2.close();
  21953. svr.stop();
  21954. t.join();
  21955. }
  21956. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21957. Server svr;
  21958. std::atomic<int> pre_request_calls{0};
  21959. std::atomic<bool> route_matched{false};
  21960. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21961. pre_request_calls++;
  21962. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21963. if (req.get_header_value("Authorization") != "Bearer token123") {
  21964. res.status = StatusCode::Unauthorized_401;
  21965. res.set_content("Unauthorized", "text/plain");
  21966. return Server::HandlerResponse::Handled;
  21967. }
  21968. return Server::HandlerResponse::Unhandled;
  21969. });
  21970. std::atomic<bool> handler_called{false};
  21971. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21972. handler_called = true;
  21973. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21974. });
  21975. auto port = svr.bind_to_any_port("localhost");
  21976. std::thread t([&]() { svr.listen_after_bind(); });
  21977. svr.wait_until_ready();
  21978. // Without Authorization header - should be rejected before upgrade
  21979. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21980. "/ws/1");
  21981. EXPECT_FALSE(client1.connect());
  21982. EXPECT_FALSE(handler_called);
  21983. EXPECT_EQ(1, pre_request_calls);
  21984. EXPECT_TRUE(route_matched);
  21985. // The rejection is an ordinary HTTP response, not a protocol switch
  21986. {
  21987. Client cli("localhost", port);
  21988. Headers headers = {{"Upgrade", "websocket"},
  21989. {"Connection", "Upgrade"},
  21990. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21991. {"Sec-WebSocket-Version", "13"}};
  21992. auto res = cli.Get("/ws/1", headers);
  21993. ASSERT_TRUE(res);
  21994. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21995. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21996. EXPECT_EQ("Unauthorized", res->body);
  21997. }
  21998. EXPECT_FALSE(handler_called);
  21999. // With Authorization header - should succeed
  22000. Headers headers = {{"Authorization", "Bearer token123"}};
  22001. ws::WebSocketClient client2(
  22002. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22003. ASSERT_TRUE(client2.connect());
  22004. std::string msg;
  22005. ASSERT_TRUE(client2.read(msg));
  22006. EXPECT_EQ("/ws/:id 2", msg);
  22007. EXPECT_TRUE(handler_called);
  22008. client2.close();
  22009. svr.stop();
  22010. t.join();
  22011. }
  22012. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22013. Server svr;
  22014. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22015. // A read timeout is how a handler gets control back. Without it, a handler
  22016. // parked in read() can never write on the connection it is reading.
  22017. ws.set_read_timeout(std::chrono::milliseconds(100));
  22018. std::string msg;
  22019. while (ws.is_open()) {
  22020. auto r = ws.read(msg);
  22021. if (r == httplib::ws::Timeout) {
  22022. ws.send("tick");
  22023. continue;
  22024. }
  22025. if (r == httplib::ws::Fail) { break; }
  22026. ws.send(msg);
  22027. }
  22028. });
  22029. auto port = svr.bind_to_any_port("localhost");
  22030. std::thread t([&]() { svr.listen_after_bind(); });
  22031. svr.wait_until_ready();
  22032. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22033. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22034. ASSERT_TRUE(client.connect());
  22035. // The client sends nothing, so anything it receives came out of the
  22036. // handler's timeout path.
  22037. std::string msg;
  22038. ASSERT_EQ(client.read(msg), ws::Text);
  22039. EXPECT_EQ("tick", msg);
  22040. client.close();
  22041. svr.stop();
  22042. t.join();
  22043. }
  22044. // Stream::read may return fewer bytes than asked for. This is that contract at
  22045. // its worst -- one byte per call -- which is what a frame header straddling a
  22046. // read buffer's boundary looks like to the frame parser.
  22047. class WsByteAtATimeStream : public Stream {
  22048. public:
  22049. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22050. bool is_readable() const override { return true; }
  22051. bool wait_readable() const override { return true; }
  22052. bool wait_writable() const override { return true; }
  22053. ssize_t read(char *ptr, size_t size) override {
  22054. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22055. *ptr = data_[pos_++];
  22056. return 1;
  22057. }
  22058. ssize_t write(const char *, size_t size) override {
  22059. return static_cast<ssize_t>(size);
  22060. }
  22061. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22062. ip = "127.0.0.1";
  22063. port = 0;
  22064. }
  22065. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22066. ip = "127.0.0.1";
  22067. port = 0;
  22068. }
  22069. socket_t socket() const override { return INVALID_SOCKET; }
  22070. time_t duration() const override { return 0; }
  22071. private:
  22072. std::string data_;
  22073. size_t pos_ = 0;
  22074. };
  22075. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22076. // The payload uses the 16-bit extended length, so the header, the length
  22077. // and the mask key are all multi-byte fields here. Each used to be read
  22078. // with a single read() call, which fails as soon as one is split. The
  22079. // payload is also a little over one read chunk, so it is read in two.
  22080. std::string body;
  22081. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22082. body += static_cast<char>(i % 251);
  22083. }
  22084. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22085. std::string frame;
  22086. frame += static_cast<char>(0x81); // FIN + Text
  22087. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22088. frame += static_cast<char>(body.size() >> 8);
  22089. frame += static_cast<char>(body.size() & 0xff);
  22090. for (size_t i = 0; i < 4; i++) {
  22091. frame += static_cast<char>(mask[i]);
  22092. }
  22093. for (size_t i = 0; i < body.size(); i++) {
  22094. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22095. }
  22096. WsByteAtATimeStream strm(frame);
  22097. ws::Opcode opcode;
  22098. std::string payload;
  22099. bool fin = false;
  22100. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22101. /*expect_masked=*/true, body.size()),
  22102. ws::impl::FrameRead::Ok);
  22103. EXPECT_TRUE(fin);
  22104. EXPECT_EQ(opcode, ws::Opcode::Text);
  22105. EXPECT_EQ(payload, body);
  22106. }
  22107. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22108. std::string body(2000, 'x');
  22109. std::string frame;
  22110. frame += static_cast<char>(0x82); // FIN + Binary
  22111. frame += static_cast<char>(126); // 16-bit length follows
  22112. frame += static_cast<char>(body.size() >> 8);
  22113. frame += static_cast<char>(body.size() & 0xff);
  22114. frame += body;
  22115. detail::BufferStream strm;
  22116. strm.write(frame.data(), frame.size());
  22117. ws::Opcode opcode;
  22118. std::string payload;
  22119. bool fin;
  22120. EXPECT_EQ(
  22121. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22122. ws::impl::FrameRead::Ok);
  22123. EXPECT_EQ(body, payload);
  22124. }
  22125. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22126. // The header announces the largest payload allowed, and only 3 bytes of it
  22127. // ever arrive.
  22128. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22129. std::string frame;
  22130. frame += static_cast<char>(0x82); // FIN + Binary
  22131. frame += static_cast<char>(127); // 64-bit length follows
  22132. for (int shift = 56; shift >= 0; shift -= 8) {
  22133. frame += static_cast<char>((len >> shift) & 0xff);
  22134. }
  22135. frame += "abc";
  22136. detail::BufferStream strm;
  22137. strm.write(frame.data(), frame.size());
  22138. ws::Opcode opcode;
  22139. std::string payload;
  22140. bool fin;
  22141. EXPECT_EQ(
  22142. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22143. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22144. ws::impl::FrameRead::Fail);
  22145. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22146. }
  22147. TEST(WebSocketTest, QueryStringInHandshake) {
  22148. Server svr;
  22149. std::mutex mtx;
  22150. std::string received_target;
  22151. std::string received_token;
  22152. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22153. {
  22154. std::lock_guard<std::mutex> lock(mtx);
  22155. received_target = req.target;
  22156. if (req.has_param("token")) {
  22157. received_token = req.get_param_value("token");
  22158. }
  22159. }
  22160. std::string msg;
  22161. while (ws.read(msg)) {
  22162. ws.send(msg);
  22163. }
  22164. });
  22165. auto port = svr.bind_to_any_port("localhost");
  22166. std::thread t([&]() { svr.listen_after_bind(); });
  22167. svr.wait_until_ready();
  22168. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22169. "/ws?token=ABC&session=123");
  22170. ASSERT_TRUE(client.connect());
  22171. // Round-trip ensures the handler has run and captured the request.
  22172. ASSERT_TRUE(client.send("hello"));
  22173. std::string msg;
  22174. ASSERT_TRUE(client.read(msg));
  22175. EXPECT_EQ("hello", msg);
  22176. client.close();
  22177. {
  22178. std::lock_guard<std::mutex> lock(mtx);
  22179. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22180. EXPECT_EQ("ABC", received_token);
  22181. }
  22182. svr.stop();
  22183. t.join();
  22184. }
  22185. // Run a handshake against a throwaway server and hand the request the server
  22186. // received back to the caller, so tests can assert on the headers the client
  22187. // actually put on the wire.
  22188. static void capture_websocket_handshake_request(
  22189. const Headers &client_headers,
  22190. std::function<void(const Request &, int port)> verify) {
  22191. Server svr;
  22192. std::mutex mtx;
  22193. Request received;
  22194. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22195. {
  22196. std::lock_guard<std::mutex> lock(mtx);
  22197. received = req;
  22198. }
  22199. std::string msg;
  22200. while (ws.read(msg)) {
  22201. ws.send(msg);
  22202. }
  22203. });
  22204. auto port = svr.bind_to_any_port("localhost");
  22205. std::thread t([&]() { svr.listen_after_bind(); });
  22206. auto se = detail::scope_exit([&] {
  22207. svr.stop();
  22208. t.join();
  22209. });
  22210. svr.wait_until_ready();
  22211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22212. client_headers);
  22213. ASSERT_TRUE(client.connect());
  22214. ASSERT_TRUE(client.send("hello"));
  22215. std::string msg;
  22216. ASSERT_TRUE(client.read(msg));
  22217. client.close();
  22218. {
  22219. std::lock_guard<std::mutex> lock(mtx);
  22220. verify(received, port);
  22221. }
  22222. }
  22223. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22224. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22225. // Non-default port must be present in the Host header. Default ports
  22226. // (80/443) are omitted; that logic is covered by
  22227. // MakeHostAndPortStringTest.
  22228. EXPECT_EQ("localhost:" + std::to_string(port),
  22229. req.get_header_value("Host"));
  22230. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22231. req.get_header_value("User-Agent"));
  22232. EXPECT_FALSE(req.has_header("Accept"));
  22233. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22234. EXPECT_FALSE(req.has_header("Content-Length"));
  22235. });
  22236. }
  22237. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22238. capture_websocket_handshake_request(
  22239. {{"Host", "example.com"},
  22240. {"User-Agent", "custom-agent"},
  22241. {"X-Custom", "value"}},
  22242. [](const Request &req, int) {
  22243. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22244. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22245. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22246. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22247. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22248. });
  22249. }
  22250. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22251. capture_websocket_handshake_request(
  22252. {{"Upgrade", "bogus"},
  22253. {"Connection", "close"},
  22254. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22255. {"Sec-WebSocket-Version", "8"}},
  22256. [](const Request &req, int) {
  22257. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22258. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22259. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22260. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22261. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22262. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22263. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22264. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22265. req.get_header_value("Sec-WebSocket-Key"));
  22266. });
  22267. }
  22268. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22269. // A header the client refuses to send must abort the handshake before any
  22270. // part of it reaches the wire; a lone request line would otherwise sit in
  22271. // the peer's buffer as a truncated request.
  22272. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22273. ASSERT_NE(INVALID_SOCKET, srv);
  22274. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22275. sockaddr_in addr{};
  22276. addr.sin_family = AF_INET;
  22277. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22278. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22279. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22280. ASSERT_EQ(0, ::listen(srv, 1));
  22281. sockaddr_in bound{};
  22282. socklen_t bound_len = sizeof(bound);
  22283. ASSERT_EQ(
  22284. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22285. auto port = ntohs(bound.sin_port);
  22286. ssize_t received = -1;
  22287. std::thread t([&] {
  22288. // Bound every blocking call so a regression fails the test with a bad
  22289. // value instead of hanging the suite.
  22290. fd_set rfds;
  22291. FD_ZERO(&rfds);
  22292. FD_SET(srv, &rfds);
  22293. timeval tv{5, 0};
  22294. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22295. 0) {
  22296. return;
  22297. }
  22298. sockaddr_in cli_addr{};
  22299. socklen_t cli_len = sizeof(cli_addr);
  22300. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22301. if (cli == INVALID_SOCKET) { return; }
  22302. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22303. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22304. char buf[4096];
  22305. received = ::recv(cli, buf, sizeof(buf), 0);
  22306. });
  22307. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22308. // connect() has already shut the socket down by the time it returns false,
  22309. // so the peer sees EOF without waiting for the client to be destroyed.
  22310. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22311. {{"X-Bad", "a\r\nInjected: 1"}});
  22312. EXPECT_FALSE(client.connect());
  22313. t.join();
  22314. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22315. EXPECT_EQ(0, received);
  22316. }
  22317. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22318. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22319. // contains "upgrade" as a substring is a different token and must not
  22320. // start a WebSocket handshake.
  22321. auto make_request = [](const std::vector<std::string> &connection_values) {
  22322. Request req;
  22323. req.method = "GET";
  22324. req.headers.emplace("Upgrade", "websocket");
  22325. for (const auto &value : connection_values) {
  22326. req.headers.emplace("Connection", value);
  22327. }
  22328. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22329. req.headers.emplace("Sec-WebSocket-Version", "13");
  22330. return req;
  22331. };
  22332. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22333. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22334. EXPECT_TRUE(
  22335. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22336. EXPECT_TRUE(
  22337. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22338. EXPECT_TRUE(
  22339. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22340. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22341. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22342. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22343. EXPECT_FALSE(
  22344. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22345. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22346. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22347. }
  22348. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22349. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22350. // asks recipients to match each protocol-name case-insensitively, and RFC
  22351. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22352. // client naming websocket alongside another protocol, or on a second field
  22353. // line, is offering websocket; a value that merely contains "websocket" as a
  22354. // substring is a different protocol name and is not.
  22355. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22356. Request req;
  22357. req.method = "GET";
  22358. for (const auto &value : upgrade_values) {
  22359. req.headers.emplace("Upgrade", value);
  22360. }
  22361. req.headers.emplace("Connection", "Upgrade");
  22362. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22363. req.headers.emplace("Sec-WebSocket-Version", "13");
  22364. return req;
  22365. };
  22366. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22367. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22368. EXPECT_TRUE(
  22369. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22370. EXPECT_TRUE(
  22371. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22372. EXPECT_TRUE(
  22373. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22374. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22375. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22376. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22377. EXPECT_FALSE(
  22378. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22379. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22380. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22381. }
  22382. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22383. Server svr;
  22384. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22385. auto port = svr.bind_to_any_port("localhost");
  22386. std::thread t([&]() { svr.listen_after_bind(); });
  22387. auto se = detail::scope_exit([&] {
  22388. svr.stop();
  22389. t.join();
  22390. });
  22391. svr.wait_until_ready();
  22392. Headers headers = {{"Upgrade", "websocket"},
  22393. {"Connection", "notupgrade"},
  22394. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22395. {"Sec-WebSocket-Version", "13"}};
  22396. Client cli("localhost", port);
  22397. auto res = cli.Get("/ws", headers);
  22398. // The route exists only as a WebSocket route, so a request that fails the
  22399. // handshake check falls through to ordinary routing.
  22400. ASSERT_TRUE(res);
  22401. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22402. }
  22403. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22404. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22405. // Connection value is the only thing left for the client to reject.
  22406. Server svr;
  22407. svr.Get("/ws", [](const Request &req, Response &res) {
  22408. res.status = StatusCode::SwitchingProtocol_101;
  22409. res.set_header("Upgrade", "websocket");
  22410. res.set_header("Connection", "notupgrade");
  22411. res.set_header("Sec-WebSocket-Accept",
  22412. detail::websocket_accept_key(
  22413. req.get_header_value("Sec-WebSocket-Key")));
  22414. });
  22415. auto port = svr.bind_to_any_port("localhost");
  22416. std::thread t([&]() { svr.listen_after_bind(); });
  22417. auto se = detail::scope_exit([&] {
  22418. svr.stop();
  22419. t.join();
  22420. });
  22421. svr.wait_until_ready();
  22422. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22423. auto res = client.connect();
  22424. EXPECT_FALSE(res);
  22425. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22426. EXPECT_FALSE(client.is_open());
  22427. }
  22428. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22429. Server svr;
  22430. svr.Get("/ws", [](const Request &req, Response &res) {
  22431. res.status = StatusCode::SwitchingProtocol_101;
  22432. res.set_header("Upgrade", "websocket");
  22433. res.set_header("Connection", "Upgrade");
  22434. res.set_header("Sec-WebSocket-Accept",
  22435. detail::websocket_accept_key(
  22436. req.get_header_value("Sec-WebSocket-Key")));
  22437. res.set_header("Sec-WebSocket-Protocol", "admin");
  22438. });
  22439. auto port = svr.bind_to_any_port("localhost");
  22440. std::thread t([&]() { svr.listen_after_bind(); });
  22441. auto se = detail::scope_exit([&] {
  22442. svr.stop();
  22443. t.join();
  22444. });
  22445. svr.wait_until_ready();
  22446. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22447. // Server selects a subprotocol the client never offered
  22448. {
  22449. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22450. ws::WebSocketClient client(url, headers);
  22451. auto res = client.connect();
  22452. EXPECT_FALSE(res);
  22453. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22454. EXPECT_FALSE(client.is_open());
  22455. EXPECT_TRUE(client.subprotocol().empty());
  22456. }
  22457. // Client offered none but the server named one anyway
  22458. {
  22459. ws::WebSocketClient client(url);
  22460. auto res = client.connect();
  22461. EXPECT_FALSE(res);
  22462. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22463. EXPECT_FALSE(client.is_open());
  22464. EXPECT_TRUE(client.subprotocol().empty());
  22465. }
  22466. }
  22467. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22468. // The socket path doubles as the URL host, so it must not contain '/'.
  22469. const char *shard = getenv("GTEST_SHARD_INDEX");
  22470. const std::string sock_path =
  22471. shard ? std::string("httplib-ws-") + shard + ".sock"
  22472. : std::string("httplib-ws.sock");
  22473. std::remove(sock_path.c_str());
  22474. Server svr;
  22475. std::mutex mtx;
  22476. std::string received_host;
  22477. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22478. {
  22479. std::lock_guard<std::mutex> lock(mtx);
  22480. received_host = req.get_header_value("Host");
  22481. }
  22482. std::string msg;
  22483. while (ws.read(msg)) {
  22484. ws.send(msg);
  22485. }
  22486. });
  22487. svr.set_address_family(AF_UNIX);
  22488. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22489. auto se = detail::scope_exit([&] {
  22490. svr.stop();
  22491. t.join();
  22492. std::remove(sock_path.c_str());
  22493. });
  22494. svr.wait_until_ready();
  22495. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22496. client.set_address_family(AF_UNIX);
  22497. ASSERT_TRUE(client.connect());
  22498. ASSERT_TRUE(client.send("hello"));
  22499. std::string msg;
  22500. ASSERT_TRUE(client.read(msg));
  22501. client.close();
  22502. {
  22503. std::lock_guard<std::mutex> lock(mtx);
  22504. // There is no host:port for a Unix socket, so the same "localhost"
  22505. // placeholder the HTTP client uses is expected.
  22506. EXPECT_EQ("localhost", received_host);
  22507. }
  22508. }
  22509. // Two threads must never parse WebSocket frames from the same stream.
  22510. // close() used to read the peer's Close reply with its own frame read, so it
  22511. // raced a reader thread that was in the middle of a payload: the payload loop
  22512. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22513. // so bytes taken by close() were replaced with bytes from further along the
  22514. // stream. The message kept its length and silently changed content.
  22515. //
  22516. // The raw peer below sends a frame header plus part of the payload, waits for
  22517. // the handler to call close(), and only then sends the rest. Whichever thread
  22518. // would win the race for those bytes, the message must arrive intact, because
  22519. // close() must not touch the stream while read() owns it.
  22520. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22521. #ifndef _WIN32
  22522. signal(SIGPIPE, SIG_IGN);
  22523. #endif
  22524. const size_t payload_len = 120; // fits the 7-bit length field
  22525. const size_t prefix_len = 8;
  22526. const int attempts = 8;
  22527. std::string expected(payload_len, '\0');
  22528. for (size_t i = 0; i < payload_len; i++) {
  22529. expected[i] = static_cast<char>('a' + i % 26);
  22530. }
  22531. std::atomic<bool> peer_stalled{false};
  22532. std::atomic<bool> handler_done{false};
  22533. std::mutex received_mutex;
  22534. std::vector<std::string> received;
  22535. // Bound every wait, so a regression fails the test instead of hanging the
  22536. // suite.
  22537. auto wait_for = [](const std::atomic<bool> &flag) {
  22538. for (int i = 0; i < 500 && !flag; i++) {
  22539. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22540. }
  22541. };
  22542. Server svr;
  22543. svr.set_websocket_ping_interval(0);
  22544. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22545. std::thread reader([&]() {
  22546. std::string msg;
  22547. while (ws.read(msg)) {
  22548. std::lock_guard<std::mutex> guard(received_mutex);
  22549. received.push_back(msg);
  22550. }
  22551. });
  22552. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22553. // inside read_websocket_frame() when close() runs.
  22554. wait_for(peer_stalled);
  22555. ws.close();
  22556. reader.join();
  22557. handler_done = true;
  22558. });
  22559. auto port = svr.bind_to_any_port("127.0.0.1");
  22560. std::thread t([&]() { svr.listen_after_bind(); });
  22561. auto se = detail::scope_exit([&] {
  22562. svr.stop();
  22563. t.join();
  22564. });
  22565. svr.wait_until_ready();
  22566. auto send_bytes = [](socket_t s, const std::string &data) {
  22567. #ifdef _WIN32
  22568. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22569. #else
  22570. auto n = ::send(s, data.data(), data.size(), 0);
  22571. #endif
  22572. return n == static_cast<decltype(n)>(data.size());
  22573. };
  22574. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22575. // Every length used here fits the 7-bit length field.
  22576. auto masked_header = [](uint8_t first_byte, size_t len) {
  22577. std::string h;
  22578. h += static_cast<char>(first_byte);
  22579. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22580. h.append(4, '\0'); // mask key
  22581. return h;
  22582. };
  22583. for (int attempt = 0; attempt < attempts; attempt++) {
  22584. peer_stalled = false;
  22585. handler_done = false;
  22586. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22587. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22588. auto se_sock = detail::scope_exit([&] {
  22589. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22590. });
  22591. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22592. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22593. sockaddr_in addr{};
  22594. addr.sin_family = AF_INET;
  22595. addr.sin_port = htons(static_cast<uint16_t>(port));
  22596. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22597. ASSERT_EQ(
  22598. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22599. << "attempt " << attempt;
  22600. ASSERT_TRUE(send_bytes(sock,
  22601. "GET /ws HTTP/1.1\r\n"
  22602. "Host: 127.0.0.1\r\n"
  22603. "Upgrade: websocket\r\n"
  22604. "Connection: Upgrade\r\n"
  22605. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22606. "Sec-WebSocket-Version: 13\r\n"
  22607. "\r\n"))
  22608. << "attempt " << attempt;
  22609. std::string response;
  22610. while (response.find("\r\n\r\n") == std::string::npos) {
  22611. char buf[512];
  22612. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22613. if (n <= 0) { break; }
  22614. response.append(buf, static_cast<size_t>(n));
  22615. }
  22616. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22617. << "attempt " << attempt;
  22618. // Send the header of a Binary message but only the first prefix_len bytes
  22619. // of its payload, leaving the reader thread stalled inside the payload.
  22620. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22621. expected.substr(0, prefix_len)))
  22622. << "attempt " << attempt;
  22623. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22624. peer_stalled = true;
  22625. // Let close() send its Close frame and park in its own read before the
  22626. // rest of the payload arrives, so both threads are waiting for it.
  22627. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22628. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22629. close_frame += static_cast<char>(0x03); // status 1000
  22630. close_frame += static_cast<char>(0xE8);
  22631. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22632. << "attempt " << attempt;
  22633. // Closing the peer releases the reader thread even on the buggy path,
  22634. // where it waits for bytes another thread already consumed.
  22635. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22636. detail::close_socket(sock);
  22637. sock = INVALID_SOCKET;
  22638. wait_for(handler_done);
  22639. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22640. }
  22641. std::lock_guard<std::mutex> guard(received_mutex);
  22642. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22643. << "a message in flight when close() ran was dropped";
  22644. for (size_t i = 0; i < received.size(); i++) {
  22645. EXPECT_EQ(expected, received[i]) << "message " << i;
  22646. }
  22647. }
  22648. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22649. // returning the socket, or INVALID_SOCKET.
  22650. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22651. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22652. if (sock == INVALID_SOCKET) { return sock; }
  22653. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22654. sockaddr_in addr{};
  22655. addr.sin_family = AF_INET;
  22656. addr.sin_port = htons(static_cast<uint16_t>(port));
  22657. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22658. std::string req = "GET " + path +
  22659. " HTTP/1.1\r\n"
  22660. "Host: 127.0.0.1\r\n"
  22661. "Upgrade: websocket\r\n"
  22662. "Connection: Upgrade\r\n"
  22663. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22664. "Sec-WebSocket-Version: 13\r\n"
  22665. "\r\n";
  22666. std::string res;
  22667. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22668. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22669. static_cast<int>(req.size())) {
  22670. char c;
  22671. while (res.find("\r\n\r\n") == std::string::npos &&
  22672. ::recv(sock, &c, 1, 0) == 1) {
  22673. res += c;
  22674. }
  22675. }
  22676. if (res.find(" 101 ") == std::string::npos) {
  22677. detail::close_socket(sock);
  22678. return INVALID_SOCKET;
  22679. }
  22680. return sock;
  22681. }
  22682. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22683. // The payload must fit the 7-bit length field.
  22684. static std::string masked_frame(uint8_t first_byte,
  22685. const std::string &payload) {
  22686. std::string f;
  22687. f += static_cast<char>(first_byte);
  22688. f += static_cast<char>(0x80 | payload.size());
  22689. f.append(4, '\0');
  22690. return f + payload;
  22691. }
  22692. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22693. std::atomic<bool> done{false};
  22694. std::string received;
  22695. Server svr;
  22696. svr.set_websocket_ping_interval(0);
  22697. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22698. std::string msg;
  22699. if (ws.read(msg) == ws::Binary) { received = msg; }
  22700. done = true;
  22701. });
  22702. auto port = svr.bind_to_any_port("127.0.0.1");
  22703. std::thread t([&]() { svr.listen_after_bind(); });
  22704. auto se = detail::scope_exit([&] {
  22705. svr.stop();
  22706. t.join();
  22707. });
  22708. svr.wait_until_ready();
  22709. auto sock = connect_raw_websocket(port, "/ws");
  22710. ASSERT_NE(INVALID_SOCKET, sock);
  22711. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22712. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22713. masked_frame(0x89, "p") + // FIN + Ping
  22714. masked_frame(0x80, "lo"); // FIN + Continuation
  22715. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22716. for (int i = 0; i < 500 && !done; i++) {
  22717. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22718. }
  22719. ASSERT_TRUE(done);
  22720. EXPECT_EQ("Hello", received);
  22721. }
  22722. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22723. Server svr;
  22724. svr.set_websocket_ping_interval(0);
  22725. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22726. std::string msg;
  22727. while (ws.read(msg)) {}
  22728. });
  22729. auto port = svr.bind_to_any_port("127.0.0.1");
  22730. std::thread t([&]() { svr.listen_after_bind(); });
  22731. auto se = detail::scope_exit([&] {
  22732. svr.stop();
  22733. t.join();
  22734. });
  22735. svr.wait_until_ready();
  22736. // Each Close payload and the reply it should get: an echo when valid, 1002
  22737. // otherwise.
  22738. std::vector<std::pair<std::string, std::string>> cases = {
  22739. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22740. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22741. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22742. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22743. };
  22744. for (const auto &c : cases) {
  22745. auto sock = connect_raw_websocket(port, "/ws");
  22746. ASSERT_NE(INVALID_SOCKET, sock);
  22747. auto close_frame = masked_frame(0x88, c.first);
  22748. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22749. std::string reply;
  22750. char buf[256];
  22751. while (reply.size() < 2 + c.second.size()) {
  22752. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22753. if (n <= 0) { break; }
  22754. reply.append(buf, static_cast<size_t>(n));
  22755. }
  22756. detail::close_socket(sock);
  22757. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22758. c.second,
  22759. reply);
  22760. }
  22761. }
  22762. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22763. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22764. protected:
  22765. void SetUp() override {
  22766. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22767. SERVER_PRIVATE_KEY_FILE);
  22768. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22769. std::string msg;
  22770. ws::ReadResult ret;
  22771. while ((ret = ws.read(msg))) {
  22772. if (ret == ws::Binary) {
  22773. ws.send(msg.data(), msg.size());
  22774. } else {
  22775. ws.send(msg);
  22776. }
  22777. }
  22778. });
  22779. port_ = server_->bind_to_any_port(HOST);
  22780. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22781. server_->wait_until_ready();
  22782. }
  22783. void TearDown() override {
  22784. server_->stop();
  22785. if (server_thread_.joinable()) { server_thread_.join(); }
  22786. }
  22787. std::unique_ptr<SSLServer> server_;
  22788. std::thread server_thread_;
  22789. int port_ = 0;
  22790. };
  22791. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  22792. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22793. {
  22794. ws::WebSocketClient client(url);
  22795. client.enable_server_certificate_verification(false);
  22796. auto calls = 0;
  22797. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  22798. calls++;
  22799. return false;
  22800. });
  22801. EXPECT_FALSE(client.connect());
  22802. EXPECT_GT(calls, 0);
  22803. }
  22804. {
  22805. ws::WebSocketClient client(url);
  22806. client.enable_server_certificate_verification(false);
  22807. client.set_session_verifier([](tls::session_t) {
  22808. return SSLVerifierResponse::CertificateRejected;
  22809. });
  22810. EXPECT_FALSE(client.connect());
  22811. }
  22812. {
  22813. ws::WebSocketClient client(url);
  22814. client.enable_server_certificate_verification(false);
  22815. client.set_session_verifier([](tls::session_t) {
  22816. return SSLVerifierResponse::CertificateAccepted;
  22817. });
  22818. EXPECT_TRUE(client.connect());
  22819. }
  22820. }
  22821. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22822. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22823. "/ws-echo");
  22824. client.enable_server_certificate_verification(false);
  22825. ASSERT_TRUE(client.connect());
  22826. ASSERT_TRUE(client.is_open());
  22827. ASSERT_TRUE(client.send("Hello WSS"));
  22828. std::string msg;
  22829. EXPECT_EQ(ws::Text, client.read(msg));
  22830. EXPECT_EQ("Hello WSS", msg);
  22831. client.close();
  22832. }
  22833. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22834. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22835. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22836. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22837. // client (without calling close() first) is the only path that runs
  22838. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22839. // bug exactly.
  22840. //
  22841. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22842. // when linked against an instrumented libssl; run under Valgrind to catch it
  22843. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22844. // suite (the freed session otherwise stalls on the close handshake) — this test
  22845. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22846. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22847. {
  22848. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22849. "/ws-echo");
  22850. client.enable_server_certificate_verification(false);
  22851. client.set_read_timeout(2, 0);
  22852. client.set_write_timeout(2, 0);
  22853. ASSERT_TRUE(client.connect());
  22854. ASSERT_TRUE(client.is_open());
  22855. ASSERT_TRUE(client.send("still open"));
  22856. // Intentionally do NOT call client.close(): leaving scope runs
  22857. // shutdown_and_close() with the WebSocket still open, which must send the
  22858. // close frame while the TLS session is still alive.
  22859. }
  22860. }
  22861. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22862. // shutdown_and_close() at the start of connect(), reproducing the same
  22863. // use-after-free within the test body rather than at scope exit. The second
  22864. // connect must succeed and echo, proving the close handshake ran over a live
  22865. // session. See the note above about memory-tool requirements.
  22866. TEST_F(WebSocketSSLIntegrationTest,
  22867. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22868. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22869. "/ws-echo");
  22870. client.enable_server_certificate_verification(false);
  22871. client.set_read_timeout(2, 0);
  22872. client.set_write_timeout(2, 0);
  22873. ASSERT_TRUE(client.connect());
  22874. ASSERT_TRUE(client.is_open());
  22875. ASSERT_TRUE(client.send("still open"));
  22876. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22877. // the still-open connection, which must not touch a freed TLS session.
  22878. ASSERT_TRUE(client.connect());
  22879. ASSERT_TRUE(client.is_open());
  22880. ASSERT_TRUE(client.send("after reconnect"));
  22881. std::string msg;
  22882. EXPECT_EQ(ws::Text, client.read(msg));
  22883. EXPECT_EQ("after reconnect", msg);
  22884. client.close();
  22885. }
  22886. #endif
  22887. #ifdef CPPHTTPLIB_SSL_ENABLED
  22888. class WebSocketSSLCATest : public ::testing::Test {
  22889. protected:
  22890. void SetUp() override {
  22891. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22892. SERVER_PRIVATE_KEY_FILE);
  22893. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22894. std::string msg;
  22895. while (ws.read(msg)) {
  22896. ws.send(msg);
  22897. }
  22898. });
  22899. port_ = server_->bind_to_any_port("127.0.0.1");
  22900. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22901. server_->wait_until_ready();
  22902. }
  22903. void TearDown() override {
  22904. server_->stop();
  22905. if (server_thread_.joinable()) { server_thread_.join(); }
  22906. }
  22907. std::string url() const {
  22908. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22909. }
  22910. std::unique_ptr<SSLServer> server_;
  22911. std::thread server_thread_;
  22912. int port_ = 0;
  22913. };
  22914. // A custom CA loaded as PEM verifies the server with full certificate
  22915. // verification enabled
  22916. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22917. ws::WebSocketClient client(url());
  22918. std::string cert;
  22919. read_file(SERVER_CERT2_FILE, cert);
  22920. client.load_ca_cert_store(cert.c_str(), cert.size());
  22921. ASSERT_TRUE(client.connect());
  22922. ASSERT_TRUE(client.send("hello"));
  22923. std::string msg;
  22924. EXPECT_EQ(ws::Text, client.read(msg));
  22925. EXPECT_EQ("hello", msg);
  22926. client.close();
  22927. }
  22928. // A custom CA that does not cover the server must fail verification (the
  22929. // custom CA is exclusive; system certs are not loaded alongside it)
  22930. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22931. ws::WebSocketClient client(url());
  22932. std::string cert;
  22933. read_file(CLIENT_CA_CERT_FILE, cert);
  22934. client.load_ca_cert_store(cert.c_str(), cert.size());
  22935. auto res = client.connect();
  22936. ASSERT_FALSE(res);
  22937. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22938. EXPECT_EQ(-1, res.status());
  22939. EXPECT_NE(0u, res.ssl_backend_error());
  22940. }
  22941. // The same CA as a file path rather than PEM in memory
  22942. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22943. ws::WebSocketClient client(url());
  22944. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22945. ASSERT_TRUE(client.connect());
  22946. ASSERT_TRUE(client.send("hello"));
  22947. std::string msg;
  22948. EXPECT_EQ(ws::Text, client.read(msg));
  22949. EXPECT_EQ("hello", msg);
  22950. client.close();
  22951. }
  22952. // ...and a CA file that does not cover the server still fails, so it is the
  22953. // path above that decides the outcome
  22954. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22955. ws::WebSocketClient client(url());
  22956. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22957. ASSERT_FALSE(client.connect());
  22958. }
  22959. // Regression test: reconnecting with a native custom CA store used to reuse
  22960. // a store handle the previous TLS context had already freed (use-after-free
  22961. // under the OpenSSL backend). The context now lives as long as the client.
  22962. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22963. ws::WebSocketClient client(url());
  22964. std::string cert;
  22965. read_file(SERVER_CERT2_FILE, cert);
  22966. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22967. ASSERT_TRUE(client.connect());
  22968. client.close();
  22969. ASSERT_TRUE(client.connect());
  22970. ASSERT_TRUE(client.send("again"));
  22971. std::string msg;
  22972. EXPECT_EQ(ws::Text, client.read(msg));
  22973. EXPECT_EQ("again", msg);
  22974. client.close();
  22975. }
  22976. // Regression test: a certificate with a trusted chain but no identity match
  22977. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22978. // verification entirely for IP hosts, so this connection succeeded there.
  22979. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22980. // chain verification while the identity check must still fail.
  22981. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22983. ASSERT_TRUE(svr.is_valid());
  22984. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22985. std::string msg;
  22986. while (ws.read(msg)) {
  22987. ws.send(msg);
  22988. }
  22989. });
  22990. auto port = svr.bind_to_any_port("127.0.0.1");
  22991. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22992. auto se = detail::scope_exit([&] {
  22993. svr.stop();
  22994. t.join();
  22995. });
  22996. svr.wait_until_ready();
  22997. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22998. "/echo");
  22999. std::string cert;
  23000. read_file(SERVER_CERT_FILE, cert);
  23001. client.load_ca_cert_store(cert.c_str(), cert.size());
  23002. ASSERT_FALSE(client.connect());
  23003. }
  23004. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23005. // SNI, so nothing binds the host name to the TLS session. These bind the
  23006. // server to "localhost" instead, the only shape that exercises the SNI and
  23007. // hostname-verification path with certificate verification left enabled.
  23008. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23009. protected:
  23010. void Start(const char *cert_file) {
  23011. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23012. SERVER_PRIVATE_KEY_FILE);
  23013. ASSERT_TRUE(server_->is_valid());
  23014. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23015. std::string msg;
  23016. while (ws.read(msg)) {
  23017. ws.send(msg);
  23018. }
  23019. });
  23020. port_ = server_->bind_to_any_port("localhost");
  23021. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23022. server_->wait_until_ready();
  23023. }
  23024. void TearDown() override {
  23025. if (server_) { server_->stop(); }
  23026. if (server_thread_.joinable()) { server_thread_.join(); }
  23027. }
  23028. std::string url() const {
  23029. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23030. }
  23031. std::unique_ptr<SSLServer> server_;
  23032. std::thread server_thread_;
  23033. int port_ = 0;
  23034. };
  23035. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23036. // out and the connection is usable
  23037. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23038. Start(SERVER_CERT2_FILE);
  23039. ws::WebSocketClient client(url());
  23040. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23041. ASSERT_TRUE(client.connect());
  23042. ASSERT_TRUE(client.send("hello"));
  23043. std::string msg;
  23044. EXPECT_EQ(ws::Text, client.read(msg));
  23045. EXPECT_EQ("hello", msg);
  23046. client.close();
  23047. }
  23048. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23049. // while the identity check must still reject "localhost"
  23050. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23051. Start(SERVER_CERT_FILE);
  23052. ws::WebSocketClient client(url());
  23053. client.set_ca_cert_path(SERVER_CERT_FILE);
  23054. auto res = client.connect();
  23055. ASSERT_FALSE(res);
  23056. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23057. EXPECT_EQ(-1, res.status());
  23058. }
  23059. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23060. // disabled: the chain is still checked, only the identity check is skipped
  23061. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23062. Start(SERVER_CERT_FILE);
  23063. ws::WebSocketClient client(url());
  23064. client.set_ca_cert_path(SERVER_CERT_FILE);
  23065. client.enable_server_hostname_verification(false);
  23066. ASSERT_TRUE(client.connect());
  23067. ASSERT_TRUE(client.send("hello"));
  23068. std::string msg;
  23069. EXPECT_EQ(ws::Text, client.read(msg));
  23070. EXPECT_EQ("hello", msg);
  23071. client.close();
  23072. }
  23073. // A CA that did not sign the server certificate fails the chain, even though
  23074. // the name would match
  23075. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23076. Start(SERVER_CERT2_FILE);
  23077. ws::WebSocketClient client(url());
  23078. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23079. ASSERT_FALSE(client.connect());
  23080. }
  23081. // With verification disabled, neither the chain nor the name is checked
  23082. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23083. Start(SERVER_CERT_FILE);
  23084. ws::WebSocketClient client(url());
  23085. client.enable_server_certificate_verification(false);
  23086. ASSERT_TRUE(client.connect());
  23087. ASSERT_TRUE(client.send("hello"));
  23088. std::string msg;
  23089. EXPECT_EQ(ws::Text, client.read(msg));
  23090. EXPECT_EQ("hello", msg);
  23091. client.close();
  23092. }
  23093. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23094. protected:
  23095. void SetUp() override {
  23096. server_ = httplib::detail::make_unique<SSLServer>(
  23097. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23098. ASSERT_TRUE(server_->is_valid());
  23099. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23100. std::string msg;
  23101. while (ws.read(msg)) {
  23102. ws.send(msg);
  23103. }
  23104. });
  23105. port_ = server_->bind_to_any_port("localhost");
  23106. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23107. server_->wait_until_ready();
  23108. }
  23109. void TearDown() override {
  23110. server_->stop();
  23111. if (server_thread_.joinable()) { server_thread_.join(); }
  23112. }
  23113. std::string url() const {
  23114. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23115. }
  23116. void ConnectWithClientCert(const std::string &client_cert_file,
  23117. const std::string &client_private_key_file,
  23118. const char *private_key_password) {
  23119. std::string cert_pem, key_pem;
  23120. read_file(client_cert_file, cert_pem);
  23121. read_file(client_private_key_file, key_pem);
  23122. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23123. key_pem.c_str(), key_pem.size(),
  23124. private_key_password};
  23125. ws::WebSocketClient client(url(), pem);
  23126. ASSERT_TRUE(client.is_valid());
  23127. client.enable_server_certificate_verification(false);
  23128. ASSERT_TRUE(client.connect());
  23129. ASSERT_TRUE(client.send("hello"));
  23130. std::string msg;
  23131. EXPECT_EQ(ws::Text, client.read(msg));
  23132. EXPECT_EQ("hello", msg);
  23133. client.close();
  23134. }
  23135. std::unique_ptr<SSLServer> server_;
  23136. std::thread server_thread_;
  23137. int port_ = 0;
  23138. };
  23139. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23140. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23141. }
  23142. // Control for the tests above: the fixture's server really does require a
  23143. // client certificate, so it is the PEM the constructor installed that decides
  23144. // the outcome.
  23145. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23146. ws::WebSocketClient client(url());
  23147. ASSERT_TRUE(client.is_valid());
  23148. client.enable_server_certificate_verification(false);
  23149. EXPECT_FALSE(client.connect());
  23150. }
  23151. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23152. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23153. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23154. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23155. }
  23156. #endif
  23157. #if !defined(_WIN32)
  23158. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23159. auto secret_dir = std::string("./symlink_test_secret");
  23160. auto served_dir = std::string("./symlink_test_served");
  23161. auto secret_file = secret_dir + "/secret.txt";
  23162. auto symlink_path = served_dir + "/escape";
  23163. // Setup: create directories and files
  23164. mkdir(secret_dir.c_str(), 0755);
  23165. mkdir(served_dir.c_str(), 0755);
  23166. {
  23167. std::ofstream ofs(secret_file);
  23168. ofs << "SECRET_DATA";
  23169. }
  23170. // Create symlink using absolute path so it resolves correctly
  23171. #ifdef PATH_MAX
  23172. char abs_secret[PATH_MAX];
  23173. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23174. #else
  23175. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23176. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23177. ASSERT_NE(nullptr, abs_secret);
  23178. #endif
  23179. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23180. auto se = detail::scope_exit([&] {
  23181. unlink(symlink_path.c_str());
  23182. unlink(secret_file.c_str());
  23183. rmdir(served_dir.c_str());
  23184. rmdir(secret_dir.c_str());
  23185. });
  23186. Server svr;
  23187. svr.set_mount_point("/", served_dir);
  23188. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23189. auto se2 = detail::scope_exit([&] {
  23190. svr.stop();
  23191. listen_thread.join();
  23192. });
  23193. svr.wait_until_ready();
  23194. Client cli("localhost", PORT);
  23195. // Symlink pointing outside base dir should be blocked
  23196. auto res = cli.Get("/escape/secret.txt");
  23197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23198. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23199. }
  23200. #endif
  23201. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23202. // "GET /smuggled" request), reads the first response, and only then sends the
  23203. // embedded request as the body. Returns how many times /smuggled ran.
  23204. //
  23205. // The body is sent AFTER receiving the first response (as in the original
  23206. // PoC) so that the stream_line_reader cannot buffer it together with the
  23207. // headers of the first request.
  23208. static int count_smuggled_requests(const std::string &outer_head,
  23209. std::string &first_response) {
  23210. Server svr;
  23211. svr.set_mount_point("/", "./www");
  23212. std::atomic<int> smuggled_count(0);
  23213. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23214. smuggled_count++;
  23215. res.set_content("oops", "text/plain");
  23216. });
  23217. svr.Post("/post", [&](const Request &req, Response &res) {
  23218. res.set_content(req.body, "text/plain");
  23219. });
  23220. auto port = svr.bind_to_any_port("localhost");
  23221. thread t = thread([&] { svr.listen_after_bind(); });
  23222. auto se = detail::scope_exit([&] {
  23223. svr.stop();
  23224. t.join();
  23225. });
  23226. svr.wait_until_ready();
  23227. auto error = Error::Success;
  23228. auto sock = detail::create_client_socket(
  23229. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23230. /*connection_timeout_sec=*/2, 0,
  23231. /*read_timeout_sec=*/2, 0,
  23232. /*write_timeout_sec=*/2, 0, std::string(), error);
  23233. EXPECT_NE(INVALID_SOCKET, sock);
  23234. if (sock == INVALID_SOCKET) { return -1; }
  23235. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23236. // The "smuggled" request will be sent as the body of the outer request
  23237. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23238. "Host: localhost\r\n"
  23239. "Connection: close\r\n"
  23240. "\r\n";
  23241. auto head = outer_head;
  23242. auto len = std::to_string(smuggled.size());
  23243. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23244. pos = head.find("{len}", pos + len.size())) {
  23245. head.replace(pos, 5, len);
  23246. }
  23247. // Step 1: Send only the outer request headers (no body yet)
  23248. auto sent = send(sock, head.data(), head.size(), 0);
  23249. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23250. // Step 2: Read the first response
  23251. char buf[4096];
  23252. for (;;) {
  23253. auto n = recv(sock, buf, sizeof(buf), 0);
  23254. if (n <= 0) break;
  23255. first_response.append(buf, static_cast<size_t>(n));
  23256. // Stop once we have a complete response (headers + body)
  23257. auto hdr_end = first_response.find("\r\n\r\n");
  23258. if (hdr_end != std::string::npos) {
  23259. // Check for Content-Length to know when the body is complete
  23260. auto cl_pos = first_response.find("Content-Length:");
  23261. if (cl_pos != std::string::npos) {
  23262. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23263. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23264. auto cl = std::stoul(
  23265. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23266. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23267. } else {
  23268. break; // No Content-Length, assume headers-only response
  23269. }
  23270. }
  23271. }
  23272. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23273. // vulnerable server the keep-alive loop reads this as a second request. The
  23274. // server may already have closed the connection, so the result is ignored.
  23275. send(sock, smuggled.data(), smuggled.size(), 0);
  23276. // Half-close so that a server which drained the body sees EOF and closes,
  23277. // instead of the read below waiting for the read timeout.
  23278. #ifdef _WIN32
  23279. ::shutdown(sock, SD_SEND);
  23280. #else
  23281. ::shutdown(sock, SHUT_WR);
  23282. #endif
  23283. // Step 4: Read until the server closes the connection
  23284. for (;;) {
  23285. auto n = recv(sock, buf, sizeof(buf), 0);
  23286. if (n <= 0) break;
  23287. }
  23288. return smuggled_count.load();
  23289. }
  23290. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23291. // A GET request with Content-Length to a static file handler must have its
  23292. // body drained before the keep-alive connection is reused. Otherwise the
  23293. // unread body bytes are interpreted as the next HTTP request.
  23294. std::string first_response;
  23295. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23296. "Host: localhost\r\n"
  23297. "Content-Length: {len}\r\n"
  23298. "\r\n",
  23299. first_response));
  23300. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23301. }
  23302. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23303. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23304. // be answered with 400 and the connection closed. Treating it as "no body"
  23305. // leaves the body to be parsed as the next request.
  23306. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23307. const char *targets[] = {
  23308. "GET /file", // handler that never reads the body
  23309. "GET /not-found", // no handler matches (404)
  23310. "POST /post", // handler that reads the body
  23311. };
  23312. for (auto target : targets) {
  23313. for (auto value : values) {
  23314. std::string first_response;
  23315. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23316. " HTTP/1.1\r\n"
  23317. "Host: localhost\r\n"
  23318. "Content-Length: " +
  23319. value + "\r\n\r\n",
  23320. first_response))
  23321. << target << " with Content-Length: " << value;
  23322. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23323. << target << " with Content-Length: " << value;
  23324. }
  23325. }
  23326. }
  23327. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23328. // A 400 for an unparseable request line leaves the rest of the message
  23329. // unread, so the connection must be closed rather than reused.
  23330. std::string first_response;
  23331. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23332. "Host: localhost\r\n"
  23333. "Content-Length: {len}\r\n"
  23334. "\r\n",
  23335. first_response));
  23336. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23337. }
  23338. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23339. // Same as above for a header block that fails to parse.
  23340. std::string first_response;
  23341. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23342. "Host: localhost\r\n"
  23343. "Bad Header\r\n"
  23344. "Content-Length: {len}\r\n"
  23345. "\r\n",
  23346. first_response));
  23347. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23348. }
  23349. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23350. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23351. // server must not read another request on that connection, even when the
  23352. // request had no body to drain.
  23353. std::string first_response;
  23354. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23355. "Host: localhost\r\n"
  23356. "\r\n",
  23357. first_response));
  23358. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23359. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23360. }
  23361. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23362. // A content reader that stops early leaves the stream inside the body.
  23363. // Draining the whole Content-Length from there, or reading the body again,
  23364. // reads into the next request, and whatever follows is parsed as a request
  23365. // of its own.
  23366. Server svr;
  23367. std::atomic<int> smuggled_count(0);
  23368. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23369. svr.Post("/upload", [](const Request &req, Response &res,
  23370. const ContentReader &content_reader) {
  23371. // Stop at the last chunk, so the whole body has been read however it
  23372. // arrives.
  23373. auto length = req.get_header_value_u64("Content-Length");
  23374. size_t total = 0;
  23375. auto consumed = content_reader([&](const char *, size_t n) {
  23376. total += n;
  23377. return total < length;
  23378. });
  23379. EXPECT_FALSE(consumed);
  23380. if (req.has_param("retry")) {
  23381. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23382. }
  23383. // Replace the 400 the aborted read set, which would close the connection.
  23384. res.set_redirect("/done");
  23385. });
  23386. auto port = svr.bind_to_any_port(HOST);
  23387. thread t = thread([&] { svr.listen_after_bind(); });
  23388. auto se = detail::scope_exit([&] {
  23389. svr.stop();
  23390. t.join();
  23391. });
  23392. svr.wait_until_ready();
  23393. // A front end sees the second request as a POST whose body is the GET. The
  23394. // first body is as long as the POST's headers, so draining it again reads
  23395. // exactly those and leaves the GET to be parsed next.
  23396. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23397. "Host: localhost\r\n"
  23398. "\r\n";
  23399. std::string second_head = "POST /post HTTP/1.1\r\n"
  23400. "Host: localhost\r\n"
  23401. "Content-Length: " +
  23402. std::to_string(inner.size()) +
  23403. "\r\n"
  23404. "\r\n";
  23405. for (auto target : {"/upload", "/upload?retry"}) {
  23406. smuggled_count = 0;
  23407. std::string request = "POST " + std::string(target) +
  23408. " HTTP/1.1\r\n"
  23409. "Host: localhost\r\n"
  23410. "Content-Length: " +
  23411. std::to_string(second_head.size()) +
  23412. "\r\n"
  23413. "\r\n" +
  23414. std::string(second_head.size(), 'A') + second_head +
  23415. inner;
  23416. std::string response;
  23417. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23418. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23419. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23420. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23421. EXPECT_EQ(0, smuggled_count.load()) << target;
  23422. }
  23423. }
  23424. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23425. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23426. // must be rejected with 400 Bad Request.
  23427. Server svr;
  23428. svr.Post("/test", [&](const Request &, Response &res) {
  23429. res.set_content("ok", "text/plain");
  23430. });
  23431. thread t = thread([&] { svr.listen(HOST, PORT); });
  23432. auto se = detail::scope_exit([&] {
  23433. svr.stop();
  23434. t.join();
  23435. ASSERT_FALSE(svr.is_running());
  23436. });
  23437. svr.wait_until_ready();
  23438. // Exact "chunked"
  23439. {
  23440. auto req = "POST /test HTTP/1.1\r\n"
  23441. "Host: localhost\r\n"
  23442. "Content-Length: 5\r\n"
  23443. "Transfer-Encoding: chunked\r\n"
  23444. "Connection: close\r\n"
  23445. "\r\n"
  23446. "hello";
  23447. std::string response;
  23448. ASSERT_TRUE(send_request(1, req, &response));
  23449. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23450. response.substr(0, response.find("\r\n")));
  23451. }
  23452. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23453. {
  23454. auto req = "POST /test HTTP/1.1\r\n"
  23455. "Host: localhost\r\n"
  23456. "Content-Length: 5\r\n"
  23457. "Transfer-Encoding: gzip, chunked\r\n"
  23458. "Connection: close\r\n"
  23459. "\r\n"
  23460. "hello";
  23461. std::string response;
  23462. ASSERT_TRUE(send_request(1, req, &response));
  23463. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23464. response.substr(0, response.find("\r\n")));
  23465. }
  23466. }
  23467. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23468. Server svr;
  23469. svr.Post("/test", [&](const Request &, Response &res) {
  23470. res.set_content("ok", "text/plain");
  23471. });
  23472. thread t = thread([&] { svr.listen(HOST, PORT); });
  23473. auto se = detail::scope_exit([&] {
  23474. svr.stop();
  23475. t.join();
  23476. ASSERT_FALSE(svr.is_running());
  23477. });
  23478. svr.wait_until_ready();
  23479. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23480. // length cannot be determined, so the server must answer 400 and close
  23481. // rather than treat the request as bodyless and leave the body in the
  23482. // socket for the next request to pick up.
  23483. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23484. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23485. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23486. std::string response;
  23487. ASSERT_TRUE(send_request(1, req, &response));
  23488. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23489. response.substr(0, response.find("\r\n")))
  23490. << transfer_encoding;
  23491. }
  23492. // RFC 9110 5.3: the codings may also be split across several
  23493. // Transfer-Encoding lines, which combine in the order they were received.
  23494. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23495. // just like the single-line "chunked, gzip" above.
  23496. {
  23497. auto req = "POST /test HTTP/1.1\r\n"
  23498. "Host: localhost\r\n"
  23499. "Transfer-Encoding: chunked\r\n"
  23500. "Transfer-Encoding: gzip\r\n"
  23501. "\r\n"
  23502. "0\r\n\r\n";
  23503. std::string response;
  23504. ASSERT_TRUE(send_request(1, req, &response));
  23505. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23506. response.substr(0, response.find("\r\n")));
  23507. }
  23508. // A sequence ending in chunked stays valid.
  23509. auto req = "POST /test HTTP/1.1\r\n"
  23510. "Host: localhost\r\n"
  23511. "Transfer-Encoding: gzip, chunked\r\n"
  23512. "Connection: close\r\n"
  23513. "\r\n"
  23514. "0\r\n\r\n";
  23515. std::string response;
  23516. ASSERT_TRUE(send_request(1, req, &response));
  23517. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23518. // ...including when it is spread over several lines.
  23519. auto split_req = "POST /test HTTP/1.1\r\n"
  23520. "Host: localhost\r\n"
  23521. "Transfer-Encoding: gzip\r\n"
  23522. "Transfer-Encoding: chunked\r\n"
  23523. "Connection: close\r\n"
  23524. "\r\n"
  23525. "0\r\n\r\n";
  23526. std::string split_response;
  23527. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23528. EXPECT_EQ("HTTP/1.1 200 OK",
  23529. split_response.substr(0, split_response.find("\r\n")));
  23530. }
  23531. // Regression for issue #2450: a DELETE without Content-Length on a
  23532. // keep-alive connection must not let the post-response drain consume the
  23533. // next request's bytes.
  23534. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23535. Server svr;
  23536. std::atomic<int> delete_count(0);
  23537. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23538. delete_count++;
  23539. res.status = StatusCode::NoContent_204;
  23540. });
  23541. auto port = svr.bind_to_any_port(HOST);
  23542. thread t = thread([&] { svr.listen_after_bind(); });
  23543. auto se = detail::scope_exit([&] {
  23544. svr.stop();
  23545. t.join();
  23546. });
  23547. svr.wait_until_ready();
  23548. auto error = Error::Success;
  23549. auto sock = detail::create_client_socket(
  23550. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23551. /*connection_timeout_sec=*/2, 0,
  23552. /*read_timeout_sec=*/2, 0,
  23553. /*write_timeout_sec=*/2, 0, std::string(), error);
  23554. ASSERT_NE(INVALID_SOCKET, sock);
  23555. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23556. auto send_request_and_read_response = [&](const std::string &req,
  23557. std::string &out) -> bool {
  23558. auto sent = send(sock, req.data(), req.size(), 0);
  23559. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23560. char buf[4096];
  23561. for (;;) {
  23562. auto n = recv(sock, buf, sizeof(buf), 0);
  23563. if (n <= 0) { return !out.empty(); }
  23564. out.append(buf, static_cast<size_t>(n));
  23565. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23566. }
  23567. };
  23568. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23569. "Host: localhost\r\n"
  23570. "\r\n";
  23571. std::string resp1;
  23572. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23573. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23574. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23575. "Host: localhost\r\n"
  23576. "Connection: close\r\n"
  23577. "\r\n";
  23578. std::string resp2;
  23579. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23580. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23581. EXPECT_EQ(2, delete_count.load());
  23582. }
  23583. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23584. Server svr;
  23585. svr.Post("/ingest", [&](const Request &, Response &res,
  23586. const ContentReader &content_reader) {
  23587. auto consumed = content_reader([](const char *, size_t) { return false; });
  23588. EXPECT_FALSE(consumed);
  23589. res.status = StatusCode::Conflict_409;
  23590. res.set_header("Connection", "close");
  23591. });
  23592. auto port = svr.bind_to_any_port(HOST);
  23593. thread t = thread([&] { svr.listen_after_bind(); });
  23594. auto se = detail::scope_exit([&] {
  23595. svr.stop();
  23596. t.join();
  23597. });
  23598. svr.wait_until_ready();
  23599. auto error = Error::Success;
  23600. auto sock = detail::create_client_socket(
  23601. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23602. /*connection_timeout_sec=*/2, 0,
  23603. /*read_timeout_sec=*/1, 0,
  23604. /*write_timeout_sec=*/2, 0, std::string(), error);
  23605. ASSERT_NE(INVALID_SOCKET, sock);
  23606. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23607. std::string request = "POST /ingest HTTP/1.1\r\n"
  23608. "Host: localhost\r\n"
  23609. "Transfer-Encoding: chunked\r\n"
  23610. "\r\n"
  23611. "4\r\n"
  23612. "data\r\n";
  23613. auto sent = send(sock, request.data(), request.size(), 0);
  23614. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23615. std::string response;
  23616. ssize_t received = 0;
  23617. do {
  23618. char buf[4096];
  23619. received = recv(sock, buf, sizeof(buf), 0);
  23620. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23621. } while (received > 0);
  23622. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23623. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23624. EXPECT_EQ(0, received);
  23625. }
  23626. namespace no_proxy_test {
  23627. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23628. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23629. // calling listen().
  23630. class ScopedServer {
  23631. public:
  23632. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23633. ~ScopedServer() {
  23634. svr_.stop();
  23635. if (th_.joinable()) { th_.join(); }
  23636. }
  23637. Server &svr() { return svr_; }
  23638. int port() const { return port_; }
  23639. void listen() {
  23640. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23641. svr_.wait_until_ready();
  23642. }
  23643. private:
  23644. Server svr_;
  23645. std::thread th_;
  23646. int port_ = 0;
  23647. };
  23648. class ProxyAndTargetServers {
  23649. public:
  23650. ProxyAndTargetServers() {
  23651. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23652. proxy_hits_++;
  23653. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23654. res.set_content("via-proxy", "text/plain");
  23655. });
  23656. target_.Get(".*", [this](const Request &req, Response &res) {
  23657. target_hits_++;
  23658. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23659. res.set_content("direct", "text/plain");
  23660. });
  23661. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23662. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23663. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23664. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23665. proxy_mock_.wait_until_ready();
  23666. target_.wait_until_ready();
  23667. }
  23668. ~ProxyAndTargetServers() {
  23669. proxy_mock_.stop();
  23670. target_.stop();
  23671. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23672. if (target_thread_.joinable()) { target_thread_.join(); }
  23673. }
  23674. Server &proxy_mock() { return proxy_mock_; }
  23675. Server &target() { return target_; }
  23676. int proxy_port() const { return proxy_port_; }
  23677. int target_port() const { return target_port_; }
  23678. int proxy_hits() const { return proxy_hits_.load(); }
  23679. int target_hits() const { return target_hits_.load(); }
  23680. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23681. void reset_counters() {
  23682. proxy_hits_ = 0;
  23683. target_hits_ = 0;
  23684. last_had_proxy_authz_ = false;
  23685. }
  23686. private:
  23687. Server proxy_mock_;
  23688. Server target_;
  23689. std::thread proxy_thread_;
  23690. std::thread target_thread_;
  23691. int proxy_port_ = 0;
  23692. int target_port_ = 0;
  23693. std::atomic<int> proxy_hits_{0};
  23694. std::atomic<int> target_hits_{0};
  23695. std::atomic<bool> last_had_proxy_authz_{false};
  23696. };
  23697. inline std::unique_ptr<Client> make_client(const std::string &host,
  23698. ProxyAndTargetServers &s) {
  23699. auto cli = detail::make_unique<Client>(host, s.target_port());
  23700. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23701. cli->set_proxy("127.0.0.1", s.proxy_port());
  23702. return cli;
  23703. }
  23704. } // namespace no_proxy_test
  23705. using no_proxy_test::make_client;
  23706. using no_proxy_test::ProxyAndTargetServers;
  23707. TEST(NoProxyTest, ExactHostnameBypasses) {
  23708. ProxyAndTargetServers s;
  23709. auto cli = make_client("example.com", s);
  23710. cli->set_no_proxy({"example.com"});
  23711. auto res = cli->Get("/");
  23712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23713. EXPECT_EQ(0, s.proxy_hits());
  23714. EXPECT_EQ(1, s.target_hits());
  23715. }
  23716. TEST(NoProxyTest, SubdomainBypasses) {
  23717. ProxyAndTargetServers s;
  23718. auto cli = make_client("foo.example.com", s);
  23719. cli->set_no_proxy({"example.com"});
  23720. auto res = cli->Get("/");
  23721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23722. EXPECT_EQ(0, s.proxy_hits());
  23723. EXPECT_EQ(1, s.target_hits());
  23724. }
  23725. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23726. // Regression guard: "evilexample.com" must not be considered a subdomain
  23727. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23728. // check would let traffic bypass the proxy and leak credentials direct
  23729. // to the attacker host.
  23730. ProxyAndTargetServers s;
  23731. auto cli = make_client("evilexample.com", s);
  23732. cli->set_no_proxy({"example.com"});
  23733. auto res = cli->Get("/");
  23734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23735. EXPECT_GE(s.proxy_hits(), 1);
  23736. EXPECT_EQ(0, s.target_hits());
  23737. }
  23738. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23739. ProxyAndTargetServers s;
  23740. auto cli = make_client("example.com.evil.com", s);
  23741. cli->set_no_proxy({"example.com"});
  23742. auto res = cli->Get("/");
  23743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23744. EXPECT_GE(s.proxy_hits(), 1);
  23745. EXPECT_EQ(0, s.target_hits());
  23746. }
  23747. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23748. ProxyAndTargetServers s;
  23749. auto cli = make_client("example.com", s);
  23750. cli->set_no_proxy({".example.com"});
  23751. auto res = cli->Get("/");
  23752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23753. EXPECT_EQ(0, s.proxy_hits());
  23754. EXPECT_EQ(1, s.target_hits());
  23755. }
  23756. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23757. ProxyAndTargetServers s;
  23758. auto cli = make_client("Example.COM", s);
  23759. cli->set_no_proxy({"EXAMPLE.com"});
  23760. auto res = cli->Get("/");
  23761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23762. EXPECT_EQ(0, s.proxy_hits());
  23763. EXPECT_EQ(1, s.target_hits());
  23764. }
  23765. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23766. ProxyAndTargetServers s;
  23767. auto cli = make_client("example.com.", s);
  23768. cli->set_no_proxy({"example.com"});
  23769. auto res = cli->Get("/");
  23770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23771. EXPECT_EQ(0, s.proxy_hits());
  23772. EXPECT_EQ(1, s.target_hits());
  23773. }
  23774. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23775. // Trailing dots must be normalized on BOTH sides — host and entry.
  23776. // An implementation that only strips the host-side trailing dot would
  23777. // fail to match host "example.com" against entry "example.com." because
  23778. // a literal substring search would compare 11 chars against 12.
  23779. ProxyAndTargetServers s;
  23780. auto cli = make_client("example.com", s);
  23781. cli->set_no_proxy({"example.com."});
  23782. auto res = cli->Get("/");
  23783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23784. EXPECT_EQ(0, s.proxy_hits());
  23785. EXPECT_EQ(1, s.target_hits());
  23786. }
  23787. TEST(NoProxyTest, WildcardBypassesEverything) {
  23788. ProxyAndTargetServers s;
  23789. auto cli = make_client("anything.invalid.test", s);
  23790. cli->set_no_proxy({"*"});
  23791. auto res = cli->Get("/");
  23792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23793. EXPECT_EQ(0, s.proxy_hits());
  23794. EXPECT_EQ(1, s.target_hits());
  23795. }
  23796. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23797. ProxyAndTargetServers s;
  23798. Client cli("127.0.0.1", s.target_port());
  23799. cli.set_proxy("127.0.0.1", s.proxy_port());
  23800. cli.set_no_proxy({"127.0.0.1"});
  23801. auto res = cli.Get("/");
  23802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23803. EXPECT_EQ(0, s.proxy_hits());
  23804. EXPECT_EQ(1, s.target_hits());
  23805. }
  23806. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23807. ProxyAndTargetServers s;
  23808. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23809. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23810. cli.set_proxy("127.0.0.1", s.proxy_port());
  23811. cli.set_no_proxy({"::1"});
  23812. auto res = cli.Get("/");
  23813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23814. EXPECT_EQ(0, s.proxy_hits());
  23815. EXPECT_EQ(1, s.target_hits());
  23816. }
  23817. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23818. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23819. // must still be recognized as IPv6 for CIDR matching. Implementations
  23820. // that detect IPv6 only when the host begins with '[' would parse the
  23821. // host as a hostname and miss the match.
  23822. ProxyAndTargetServers s;
  23823. Client cli("fe80::1", s.target_port());
  23824. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23825. cli.set_proxy("127.0.0.1", s.proxy_port());
  23826. cli.set_no_proxy({"fe80::/10"});
  23827. auto res = cli.Get("/");
  23828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23829. EXPECT_EQ(0, s.proxy_hits());
  23830. EXPECT_EQ(1, s.target_hits());
  23831. }
  23832. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23833. ProxyAndTargetServers s;
  23834. Client cli("::1", s.target_port());
  23835. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23836. cli.set_proxy("127.0.0.1", s.proxy_port());
  23837. cli.set_no_proxy({"[::1]"});
  23838. auto res = cli.Get("/");
  23839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23840. EXPECT_EQ(0, s.proxy_hits());
  23841. EXPECT_EQ(1, s.target_hits());
  23842. }
  23843. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23844. ProxyAndTargetServers s;
  23845. Client cli("fe80::1", s.target_port());
  23846. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23847. cli.set_proxy("127.0.0.1", s.proxy_port());
  23848. cli.set_no_proxy({"[fe80::]/10"});
  23849. auto res = cli.Get("/");
  23850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23851. EXPECT_EQ(0, s.proxy_hits());
  23852. EXPECT_EQ(1, s.target_hits());
  23853. }
  23854. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23855. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23856. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23857. // tricks via address-family conversion.
  23858. ProxyAndTargetServers s;
  23859. Client cli("::ffff:127.0.0.1", s.target_port());
  23860. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23861. cli.set_proxy("127.0.0.1", s.proxy_port());
  23862. cli.set_no_proxy({"127.0.0.1"});
  23863. auto res = cli.Get("/");
  23864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23865. EXPECT_GE(s.proxy_hits(), 1);
  23866. EXPECT_EQ(0, s.target_hits());
  23867. }
  23868. TEST(NoProxyTest, IPv4CidrMatch) {
  23869. ProxyAndTargetServers s;
  23870. Client cli("127.0.0.1", s.target_port());
  23871. cli.set_proxy("127.0.0.1", s.proxy_port());
  23872. cli.set_no_proxy({"127.0.0.0/8"});
  23873. auto res = cli.Get("/");
  23874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23875. EXPECT_EQ(0, s.proxy_hits());
  23876. EXPECT_EQ(1, s.target_hits());
  23877. }
  23878. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23879. ProxyAndTargetServers s;
  23880. Client cli("127.0.0.1", s.target_port());
  23881. cli.set_proxy("127.0.0.1", s.proxy_port());
  23882. cli.set_no_proxy({"10.0.0.0/8"});
  23883. auto res = cli.Get("/");
  23884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23885. EXPECT_GE(s.proxy_hits(), 1);
  23886. EXPECT_EQ(0, s.target_hits());
  23887. }
  23888. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23889. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23890. // IPv4 target matches.
  23891. ProxyAndTargetServers s;
  23892. Client cli("127.0.0.1", s.target_port());
  23893. cli.set_proxy("127.0.0.1", s.proxy_port());
  23894. cli.set_no_proxy({"0.0.0.0/0"});
  23895. auto res = cli.Get("/");
  23896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23897. EXPECT_EQ(0, s.proxy_hits());
  23898. EXPECT_EQ(1, s.target_hits());
  23899. }
  23900. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23901. ProxyAndTargetServers s;
  23902. Client cli("127.0.0.1", s.target_port());
  23903. cli.set_proxy("127.0.0.1", s.proxy_port());
  23904. cli.set_no_proxy({"127.0.0.1"});
  23905. auto res = cli.Get("/");
  23906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23907. EXPECT_EQ(0, s.proxy_hits());
  23908. EXPECT_EQ(1, s.target_hits());
  23909. }
  23910. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23911. ProxyAndTargetServers s;
  23912. Client cli("127.0.0.1", s.target_port());
  23913. cli.set_proxy("127.0.0.1", s.proxy_port());
  23914. cli.set_no_proxy({"127.0.0.0/33"});
  23915. auto res = cli.Get("/");
  23916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23917. EXPECT_GE(s.proxy_hits(), 1);
  23918. EXPECT_EQ(0, s.target_hits());
  23919. }
  23920. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23921. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23922. ProxyAndTargetServers s;
  23923. Client cli("127.0.0.1", s.target_port());
  23924. cli.set_proxy("127.0.0.1", s.proxy_port());
  23925. cli.set_no_proxy({"127.0.0.1/"});
  23926. auto res = cli.Get("/");
  23927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23928. EXPECT_GE(s.proxy_hits(), 1);
  23929. EXPECT_EQ(0, s.target_hits());
  23930. }
  23931. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23932. ProxyAndTargetServers s;
  23933. auto cli = make_client("internal.corp", s);
  23934. cli->set_proxy_basic_auth("u", "p");
  23935. cli->set_no_proxy({"internal.corp"});
  23936. auto res = cli->Get("/");
  23937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23938. EXPECT_EQ(1, s.target_hits());
  23939. EXPECT_EQ(0, s.proxy_hits());
  23940. EXPECT_FALSE(s.last_had_proxy_authz())
  23941. << "Proxy-Authorization must not be sent direct to the target";
  23942. }
  23943. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23944. ProxyAndTargetServers s;
  23945. auto cli = make_client("public.example", s);
  23946. cli->set_proxy_basic_auth("u", "p");
  23947. cli->set_no_proxy({"internal.corp"}); // does not match
  23948. auto res = cli->Get("/");
  23949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23950. EXPECT_GE(s.proxy_hits(), 1);
  23951. EXPECT_TRUE(s.last_had_proxy_authz());
  23952. }
  23953. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23954. std::atomic<int> hits{0};
  23955. std::atomic<int> hits_with_authz{0};
  23956. no_proxy_test::ScopedServer proxy_mock;
  23957. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23958. hits++;
  23959. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23960. if (req.target.find("/redir") != std::string::npos) {
  23961. res.set_redirect("http://other.example/landed");
  23962. } else {
  23963. res.set_content("via-proxy", "text/plain");
  23964. }
  23965. });
  23966. proxy_mock.listen();
  23967. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23968. hits = 0;
  23969. hits_with_authz = 0;
  23970. Client cli("public.example", 80);
  23971. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23972. cli.set_proxy_basic_auth(c.first, c.second);
  23973. cli.set_follow_location(true);
  23974. // The redirect to another host goes through the proxy as well
  23975. auto res = cli.Get("/redir");
  23976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23977. EXPECT_EQ(2, hits.load());
  23978. EXPECT_EQ(2, hits_with_authz.load());
  23979. }
  23980. }
  23981. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23982. ProxyAndTargetServers s;
  23983. auto cli = make_client("anything.test", s);
  23984. auto res = cli->Get("/");
  23985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23986. EXPECT_GE(s.proxy_hits(), 1);
  23987. EXPECT_EQ(0, s.target_hits());
  23988. }
  23989. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23990. ProxyAndTargetServers s;
  23991. auto cli = make_client("example.com", s);
  23992. cli->set_no_proxy({"example.com:8080"});
  23993. auto res = cli->Get("/");
  23994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23995. EXPECT_GE(s.proxy_hits(), 1);
  23996. EXPECT_EQ(0, s.target_hits());
  23997. }
  23998. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23999. ProxyAndTargetServers s;
  24000. auto cli = make_client("anything.test", s);
  24001. cli->set_no_proxy({"", " ", "\t"});
  24002. auto res = cli->Get("/");
  24003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24004. EXPECT_GE(s.proxy_hits(), 1);
  24005. EXPECT_EQ(0, s.target_hits());
  24006. }
  24007. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24008. // An entry with leading/trailing whitespace must still match — env-style
  24009. // values are commonly pasted with stray spaces and an implementation
  24010. // that feeds the raw token directly to inet_pton would fail to match
  24011. // valid CIDRs because of the spaces.
  24012. ProxyAndTargetServers s;
  24013. Client cli("127.0.0.1", s.target_port());
  24014. cli.set_proxy("127.0.0.1", s.proxy_port());
  24015. cli.set_no_proxy({" 127.0.0.0/8 "});
  24016. auto res = cli.Get("/");
  24017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24018. EXPECT_EQ(0, s.proxy_hits());
  24019. EXPECT_EQ(1, s.target_hits());
  24020. }
  24021. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24022. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24023. // go direct and must NOT carry Proxy-Authorization.
  24024. std::atomic<int> proxy_hits{0};
  24025. std::atomic<int> target_hits{0};
  24026. std::atomic<bool> target_saw_authz{false};
  24027. no_proxy_test::ScopedServer proxy_mock, target;
  24028. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24029. proxy_hits++;
  24030. res.status = 302;
  24031. res.set_header("Location", "http://127.0.0.1:" +
  24032. std::to_string(target.port()) + "/landed");
  24033. });
  24034. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24035. target_hits++;
  24036. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24037. res.set_content("direct", "text/plain");
  24038. });
  24039. proxy_mock.listen();
  24040. target.listen();
  24041. Client cli("public.example", target.port());
  24042. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24043. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24044. cli.set_proxy_basic_auth("u", "p");
  24045. cli.set_no_proxy({"127.0.0.1"});
  24046. cli.set_follow_location(true);
  24047. auto res = cli.Get("/redir");
  24048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24049. EXPECT_GE(proxy_hits.load(), 1);
  24050. EXPECT_GE(target_hits.load(), 1);
  24051. EXPECT_FALSE(target_saw_authz.load());
  24052. }
  24053. #ifdef CPPHTTPLIB_SSL_ENABLED
  24054. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24055. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24056. // proxy creds would be sent to the (possibly hostile) origin.
  24057. std::atomic<int> target_hits{0};
  24058. std::atomic<bool> target_saw_proxy_authz{false};
  24059. no_proxy_test::ScopedServer target;
  24060. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24061. target_hits++;
  24062. if (req.has_header("Proxy-Authorization")) {
  24063. target_saw_proxy_authz = true;
  24064. }
  24065. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24066. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24067. "nonce=\"abc\", algorithm=MD5");
  24068. });
  24069. target.listen();
  24070. // The proxy address is set to the target's port: the bypass MUST kick in;
  24071. // if it doesn't, the test still routes "via proxy" to the same server and
  24072. // the Proxy-Authorization assertion below catches the leak.
  24073. Client cli("evil.example", target.port());
  24074. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24075. cli.set_proxy("127.0.0.1", target.port());
  24076. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24077. cli.set_no_proxy({"evil.example"});
  24078. auto res = cli.Get("/x");
  24079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24080. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24081. EXPECT_EQ(1, target_hits.load());
  24082. EXPECT_FALSE(target_saw_proxy_authz.load());
  24083. }
  24084. #endif
  24085. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24086. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24087. std::atomic<int> proxy_hits{0};
  24088. std::atomic<int> bypass_hits{0};
  24089. std::atomic<bool> proxy_saw_c_url{false};
  24090. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24091. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24092. proxy_hits++;
  24093. if (req.path.find("/start") != std::string::npos) {
  24094. res.status = 302;
  24095. res.set_header("Location", "http://127.0.0.1:" +
  24096. std::to_string(bypass_server.port()) +
  24097. "/middle");
  24098. return;
  24099. }
  24100. if (req.path.find("/end") != std::string::npos) {
  24101. proxy_saw_c_url = true;
  24102. res.set_content("c-via-proxy", "text/plain");
  24103. return;
  24104. }
  24105. res.set_content("unexpected", "text/plain");
  24106. });
  24107. // public.example's "advertised" port is arbitrary (the request never lands
  24108. // there — it goes through the proxy), but use a dynamic value to stay
  24109. // friendly with sharded parallel runs.
  24110. int public_port = bypass_server.port();
  24111. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24112. bypass_hits++;
  24113. res.status = 302;
  24114. res.set_header("Location", "http://public.example:" +
  24115. std::to_string(public_port) + "/end");
  24116. });
  24117. proxy_mock.listen();
  24118. bypass_server.listen();
  24119. Client cli("public.example", public_port);
  24120. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24121. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24122. cli.set_no_proxy({"127.0.0.1"});
  24123. cli.set_follow_location(true);
  24124. auto res = cli.Get("/start");
  24125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24126. EXPECT_EQ(StatusCode::OK_200, res->status);
  24127. EXPECT_EQ("c-via-proxy", res->body);
  24128. EXPECT_GE(proxy_hits.load(), 2);
  24129. EXPECT_GE(bypass_hits.load(), 1);
  24130. EXPECT_TRUE(proxy_saw_c_url.load());
  24131. }
  24132. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24133. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24134. // request reconnects to the correct endpoint.
  24135. std::atomic<int> proxy_hits{0};
  24136. std::atomic<int> target_hits{0};
  24137. no_proxy_test::ScopedServer proxy_mock, target;
  24138. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24139. proxy_hits++;
  24140. res.set_content("via-proxy", "text/plain");
  24141. });
  24142. target.svr().Get(".*", [&](const Request &, Response &res) {
  24143. target_hits++;
  24144. res.set_content("direct", "text/plain");
  24145. });
  24146. proxy_mock.listen();
  24147. target.listen();
  24148. Client cli("public.example", target.port());
  24149. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24150. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24151. cli.set_keep_alive(true);
  24152. auto res1 = cli.Get("/a");
  24153. ASSERT_TRUE(res1);
  24154. EXPECT_EQ("via-proxy", res1->body);
  24155. EXPECT_EQ(1, proxy_hits.load());
  24156. EXPECT_EQ(0, target_hits.load());
  24157. cli.set_no_proxy({"public.example"});
  24158. auto res2 = cli.Get("/b");
  24159. ASSERT_TRUE(res2);
  24160. EXPECT_EQ("direct", res2->body);
  24161. EXPECT_EQ(1, proxy_hits.load());
  24162. EXPECT_EQ(1, target_hits.load());
  24163. }
  24164. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24165. namespace proxy_tunnel_test {
  24166. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24167. class ScopedSSLServer {
  24168. public:
  24169. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24170. port_ = svr_.bind_to_any_port("127.0.0.1");
  24171. }
  24172. ~ScopedSSLServer() {
  24173. svr_.stop();
  24174. if (th_.joinable()) { th_.join(); }
  24175. }
  24176. SSLServer &svr() { return svr_; }
  24177. int port() const { return port_; }
  24178. void listen() {
  24179. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24180. svr_.wait_until_ready();
  24181. }
  24182. private:
  24183. SSLServer svr_;
  24184. std::thread th_;
  24185. int port_ = 0;
  24186. };
  24187. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24188. class ScopedConnectProxy {
  24189. public:
  24190. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24191. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24192. if (listen_fd_ < 0) { return; }
  24193. int yes = 1;
  24194. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24195. sockaddr_in a{};
  24196. a.sin_family = AF_INET;
  24197. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24198. a.sin_port = 0;
  24199. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24200. return;
  24201. }
  24202. socklen_t alen = sizeof(a);
  24203. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24204. 0) {
  24205. return;
  24206. }
  24207. port_ = ntohs(a.sin_port);
  24208. if (::listen(listen_fd_, 1) != 0) { return; }
  24209. th_ = std::thread([this] { run(); });
  24210. }
  24211. ~ScopedConnectProxy() {
  24212. stop_ = true;
  24213. if (listen_fd_ >= 0) {
  24214. ::shutdown(listen_fd_, SHUT_RDWR);
  24215. ::close(listen_fd_);
  24216. }
  24217. if (th_.joinable()) { th_.join(); }
  24218. }
  24219. int port() const { return port_; }
  24220. int connect_hits() const { return connect_hits_.load(); }
  24221. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24222. std::string connect_request() const {
  24223. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24224. return connect_request_;
  24225. }
  24226. private:
  24227. void run() {
  24228. while (!stop_.load()) {
  24229. fd_set rfds;
  24230. FD_ZERO(&rfds);
  24231. FD_SET(listen_fd_, &rfds);
  24232. timeval tv{0, 100 * 1000};
  24233. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24234. if (sel <= 0) { continue; }
  24235. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24236. if (client_fd < 0) { continue; }
  24237. std::string req;
  24238. char buf[2048];
  24239. while (req.find("\r\n\r\n") == std::string::npos) {
  24240. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24241. if (n <= 0) { break; }
  24242. req.append(buf, static_cast<size_t>(n));
  24243. }
  24244. if (req.compare(0, 7, "CONNECT") != 0) {
  24245. ::close(client_fd);
  24246. continue;
  24247. }
  24248. connect_hits_++;
  24249. {
  24250. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24251. connect_request_ = req;
  24252. }
  24253. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24254. ::send(client_fd, ok, std::strlen(ok), 0);
  24255. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24256. sockaddr_in o{};
  24257. o.sin_family = AF_INET;
  24258. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24259. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24260. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24261. 0) {
  24262. ::close(client_fd);
  24263. ::close(origin_fd);
  24264. continue;
  24265. }
  24266. auto forward = [](int from, int to) {
  24267. char b[8192];
  24268. for (;;) {
  24269. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24270. if (n <= 0) { break; }
  24271. ssize_t off = 0;
  24272. while (off < n) {
  24273. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24274. if (s <= 0) {
  24275. off = n;
  24276. break;
  24277. }
  24278. off += s;
  24279. }
  24280. }
  24281. ::shutdown(to, SHUT_WR);
  24282. };
  24283. std::thread t1([&] { forward(client_fd, origin_fd); });
  24284. std::thread t2([&] { forward(origin_fd, client_fd); });
  24285. t1.join();
  24286. t2.join();
  24287. ::close(client_fd);
  24288. ::close(origin_fd);
  24289. }
  24290. }
  24291. int forward_port_ = -1;
  24292. int listen_fd_ = -1;
  24293. int port_ = 0;
  24294. std::thread th_;
  24295. std::atomic<bool> stop_{false};
  24296. std::atomic<int> connect_hits_{0};
  24297. mutable std::mutex connect_request_mutex_;
  24298. std::string connect_request_;
  24299. };
  24300. // Sends one request through the CONNECT proxy to the TLS origin with a
  24301. // credential configured for each hop, and checks that each credential reaches
  24302. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24303. // origin's (every header in origin_headers) on the tunnelled request.
  24304. void CredentialsStayWithTheirHop(
  24305. const std::function<void(SSLClient &)> &set_credentials,
  24306. const std::string &scheme,
  24307. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24308. std::atomic<int> origin_hits{0};
  24309. std::atomic<bool> origin_saw_proxy_authz{false};
  24310. std::atomic<bool> origin_saw_headers{false};
  24311. ScopedSSLServer origin;
  24312. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24313. origin_hits++;
  24314. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24315. origin_saw_headers =
  24316. std::all_of(origin_headers.begin(), origin_headers.end(),
  24317. [&](const std::string &h) { return req.has_header(h); });
  24318. res.set_content("ok", "text/plain");
  24319. });
  24320. origin.listen();
  24321. ScopedConnectProxy proxy(origin.port());
  24322. ASSERT_NE(0, proxy.port());
  24323. // Pinned to 127.0.0.1 for the same reason as the test below.
  24324. SSLClient cli("127.0.0.1", origin.port());
  24325. cli.enable_server_certificate_verification(false);
  24326. cli.set_proxy("127.0.0.1", proxy.port());
  24327. set_credentials(cli);
  24328. auto res = cli.Get("/x");
  24329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24330. EXPECT_EQ(StatusCode::OK_200, res->status);
  24331. EXPECT_EQ(1, origin_hits.load());
  24332. EXPECT_EQ(1, proxy.connect_hits());
  24333. EXPECT_TRUE(origin_saw_headers.load());
  24334. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24335. << "Proxy-Authorization must not be sent inside the tunnel";
  24336. auto connect_req = proxy.connect_request();
  24337. EXPECT_NE(std::string::npos,
  24338. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24339. for (const auto &h : origin_headers) {
  24340. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24341. << h << " must not be sent to the proxy on CONNECT";
  24342. }
  24343. }
  24344. } // namespace proxy_tunnel_test
  24345. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24346. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24347. [](SSLClient &cli) {
  24348. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24349. cli.set_basic_auth("origin-user", "origin-pass");
  24350. },
  24351. "Basic");
  24352. }
  24353. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24354. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24355. [](SSLClient &cli) {
  24356. cli.set_proxy_bearer_token_auth("proxy-token");
  24357. cli.set_bearer_token_auth("origin-token");
  24358. },
  24359. "Bearer");
  24360. }
  24361. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24362. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24363. [](SSLClient &cli) {
  24364. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24365. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24366. {"Cookie", "sid=origin-session"},
  24367. {"X-Api-Key", "origin-key"}});
  24368. },
  24369. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24370. }
  24371. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24372. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24373. // retry; otherwise proxy creds would be sent to the origin.
  24374. std::atomic<int> origin_hits{0};
  24375. std::atomic<bool> origin_saw_proxy_authz{false};
  24376. proxy_tunnel_test::ScopedSSLServer origin;
  24377. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24378. origin_hits++;
  24379. if (req.has_header("Proxy-Authorization")) {
  24380. origin_saw_proxy_authz = true;
  24381. }
  24382. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24383. res.set_header("Proxy-Authenticate",
  24384. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24385. "algorithm=MD5");
  24386. });
  24387. origin.listen();
  24388. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24389. ASSERT_NE(0, proxy.port());
  24390. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24391. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24392. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24393. // and answer with its own status, making this test flaky.
  24394. SSLClient cli("127.0.0.1", origin.port());
  24395. cli.enable_server_certificate_verification(false);
  24396. cli.set_proxy("127.0.0.1", proxy.port());
  24397. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24398. auto res = cli.Get("/x");
  24399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24400. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24401. EXPECT_EQ(1, origin_hits.load());
  24402. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24403. EXPECT_EQ(1, proxy.connect_hits());
  24404. }
  24405. #endif