test.cc 908 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. } // namespace detail
  480. } // namespace httplib
  481. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  482. struct {
  483. const char *line;
  484. const char *version;
  485. int status;
  486. const char *reason;
  487. } cases[] = {
  488. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  489. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  490. // The reason phrase may be empty, or left out along with its space.
  491. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  492. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  493. };
  494. for (const auto &c : cases) {
  495. std::string version;
  496. int status = 0;
  497. std::string reason = "unset";
  498. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  499. << c.line;
  500. EXPECT_EQ(c.version, version);
  501. EXPECT_EQ(c.status, status);
  502. EXPECT_EQ(c.reason, reason);
  503. }
  504. }
  505. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  506. const char *lines[] = {
  507. "HTTP/2 200 OK\r\n",
  508. "HTTP/1.2 200 OK\r\n",
  509. "HTTP/1.1 20 OK\r\n",
  510. "HTTP/1.1 2000 OK\r\n",
  511. "HTTP/1.1 2x0 OK\r\n",
  512. "HTTP/1.1 200 OK\r\n",
  513. "HTTP/1.1 200OK\r\n",
  514. "HTTP/1.1 200 O\rK\r\n",
  515. "HTTP/1.1 200 OK",
  516. "HTTP/1.1 200 OK\r\nX",
  517. "",
  518. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  519. "HTTP/1.1 200 OK\n",
  520. #endif
  521. };
  522. for (auto line : lines) {
  523. std::string version;
  524. int status = 0;
  525. std::string reason;
  526. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  527. << line;
  528. }
  529. }
  530. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  531. // Long enough to overflow the stack when matched with std::regex.
  532. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  533. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  538. EXPECT_EQ(200, status);
  539. EXPECT_EQ(long_reason, reason);
  540. }
  541. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  542. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  543. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  544. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  545. EXPECT_EQ("", detail::file_extension("noext"));
  546. EXPECT_EQ("", detail::file_extension("a."));
  547. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  548. EXPECT_EQ("", detail::file_extension("a.b-c"));
  549. // Long enough to overflow the stack when matched with std::regex.
  550. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  551. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  552. }
  553. // Forward declaration: in split builds split.py strips `inline` and moves the
  554. // definition into httplib.cc, so detail::base64_encode is not visible from the
  555. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  556. // in both header-only and split builds.
  557. namespace httplib {
  558. namespace detail {
  559. std::string base64_encode(const std::string &in);
  560. } // namespace detail
  561. } // namespace httplib
  562. TEST(Base64EncodeTest, KnownAnswers) {
  563. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  564. // where the accumulator's top bit is already set before the next shift.
  565. EXPECT_EQ("", detail::base64_encode(""));
  566. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  567. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  568. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  569. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  570. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  571. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  572. // High bytes keep the top bit set across several rounds.
  573. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  574. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  575. }
  576. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  577. string unescapedCharacters = "-_.!~*'()";
  578. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  579. }
  580. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  581. string reservedCharacters = ";,/?:@&=+$";
  582. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  583. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  584. }
  585. TEST(ClientQueryOrder, PreserveOrder) {
  586. // This test reproduces Issue #2259: client may reorder query parameters
  587. // when sending a GET request. The expected behavior is that the client
  588. // preserves the original query string order when the caller supplied it
  589. // as part of the path.
  590. Server svr;
  591. svr.Get("/", [&](const Request &req, Response &res) {
  592. // Echo back the raw target so the test can assert ordering
  593. res.set_content(req.target, "text/plain");
  594. });
  595. std::thread t{[&] { svr.listen(HOST, PORT); }};
  596. auto se = detail::scope_exit([&] {
  597. svr.stop();
  598. t.join();
  599. ASSERT_FALSE(svr.is_running());
  600. });
  601. svr.wait_until_ready();
  602. Client cli(HOST, PORT);
  603. ASSERT_TRUE(cli.is_valid());
  604. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  605. auto res = cli.Get(original);
  606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  607. // Expect the echoed target to exactly match the original path (order
  608. // preserved)
  609. EXPECT_EQ(res->body, original);
  610. }
  611. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  612. string chineseCharacters = U8("中国語");
  613. string russianCharacters = U8("дом");
  614. string brazilianCharacters = U8("óculos");
  615. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  616. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  617. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  618. "%D0%B4%D0%BE%D0%BC");
  619. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  620. }
  621. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  622. string unescapedCharacters = "-_.!~*'()";
  623. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  624. }
  625. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  626. string reservedCharacters = ";,/?:@&=+$";
  627. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  628. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  629. }
  630. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  631. string chineseCharacters = U8("中国語");
  632. string russianCharacters = U8("дом");
  633. string brazilianCharacters = U8("óculos");
  634. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  635. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  636. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  637. "%D0%B4%D0%BE%D0%BC");
  638. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  639. }
  640. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  641. // Issue #2082 use case: encoding path component with ampersand
  642. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  643. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  644. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  645. }
  646. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  647. string unescapedCharacters = "-_.!~*'()";
  648. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  649. }
  650. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  651. string reservedCharacters = ";,/?:@&=+$#";
  652. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  653. }
  654. TEST(EncodeUriTest, TestUTF8Characters) {
  655. string chineseCharacters = U8("中国語");
  656. string russianCharacters = U8("дом");
  657. string brazilianCharacters = U8("óculos");
  658. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  659. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  660. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  661. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  662. }
  663. TEST(EncodeUriTest, TestCompleteUri) {
  664. string uri =
  665. "https://example.com/path/to/resource?query=value&param=test#fragment";
  666. EXPECT_EQ(
  667. httplib::encode_uri(uri),
  668. "https://example.com/path/to/resource?query=value&param=test#fragment");
  669. }
  670. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  671. string uri =
  672. "https://example.com/path with spaces/file name.html?q=hello world";
  673. EXPECT_EQ(httplib::encode_uri(uri),
  674. "https://example.com/path%20with%20spaces/"
  675. "file%20name.html?q=hello%20world");
  676. }
  677. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  678. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  679. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  680. }
  681. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  682. string unescapedCharacters = "-_.!~*'()";
  683. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  684. }
  685. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  686. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  687. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  688. string encodedBrazilian = "%C3%B3culos";
  689. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  690. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  691. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  692. }
  693. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  694. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  695. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  696. "Piri Tommy Villiers - on & on");
  697. }
  698. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  699. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  700. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  701. }
  702. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  703. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  704. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  705. }
  706. TEST(DecodeUriTest, TestUTF8Characters) {
  707. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  708. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  709. string encodedBrazilian = "%C3%B3culos";
  710. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  711. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  712. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  713. }
  714. TEST(DecodeUriTest, TestCompleteUri) {
  715. string encodedUri = "https://example.com/path%20with%20spaces/"
  716. "file%20name.html?q=hello%20world";
  717. EXPECT_EQ(
  718. httplib::decode_uri(encodedUri),
  719. "https://example.com/path with spaces/file name.html?q=hello world");
  720. }
  721. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  722. string original =
  723. "https://example.com/path with spaces/file name.html?q=hello world";
  724. string encoded = httplib::encode_uri(original);
  725. string decoded = httplib::decode_uri(encoded);
  726. EXPECT_EQ(decoded, original);
  727. }
  728. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  729. // decode_uri is the inverse of encode_uri: an escaped reserved character
  730. // stays encoded so it is not promoted into a real delimiter, while
  731. // non-reserved escapes still decode (like JS decodeURI).
  732. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  733. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  734. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  735. "%3F%3A%40%26%3D%2B%24%2C%3B");
  736. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  737. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  738. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  739. "http://example.com/a%2Fb");
  740. // decode_uri_component still decodes the reserved character.
  741. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  742. }
  743. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  744. string original = "Piri Tommy Villiers - on & on";
  745. string encoded = httplib::encode_uri_component(original);
  746. string decoded = httplib::decode_uri_component(encoded);
  747. EXPECT_EQ(decoded, original);
  748. }
  749. TEST(TrimTests, TrimStringTests) {
  750. EXPECT_EQ("abc", detail::trim_copy("abc"));
  751. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  752. EXPECT_TRUE(detail::trim_copy("").empty());
  753. }
  754. TEST(AsciiTest, LocaleIndependentClassification) {
  755. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  756. // which consult the global C locale: std::isalnum(0xC5) can return true
  757. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  758. // helpers must classify every byte by the ASCII grammar alone.
  759. for (int i = 0; i < 256; i++) {
  760. auto c = static_cast<char>(i);
  761. auto is_digit = i >= '0' && i <= '9';
  762. auto is_upper = i >= 'A' && i <= 'Z';
  763. auto is_lower = i >= 'a' && i <= 'z';
  764. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  765. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  766. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  767. << "byte " << i;
  768. }
  769. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  770. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  771. // Non-ASCII bytes must be percent-encoded, never passed through as
  772. // alphanumeric.
  773. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  774. }
  775. TEST(FromCharsTest, Double) {
  776. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  777. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  778. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  779. auto parse = [](const std::string &s, double &v) {
  780. return detail::from_chars(s.data(), s.data() + s.size(), v);
  781. };
  782. double v = -1.0;
  783. // Representative quality values.
  784. EXPECT_EQ(parse("0", v).ec, std::errc{});
  785. EXPECT_DOUBLE_EQ(v, 0.0);
  786. EXPECT_EQ(parse("1", v).ec, std::errc{});
  787. EXPECT_DOUBLE_EQ(v, 1.0);
  788. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  789. EXPECT_DOUBLE_EQ(v, 0.8);
  790. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  791. EXPECT_DOUBLE_EQ(v, 0.001);
  792. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  793. EXPECT_DOUBLE_EQ(v, 1.0);
  794. // A missing integer or fractional part is tolerated.
  795. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  796. EXPECT_DOUBLE_EQ(v, 0.5);
  797. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  798. EXPECT_DOUBLE_EQ(v, 5.0);
  799. // Values outside [0, 1] still parse; the caller range-checks them.
  800. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  801. EXPECT_DOUBLE_EQ(v, 123.456);
  802. // Stops at the first byte that is not part of the number and reports where.
  803. std::string trailing = "0.9, text/html";
  804. auto r = parse(trailing, v);
  805. EXPECT_EQ(r.ec, std::errc{});
  806. EXPECT_DOUBLE_EQ(v, 0.9);
  807. EXPECT_EQ(*r.ptr, ',');
  808. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  809. // outright, and an 'e'/'E' simply ends the number.
  810. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  811. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  812. std::string exp_input = "1.5e3";
  813. r = parse(exp_input, v);
  814. EXPECT_EQ(r.ec, std::errc{});
  815. EXPECT_DOUBLE_EQ(v, 1.5);
  816. EXPECT_EQ(*r.ptr, 'e');
  817. // Invalid inputs.
  818. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  819. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  820. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  821. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  822. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  823. // Pathological but well-formed inputs must stay bounded (no overflow, no
  824. // out-of-bounds table access) and stay within [0, 1] for the caller.
  825. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  826. std::errc{});
  827. EXPECT_DOUBLE_EQ(v, 0.0);
  828. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  829. std::errc{});
  830. EXPECT_GE(v, 0.0);
  831. EXPECT_LE(v, 1.0);
  832. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  833. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  834. }
  835. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  836. // Simple case without quality values
  837. std::vector<std::string> result1;
  838. EXPECT_TRUE(detail::parse_accept_header(
  839. "text/html,application/json,text/plain", result1));
  840. EXPECT_EQ(result1.size(), 3U);
  841. EXPECT_EQ(result1[0], "text/html");
  842. EXPECT_EQ(result1[1], "application/json");
  843. EXPECT_EQ(result1[2], "text/plain");
  844. // With quality values
  845. std::vector<std::string> result2;
  846. EXPECT_TRUE(detail::parse_accept_header(
  847. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  848. EXPECT_EQ(result2.size(), 3U);
  849. EXPECT_EQ(result2[0], "application/json"); // highest q value
  850. EXPECT_EQ(result2[1], "text/html");
  851. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  852. }
  853. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  854. // Mixed with and without quality values
  855. std::vector<std::string> result;
  856. EXPECT_TRUE(detail::parse_accept_header(
  857. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  858. EXPECT_EQ(result.size(), 3U);
  859. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  860. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  861. EXPECT_EQ(result[2], "application/json"); // q=0.5
  862. }
  863. TEST(ParseAcceptHeaderTest, EdgeCases) {
  864. // Empty header
  865. std::vector<std::string> empty_result;
  866. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  867. EXPECT_TRUE(empty_result.empty());
  868. // Single type
  869. std::vector<std::string> single_result;
  870. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  871. EXPECT_EQ(single_result.size(), 1U);
  872. EXPECT_EQ(single_result[0], "application/json");
  873. // Wildcard types
  874. std::vector<std::string> wildcard_result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  877. EXPECT_EQ(wildcard_result.size(), 3U);
  878. EXPECT_EQ(wildcard_result[0], "application/json");
  879. EXPECT_EQ(wildcard_result[1], "text/*");
  880. EXPECT_EQ(wildcard_result[2], "*/*");
  881. }
  882. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  883. // Common browser Accept header
  884. std::vector<std::string> browser_result;
  885. EXPECT_TRUE(
  886. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  887. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  888. browser_result));
  889. EXPECT_EQ(browser_result.size(), 6U);
  890. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  891. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  892. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  893. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  894. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  895. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  896. // API client header
  897. std::vector<std::string> api_result;
  898. EXPECT_TRUE(detail::parse_accept_header(
  899. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  900. api_result));
  901. EXPECT_EQ(api_result.size(), 3U);
  902. EXPECT_EQ(api_result[0], "application/json");
  903. EXPECT_EQ(api_result[1], "application/xml");
  904. EXPECT_EQ(api_result[2], "text/plain");
  905. }
  906. TEST(ParseAcceptHeaderTest, SpecialCases) {
  907. // Quality value with 3 decimal places
  908. std::vector<std::string> decimal_result;
  909. EXPECT_TRUE(detail::parse_accept_header(
  910. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  911. EXPECT_EQ(decimal_result.size(), 2U);
  912. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  913. EXPECT_EQ(decimal_result[1], "text/html");
  914. // Zero quality (should still be included but with lowest priority)
  915. std::vector<std::string> zero_q_result;
  916. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  917. zero_q_result));
  918. EXPECT_EQ(zero_q_result.size(), 2U);
  919. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  920. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  921. // No spaces around commas
  922. std::vector<std::string> no_space_result;
  923. EXPECT_TRUE(detail::parse_accept_header(
  924. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  925. no_space_result));
  926. EXPECT_EQ(no_space_result.size(), 3U);
  927. EXPECT_EQ(no_space_result[0], "text/html");
  928. EXPECT_EQ(no_space_result[1], "application/json");
  929. EXPECT_EQ(no_space_result[2], "text/plain");
  930. }
  931. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  932. // Quality values always use '.' as the decimal separator, so parsing must
  933. // not depend on the process locale. An embedding application may have
  934. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  935. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  936. std::string saved = cur ? cur : "C";
  937. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  938. "fr_FR.UTF-8"};
  939. bool switched = false;
  940. for (const auto loc : comma_locales) {
  941. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  942. std::localeconv()->decimal_point[0] == ',') {
  943. switched = true;
  944. break;
  945. }
  946. }
  947. if (!switched) {
  948. std::setlocale(LC_NUMERIC, saved.c_str());
  949. GTEST_SKIP() << "no comma-decimal locale available on this host";
  950. }
  951. // The higher-weighted type appears later in the list, so a correct parse
  952. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  953. // sensitive parse reads both weights as 0 and leaves the original order.
  954. std::vector<std::string> result;
  955. EXPECT_TRUE(detail::parse_accept_header(
  956. "application/json;q=0.1,text/html;q=0.9", result));
  957. ASSERT_EQ(result.size(), 2U);
  958. EXPECT_EQ(result[0], "text/html");
  959. EXPECT_EQ(result[1], "application/json");
  960. std::setlocale(LC_NUMERIC, saved.c_str());
  961. }
  962. TEST(ParseAcceptHeaderTest, InvalidCases) {
  963. std::vector<std::string> result;
  964. // Invalid quality value (> 1.0)
  965. EXPECT_FALSE(
  966. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  967. // Invalid quality value (< 0.0)
  968. EXPECT_FALSE(
  969. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  970. // Invalid quality value (not a number)
  971. EXPECT_FALSE(detail::parse_accept_header(
  972. "text/html;q=invalid,application/json", result));
  973. // A valid numeric prefix does not make the entire quality value valid.
  974. EXPECT_FALSE(detail::parse_accept_header(
  975. "text/html;q=0.5junk,application/json", result));
  976. // Empty quality value
  977. EXPECT_FALSE(
  978. detail::parse_accept_header("text/html;q=,application/json", result));
  979. // Invalid media type format (no slash and not wildcard)
  980. EXPECT_FALSE(
  981. detail::parse_accept_header("invalidtype,application/json", result));
  982. // Valid cases should still work
  983. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  984. EXPECT_EQ(result.size(), 1U);
  985. EXPECT_EQ(result[0], "*/*");
  986. EXPECT_TRUE(detail::parse_accept_header("*", result));
  987. EXPECT_EQ(result.size(), 1U);
  988. EXPECT_EQ(result[0], "*");
  989. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  990. EXPECT_EQ(result.size(), 1U);
  991. EXPECT_EQ(result[0], "text/*");
  992. }
  993. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  994. // elements, so a leading, trailing or doubled comma is a legal Accept value
  995. // and must not be answered with 400 Bad Request.
  996. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  997. struct {
  998. const char *value;
  999. std::vector<std::string> expected;
  1000. } cases[] = {
  1001. {",application/json", {"application/json"}},
  1002. {"text/html,", {"text/html"}},
  1003. {"text/html,,*/*", {"text/html", "*/*"}},
  1004. // An empty element may be spelled with whitespace in it
  1005. {"text/html, , application/json", {"text/html", "application/json"}},
  1006. // Nothing but empty elements is an empty list, which means the same
  1007. // thing as no Accept header at all
  1008. {",,,", {}},
  1009. // Quality values still apply across ignored empty elements
  1010. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1011. };
  1012. for (const auto &c : cases) {
  1013. std::vector<std::string> result;
  1014. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1015. << "value: " << c.value;
  1016. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1017. }
  1018. // An invalid entry is still rejected when empty elements surround it
  1019. std::vector<std::string> result;
  1020. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1021. }
  1022. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1023. // or ';' inside one does not end the list element or the parameter. Section
  1024. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1025. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1026. struct {
  1027. const char *value;
  1028. std::vector<std::string> expected;
  1029. } cases[] = {
  1030. {"text/html;profile=\"a,b\",application/json",
  1031. {"text/html", "application/json"}},
  1032. // A "q=" inside a quoted value is not the weight
  1033. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1034. {"text/html", "application/json"}},
  1035. // The weight after a quoted value still applies
  1036. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1037. {"application/json", "text/html"}},
  1038. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1039. {"application/json", "text/html"}},
  1040. {"text/html;profile=\"a\\\"b\",application/json",
  1041. {"text/html", "application/json"}},
  1042. // An escaped backslash does not escape the '"' after it
  1043. {"text/html;profile=\"a\\\\\",application/json",
  1044. {"text/html", "application/json"}},
  1045. };
  1046. for (const auto &c : cases) {
  1047. std::vector<std::string> result;
  1048. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1049. << "value: " << c.value;
  1050. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1051. }
  1052. }
  1053. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1054. Server svr;
  1055. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1056. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1057. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1058. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1059. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1060. res.set_content("ok", "text/plain");
  1061. });
  1062. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1063. EXPECT_TRUE(false);
  1064. res.set_content("bad request", "text/plain");
  1065. });
  1066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1067. auto se = detail::scope_exit([&] {
  1068. svr.stop();
  1069. listen_thread.join();
  1070. ASSERT_FALSE(svr.is_running());
  1071. });
  1072. svr.wait_until_ready();
  1073. Client cli("localhost", PORT);
  1074. {
  1075. auto res = cli.Get(
  1076. "/accept_ok",
  1077. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1079. EXPECT_EQ(StatusCode::OK_200, res->status);
  1080. }
  1081. {
  1082. auto res = cli.Get("/accept_bad_request",
  1083. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1085. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1086. }
  1087. }
  1088. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1089. Server svr;
  1090. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1091. res.set_content("ok", "text/plain");
  1092. });
  1093. std::atomic<int> start_count{0};
  1094. std::atomic<bool> running_when_called{false};
  1095. svr.set_start_handler([&]() {
  1096. running_when_called = svr.is_running();
  1097. start_count++;
  1098. });
  1099. auto port = svr.bind_to_any_port(HOST);
  1100. std::thread t([&]() { svr.listen_after_bind(); });
  1101. auto se = detail::scope_exit([&] {
  1102. svr.stop();
  1103. t.join();
  1104. ASSERT_FALSE(svr.is_running());
  1105. });
  1106. svr.wait_until_ready();
  1107. // A successful request proves the accept loop is running, which the start
  1108. // handler precedes; so by now the handler must have run exactly once.
  1109. Client cli(HOST, port);
  1110. cli.set_connection_timeout(std::chrono::seconds(5));
  1111. auto res = cli.Get("/");
  1112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1113. EXPECT_EQ(StatusCode::OK_200, res->status);
  1114. EXPECT_EQ(1, start_count.load());
  1115. EXPECT_TRUE(running_when_called.load());
  1116. }
  1117. TEST(DivideTest, DivideStringTests) {
  1118. auto divide = [](const std::string &str, char d) {
  1119. std::string lhs;
  1120. std::string rhs;
  1121. detail::divide(str, d,
  1122. [&](const char *lhs_data, std::size_t lhs_size,
  1123. const char *rhs_data, std::size_t rhs_size) {
  1124. lhs.assign(lhs_data, lhs_size);
  1125. rhs.assign(rhs_data, rhs_size);
  1126. });
  1127. return std::make_pair(std::move(lhs), std::move(rhs));
  1128. };
  1129. {
  1130. const auto res = divide("", '=');
  1131. EXPECT_EQ(res.first, "");
  1132. EXPECT_EQ(res.second, "");
  1133. }
  1134. {
  1135. const auto res = divide("=", '=');
  1136. EXPECT_EQ(res.first, "");
  1137. EXPECT_EQ(res.second, "");
  1138. }
  1139. {
  1140. const auto res = divide(" ", '=');
  1141. EXPECT_EQ(res.first, " ");
  1142. EXPECT_EQ(res.second, "");
  1143. }
  1144. {
  1145. const auto res = divide("a", '=');
  1146. EXPECT_EQ(res.first, "a");
  1147. EXPECT_EQ(res.second, "");
  1148. }
  1149. {
  1150. const auto res = divide("a=", '=');
  1151. EXPECT_EQ(res.first, "a");
  1152. EXPECT_EQ(res.second, "");
  1153. }
  1154. {
  1155. const auto res = divide("=b", '=');
  1156. EXPECT_EQ(res.first, "");
  1157. EXPECT_EQ(res.second, "b");
  1158. }
  1159. {
  1160. const auto res = divide("a=b", '=');
  1161. EXPECT_EQ(res.first, "a");
  1162. EXPECT_EQ(res.second, "b");
  1163. }
  1164. {
  1165. const auto res = divide("a=b=", '=');
  1166. EXPECT_EQ(res.first, "a");
  1167. EXPECT_EQ(res.second, "b=");
  1168. }
  1169. {
  1170. const auto res = divide("a=b=c", '=');
  1171. EXPECT_EQ(res.first, "a");
  1172. EXPECT_EQ(res.second, "b=c");
  1173. }
  1174. }
  1175. TEST(SplitTest, ParseQueryString) {
  1176. string s = "key1=val1&key2=val2&key3=val3";
  1177. Params dic;
  1178. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1179. [&](const char *b, const char *e) {
  1180. string key, val;
  1181. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1182. if (key.empty()) {
  1183. key.assign(b2, e2);
  1184. } else {
  1185. val.assign(b2, e2);
  1186. }
  1187. });
  1188. dic.emplace(key, val);
  1189. });
  1190. EXPECT_EQ("val1", dic.find("key1")->second);
  1191. EXPECT_EQ("val2", dic.find("key2")->second);
  1192. EXPECT_EQ("val3", dic.find("key3")->second);
  1193. }
  1194. TEST(SplitTest, ParseInvalidQueryTests) {
  1195. {
  1196. string s = " ";
  1197. Params dict;
  1198. detail::parse_query_text(s, dict);
  1199. EXPECT_TRUE(dict.empty());
  1200. }
  1201. {
  1202. string s = " = =";
  1203. Params dict;
  1204. detail::parse_query_text(s, dict);
  1205. EXPECT_TRUE(dict.empty());
  1206. }
  1207. }
  1208. TEST(ParseQueryTest, ParseQueryString) {
  1209. {
  1210. std::string s = "key1=val1&key2=val2&key3=val3";
  1211. Params dic;
  1212. detail::parse_query_text(s, dic);
  1213. EXPECT_EQ("val1", dic.find("key1")->second);
  1214. EXPECT_EQ("val2", dic.find("key2")->second);
  1215. EXPECT_EQ("val3", dic.find("key3")->second);
  1216. }
  1217. {
  1218. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1219. Params dic;
  1220. detail::parse_query_text(s, dic);
  1221. EXPECT_EQ("", dic.find("key1")->second);
  1222. EXPECT_EQ("val1", dic.find("key2")->second);
  1223. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1224. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1225. }
  1226. }
  1227. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1228. Params dic;
  1229. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1230. dic.emplace("key1", "val1");
  1231. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1232. dic.emplace("key2", "val2");
  1233. dic.emplace("key3", "val3");
  1234. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1235. }
  1236. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1237. Params params;
  1238. params.emplace("a", "1");
  1239. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1240. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1241. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1242. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1243. // Long enough to overflow the stack when matched with std::regex.
  1244. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1245. EXPECT_EQ("/p?" + long_query + "&a=1",
  1246. append_query_params("/p?" + long_query, params));
  1247. }
  1248. // Joins every entry of a Headers or Params into "key=value " so a whole
  1249. // traversal can be compared in one assertion. Both are instantiations of the
  1250. // same insertion-ordered container, so one helper serves both.
  1251. template <typename Map> static std::string entries_to_string(const Map &m) {
  1252. std::string s;
  1253. for (const auto &entry : m) {
  1254. s += entry.first + "=" + entry.second + " ";
  1255. }
  1256. return s;
  1257. }
  1258. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1259. // Params used to be a std::multimap, which sorted by name and handed the
  1260. // caller's query back alphabetised. A client signing its query string could
  1261. // not reproduce the order it asked for.
  1262. Params dic;
  1263. dic.emplace("zulu", "1");
  1264. dic.emplace("alpha", "2");
  1265. dic.emplace("mike", "3");
  1266. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1267. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1268. }
  1269. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1270. Params dic;
  1271. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1272. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1273. }
  1274. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1275. Request req;
  1276. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1277. req.params);
  1278. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1279. EXPECT_EQ("first", req.get_param_value("tag"));
  1280. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1281. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1282. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1283. EXPECT_EQ("", req.get_param_value("tag", 3));
  1284. }
  1285. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1286. // Params shares its container with Headers, which matches field names
  1287. // case-insensitively. Parameter names must not pick that up.
  1288. Params dic;
  1289. dic.emplace("Key", "upper");
  1290. dic.emplace("key", "lower");
  1291. EXPECT_EQ(2U, dic.size());
  1292. EXPECT_EQ(1U, dic.count("Key"));
  1293. EXPECT_EQ(1U, dic.count("key"));
  1294. EXPECT_EQ("upper", dic.find("Key")->second);
  1295. EXPECT_EQ("lower", dic.find("key")->second);
  1296. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1297. }
  1298. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1299. Server svr;
  1300. std::string order;
  1301. svr.Get("/order", [&](const Request &req, Response &res) {
  1302. order = entries_to_string(req.params);
  1303. res.set_content("ok", "text/plain");
  1304. });
  1305. auto port = svr.bind_to_any_port(HOST);
  1306. thread t = thread([&] { svr.listen_after_bind(); });
  1307. auto se = detail::scope_exit([&] {
  1308. svr.stop();
  1309. t.join();
  1310. ASSERT_FALSE(svr.is_running());
  1311. });
  1312. svr.wait_until_ready();
  1313. Client cli(HOST, port);
  1314. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1315. ASSERT_TRUE(res);
  1316. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1317. }
  1318. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1319. Server svr;
  1320. std::string field_order, file_order;
  1321. svr.Post("/order", [&](const Request &req, Response &res) {
  1322. for (const auto &field : req.form.fields) {
  1323. field_order += field.first + "=" + field.second.content + " ";
  1324. }
  1325. for (const auto &file : req.form.files) {
  1326. file_order += file.first + "=" + file.second.filename + " ";
  1327. }
  1328. res.set_content("ok", "text/plain");
  1329. });
  1330. auto port = svr.bind_to_any_port(HOST);
  1331. thread t = thread([&] { svr.listen_after_bind(); });
  1332. auto se = detail::scope_exit([&] {
  1333. svr.stop();
  1334. t.join();
  1335. ASSERT_FALSE(svr.is_running());
  1336. });
  1337. svr.wait_until_ready();
  1338. UploadFormDataItems items = {
  1339. {"zulu", "1", "", ""},
  1340. {"alpha", "2", "", ""},
  1341. {"mike", "3", "", ""},
  1342. {"zebra", "z", "z.txt", "text/plain"},
  1343. {"apple", "a", "a.txt", "text/plain"},
  1344. };
  1345. Client cli(HOST, port);
  1346. auto res = cli.Post("/order", items);
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1349. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1350. }
  1351. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1352. Server svr;
  1353. std::vector<std::string> values;
  1354. std::string first, second, out_of_range, order;
  1355. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1356. values = req.form.get_fields("tag");
  1357. first = req.form.get_field("tag", 0);
  1358. second = req.form.get_field("tag", 1);
  1359. out_of_range = req.form.get_field("tag", 2);
  1360. for (const auto &field : req.form.fields) {
  1361. order += field.first + "=" + field.second.content + " ";
  1362. }
  1363. res.set_content("ok", "text/plain");
  1364. });
  1365. auto port = svr.bind_to_any_port(HOST);
  1366. thread t = thread([&] { svr.listen_after_bind(); });
  1367. auto se = detail::scope_exit([&] {
  1368. svr.stop();
  1369. t.join();
  1370. ASSERT_FALSE(svr.is_running());
  1371. });
  1372. svr.wait_until_ready();
  1373. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1374. // not adjacent in the container.
  1375. UploadFormDataItems items = {
  1376. {"tag", "first", "", ""},
  1377. {"other", "x", "", ""},
  1378. {"tag", "second", "", ""},
  1379. };
  1380. Client cli(HOST, port);
  1381. auto res = cli.Post("/repeated", items);
  1382. ASSERT_TRUE(res);
  1383. ASSERT_EQ(2U, values.size());
  1384. EXPECT_EQ("first", values[0]);
  1385. EXPECT_EQ("second", values[1]);
  1386. EXPECT_EQ("first", first);
  1387. EXPECT_EQ("second", second);
  1388. // std::multimap already kept entries sharing a name in insertion order, so
  1389. // everything above passes without this change too. The whole traversal is
  1390. // what tells the two apart: sorting by name would hoist "other" to the front
  1391. // and the two "tag" parts would end up adjacent.
  1392. EXPECT_EQ("tag=first other=x tag=second ", order);
  1393. // Advancing past the last entry of a name used to run off the container;
  1394. // the container's saturating increment makes it return the default instead.
  1395. EXPECT_EQ("", out_of_range);
  1396. }
  1397. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1398. // Server::read_content() keeps a FormFields::iterator alive across the
  1399. // content callbacks that fill the part it points at. The container is
  1400. // vector-backed, so a later emplace can reallocate and invalidate an older
  1401. // iterator; 64 parts grow the vector through seven reallocations, which
  1402. // checks that every part's content still lands in its own entry.
  1403. const size_t part_count = 64;
  1404. // One formula for both the parts sent and the values expected back, so the
  1405. // two cannot drift apart.
  1406. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1407. auto content_of = [](size_t i) {
  1408. return std::string(64, static_cast<char>('a' + (i % 26)));
  1409. };
  1410. Server svr;
  1411. std::vector<std::pair<std::string, std::string>> received;
  1412. svr.Post("/many", [&](const Request &req, Response &res) {
  1413. for (const auto &field : req.form.fields) {
  1414. received.emplace_back(field.first, field.second.content);
  1415. }
  1416. res.set_content("ok", "text/plain");
  1417. });
  1418. auto port = svr.bind_to_any_port(HOST);
  1419. thread t = thread([&] { svr.listen_after_bind(); });
  1420. auto se = detail::scope_exit([&] {
  1421. svr.stop();
  1422. t.join();
  1423. ASSERT_FALSE(svr.is_running());
  1424. });
  1425. svr.wait_until_ready();
  1426. UploadFormDataItems items;
  1427. for (size_t i = 0; i < part_count; i++) {
  1428. items.push_back({name_of(i), content_of(i), "", ""});
  1429. }
  1430. Client cli(HOST, port);
  1431. auto res = cli.Post("/many", items);
  1432. ASSERT_TRUE(res);
  1433. ASSERT_EQ(part_count, received.size());
  1434. for (size_t i = 0; i < part_count; i++) {
  1435. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1436. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1437. }
  1438. }
  1439. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1440. string content_type = "multipart/form-data; boundary=something";
  1441. string boundary;
  1442. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1443. EXPECT_TRUE(ret);
  1444. EXPECT_EQ(boundary, "something");
  1445. }
  1446. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1447. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1448. string boundary;
  1449. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1450. EXPECT_TRUE(ret);
  1451. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1452. }
  1453. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1454. string content_type =
  1455. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1456. string boundary;
  1457. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1458. EXPECT_TRUE(ret);
  1459. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1460. }
  1461. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1462. string content_type =
  1463. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1464. string boundary;
  1465. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1466. EXPECT_TRUE(ret);
  1467. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1468. }
  1469. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1470. const string boundary(70, 'a');
  1471. string content_type = "multipart/form-data; boundary=" + boundary;
  1472. string parsed;
  1473. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1474. EXPECT_TRUE(ret);
  1475. EXPECT_EQ(parsed, boundary);
  1476. }
  1477. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1478. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1479. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1480. string parsed;
  1481. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1482. EXPECT_FALSE(ret);
  1483. }
  1484. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1485. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1486. // is 72 characters on the wire and still valid.
  1487. const string boundary(70, 'a');
  1488. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1489. string parsed;
  1490. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1491. EXPECT_EQ(parsed, boundary);
  1492. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1493. parsed.clear();
  1494. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1495. }
  1496. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1497. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1498. // The parameter parser must not treat that '=' as the key/value separator.
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1501. "charset=UTF-8";
  1502. string parsed;
  1503. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1504. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1507. // A ';' inside the quoted-string is part of the value, not a parameter
  1508. // separator, so it must not truncate the boundary.
  1509. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1510. string parsed;
  1511. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1512. EXPECT_EQ(parsed, "a;b");
  1513. }
  1514. TEST(ParseDispositionParamsTest, QuotedValues) {
  1515. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1516. // ';' and '=' are ordinary characters inside one.
  1517. struct {
  1518. const char *value;
  1519. std::vector<std::pair<const char *, const char *>> expected;
  1520. } cases[] = {
  1521. {"name=\"file1\"; filename=\"a.txt\"",
  1522. {{"name", "file1"}, {"filename", "a.txt"}}},
  1523. // Whitespace around '=' and ';' is still trimmed
  1524. {"name=\"file2\" ;filename = \"a.html\"",
  1525. {{"name", "file2"}, {"filename", "a.html"}}},
  1526. // '=' inside the value used to leave only the text after the last one
  1527. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1528. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1529. {"name=\"x=y\"", {{"name", "x=y"}}},
  1530. // ';' inside the value used to truncate the pair and leave a bogus one
  1531. {"name=\"file3\"; filename=\"a;b.txt\"",
  1532. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1533. // An unquoted value keeps working, and so does filename*
  1534. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1535. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1536. // A parameter with no key is dropped rather than turned into one whose
  1537. // key is the value
  1538. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1539. };
  1540. for (const auto &c : cases) {
  1541. Params params;
  1542. detail::parse_disposition_params(c.value, params);
  1543. for (const auto &kv : c.expected) {
  1544. auto it = params.find(kv.first);
  1545. ASSERT_NE(it, params.end())
  1546. << "value: " << c.value << ", key: " << kv.first;
  1547. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1548. }
  1549. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1550. }
  1551. }
  1552. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1553. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1554. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1555. Server svr;
  1556. std::string field_value, file_name, file_filename;
  1557. bool has_field = false, has_file = false;
  1558. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1559. has_field = req.form.has_field("x=y");
  1560. field_value = req.form.get_field("x=y");
  1561. has_file = req.form.has_file("file1");
  1562. const auto &file = req.form.get_file("file1");
  1563. file_name = file.name;
  1564. file_filename = file.filename;
  1565. res.set_content("ok", "text/plain");
  1566. });
  1567. auto port = svr.bind_to_any_port(HOST);
  1568. thread t = thread([&] { svr.listen_after_bind(); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. t.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. UploadFormDataItems items = {
  1576. {"x=y", "field-value", "", ""},
  1577. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1578. };
  1579. Client cli(HOST, port);
  1580. auto res = cli.Post("/quoted", items);
  1581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1582. ASSERT_EQ(StatusCode::OK_200, res->status);
  1583. EXPECT_TRUE(has_field);
  1584. EXPECT_EQ("field-value", field_value);
  1585. EXPECT_TRUE(has_file);
  1586. EXPECT_EQ("file1", file_name);
  1587. EXPECT_EQ("a;b=report.pdf", file_filename);
  1588. }
  1589. TEST(GetHeaderValueTest, DefaultValue) {
  1590. Headers headers = {{"Dummy", "Dummy"}};
  1591. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1592. EXPECT_STREQ("text/plain", val);
  1593. }
  1594. TEST(GetHeaderValueTest, DefaultValueInt) {
  1595. Headers headers = {{"Dummy", "Dummy"}};
  1596. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1597. EXPECT_EQ(100ull, val);
  1598. }
  1599. TEST(GetHeaderValueTest, RegularValue) {
  1600. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1601. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1602. EXPECT_STREQ("text/html", val);
  1603. }
  1604. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1605. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1606. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1607. EXPECT_STREQ("text/html", val);
  1608. }
  1609. TEST(GetHeaderValueTest, SetContent) {
  1610. Response res;
  1611. res.set_content("html", "text/html");
  1612. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1613. res.set_content("text", "text/plain");
  1614. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1615. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1616. }
  1617. TEST(GetHeaderValueTest, RegularValueInt) {
  1618. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1619. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1620. EXPECT_EQ(100ull, val);
  1621. }
  1622. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1623. Headers headers = {{"Content-Length", "x"}};
  1624. auto is_invalid_value = false;
  1625. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1626. is_invalid_value);
  1627. EXPECT_EQ(0ull, val);
  1628. EXPECT_TRUE(is_invalid_value);
  1629. }
  1630. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1631. // An all-digit value that overflows size_t must be reported as invalid, not
  1632. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1633. // a large length to a small one on 32-bit builds, leaving the framing length
  1634. // wrong while is_invalid_value stayed false.
  1635. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1636. auto is_invalid_value = false;
  1637. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1638. is_invalid_value);
  1639. EXPECT_TRUE(is_invalid_value);
  1640. // A well-formed length is unaffected.
  1641. Headers ok = {{"Content-Length", "1234"}};
  1642. is_invalid_value = false;
  1643. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1644. is_invalid_value);
  1645. EXPECT_EQ(1234ull, val);
  1646. EXPECT_FALSE(is_invalid_value);
  1647. }
  1648. TEST(GetHeaderValueTest, Range) {
  1649. {
  1650. Headers headers = {make_range_header({{1, -1}})};
  1651. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1652. EXPECT_STREQ("bytes=1-", val);
  1653. }
  1654. {
  1655. Headers headers = {make_range_header({{-1, 1}})};
  1656. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1657. EXPECT_STREQ("bytes=-1", val);
  1658. }
  1659. {
  1660. Headers headers = {make_range_header({{1, 10}})};
  1661. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1662. EXPECT_STREQ("bytes=1-10", val);
  1663. }
  1664. {
  1665. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1666. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1667. EXPECT_STREQ("bytes=1-10, 100-", val);
  1668. }
  1669. {
  1670. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1671. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1672. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1673. }
  1674. {
  1675. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1676. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1677. EXPECT_STREQ("bytes=0-0, -1", val);
  1678. }
  1679. }
  1680. TEST(BearerTokenAuthTest, SchemeValidation) {
  1681. // A value shorter than "Bearer " must not throw from the fixed-length
  1682. // substr, and a non-Bearer scheme must not be reported as a token.
  1683. struct {
  1684. const char *value;
  1685. const char *expected;
  1686. } cases[] = {
  1687. {"x", ""},
  1688. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1689. {"Bearer abc123", "abc123"},
  1690. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1691. };
  1692. for (const auto &c : cases) {
  1693. Request req;
  1694. req.set_header("Authorization", c.value);
  1695. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1696. }
  1697. }
  1698. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1699. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1700. // to depend on the standard library (libstdc++ handed back duplicates in
  1701. // reverse insertion order, libc++ in insertion order).
  1702. Request req;
  1703. req.set_header("Accept-Encoding", "gzip");
  1704. req.set_header("Accept-Encoding", "deflate");
  1705. req.set_header("Accept-Encoding", "br");
  1706. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1707. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1708. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1709. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1710. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1711. }
  1712. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1713. Request req;
  1714. req.set_header("X-Test", "only");
  1715. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1716. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1717. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1718. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1719. }
  1720. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1721. Request req;
  1722. req.set_header("X-First", "1");
  1723. req.set_header("X-Test", "2");
  1724. req.params.emplace("first", "1");
  1725. req.params.emplace("test", "2");
  1726. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1727. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1728. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1729. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1730. // The second one is negative when read as a signed value
  1731. const auto max_id = (std::numeric_limits<size_t>::max)();
  1732. for (auto id : {max_id / 2, max_id}) {
  1733. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1734. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1735. EXPECT_EQ("", req.get_param_value("test", id));
  1736. EXPECT_EQ("", req.form.get_field("test", id));
  1737. EXPECT_EQ("", req.form.get_file("test", id).content);
  1738. }
  1739. }
  1740. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1741. Headers headers;
  1742. headers.emplace("Host", "example.com");
  1743. headers.emplace("Accept-Encoding", "gzip");
  1744. headers.emplace("User-Agent", "test");
  1745. headers.emplace("Accept-Encoding", "deflate");
  1746. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1747. "Accept-Encoding=deflate ",
  1748. entries_to_string(headers));
  1749. }
  1750. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1751. Headers headers = {{"Content-Type", "text/html"},
  1752. {"CONTENT-TYPE", "text/xml"}};
  1753. EXPECT_EQ(2U, headers.count("content-type"));
  1754. auto it = headers.find("content-type");
  1755. ASSERT_TRUE(it != headers.end());
  1756. EXPECT_EQ("text/html", it->second);
  1757. }
  1758. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1759. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1760. // drop only those fields and leave everything positioned between them.
  1761. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1762. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1763. auto rng = headers.equal_range("a");
  1764. headers.erase(rng.first, rng.second);
  1765. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1766. }
  1767. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1768. Headers headers = {
  1769. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1770. EXPECT_EQ(3U, headers.erase("A"));
  1771. EXPECT_EQ(0U, headers.count("A"));
  1772. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1773. }
  1774. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1775. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1776. headers.emplace_front("Host", "example.com");
  1777. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1778. entries_to_string(headers));
  1779. }
  1780. TEST(ParseHeaderValueTest, Range) {
  1781. {
  1782. Ranges ranges;
  1783. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1784. EXPECT_TRUE(ret);
  1785. EXPECT_EQ(1u, ranges.size());
  1786. EXPECT_EQ(1u, ranges[0].first);
  1787. EXPECT_EQ(-1, ranges[0].second);
  1788. }
  1789. {
  1790. Ranges ranges;
  1791. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1792. EXPECT_TRUE(ret);
  1793. EXPECT_EQ(1u, ranges.size());
  1794. EXPECT_EQ(-1, ranges[0].first);
  1795. EXPECT_EQ(1u, ranges[0].second);
  1796. }
  1797. {
  1798. Ranges ranges;
  1799. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1800. EXPECT_TRUE(ret);
  1801. EXPECT_EQ(1u, ranges.size());
  1802. EXPECT_EQ(1u, ranges[0].first);
  1803. EXPECT_EQ(10u, ranges[0].second);
  1804. }
  1805. {
  1806. Ranges ranges;
  1807. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1808. EXPECT_FALSE(ret);
  1809. }
  1810. {
  1811. Ranges ranges;
  1812. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1813. EXPECT_TRUE(ret);
  1814. EXPECT_EQ(2u, ranges.size());
  1815. EXPECT_EQ(1u, ranges[0].first);
  1816. EXPECT_EQ(10u, ranges[0].second);
  1817. EXPECT_EQ(100u, ranges[1].first);
  1818. EXPECT_EQ(-1, ranges[1].second);
  1819. }
  1820. {
  1821. Ranges ranges;
  1822. auto ret =
  1823. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1824. EXPECT_TRUE(ret);
  1825. EXPECT_EQ(3u, ranges.size());
  1826. EXPECT_EQ(1u, ranges[0].first);
  1827. EXPECT_EQ(10u, ranges[0].second);
  1828. EXPECT_EQ(100u, ranges[1].first);
  1829. EXPECT_EQ(200u, ranges[1].second);
  1830. EXPECT_EQ(300u, ranges[2].first);
  1831. EXPECT_EQ(400u, ranges[2].second);
  1832. }
  1833. {
  1834. Ranges ranges;
  1835. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1836. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1837. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1838. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1839. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1840. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1841. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1842. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1843. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1844. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1845. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1846. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1847. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1848. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1849. EXPECT_FALSE(
  1850. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1851. EXPECT_TRUE(ranges.empty());
  1852. }
  1853. {
  1854. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1855. // remainder of the representation, so it stays accepted.
  1856. Ranges ranges;
  1857. auto ret =
  1858. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1859. EXPECT_TRUE(ret);
  1860. ASSERT_EQ(1u, ranges.size());
  1861. EXPECT_EQ(0, ranges[0].first);
  1862. EXPECT_EQ(-1, ranges[0].second);
  1863. }
  1864. // RFC 9110 14.1: range unit names are case-insensitive.
  1865. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1866. Ranges ranges;
  1867. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1868. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1869. }
  1870. }
  1871. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1872. Request req;
  1873. req.set_header("Accept-Encoding", "gzip");
  1874. Response res;
  1875. res.set_header("Content-Type", "text/plain");
  1876. auto ret = detail::encoding_type(req, res);
  1877. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1878. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1879. #else
  1880. EXPECT_TRUE(ret == detail::EncodingType::None);
  1881. #endif
  1882. }
  1883. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1884. Request req;
  1885. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1886. Response res;
  1887. res.set_header("Content-Type", "text/plain");
  1888. auto ret = detail::encoding_type(req, res);
  1889. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1890. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1891. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1892. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1893. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1894. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1895. #else
  1896. EXPECT_TRUE(ret == detail::EncodingType::None);
  1897. #endif
  1898. }
  1899. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1900. Request req;
  1901. req.set_header("Accept-Encoding",
  1902. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1903. Response res;
  1904. res.set_header("Content-Type", "text/plain");
  1905. auto ret = detail::encoding_type(req, res);
  1906. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1907. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1908. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1909. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1910. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1911. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1912. #else
  1913. EXPECT_TRUE(ret == detail::EncodingType::None);
  1914. #endif
  1915. }
  1916. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1917. // All supported encodings rejected with q=0 should return None
  1918. Request req;
  1919. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1920. Response res;
  1921. res.set_header("Content-Type", "text/plain");
  1922. auto ret = detail::encoding_type(req, res);
  1923. EXPECT_TRUE(ret == detail::EncodingType::None);
  1924. }
  1925. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1926. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1927. Request req;
  1928. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1929. Response res;
  1930. res.set_header("Content-Type", "text/plain");
  1931. auto ret = detail::encoding_type(req, res);
  1932. EXPECT_TRUE(ret == detail::EncodingType::None);
  1933. }
  1934. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1935. Request req;
  1936. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1937. Response res;
  1938. res.set_header("Content-Type", "text/plain");
  1939. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1940. }
  1941. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1942. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1943. Request req;
  1944. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1945. Response res;
  1946. res.set_header("Content-Type", "text/plain");
  1947. auto ret = detail::encoding_type(req, res);
  1948. EXPECT_TRUE(ret == detail::EncodingType::None);
  1949. }
  1950. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1951. // RFC 7231: Accept-Encoding values are case-insensitive
  1952. Request req;
  1953. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1954. Response res;
  1955. res.set_header("Content-Type", "text/plain");
  1956. auto ret = detail::encoding_type(req, res);
  1957. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1958. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1959. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1960. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1961. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1962. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1963. #else
  1964. EXPECT_TRUE(ret == detail::EncodingType::None);
  1965. #endif
  1966. }
  1967. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1968. // q value should determine priority, not hardcoded order
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1971. Response res;
  1972. res.set_header("Content-Type", "text/plain");
  1973. auto ret = detail::encoding_type(req, res);
  1974. // gzip has highest q=1.0, so it should be selected even though
  1975. // br and zstd are also supported
  1976. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1980. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1981. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1982. #else
  1983. EXPECT_TRUE(ret == detail::EncodingType::None);
  1984. #endif
  1985. }
  1986. TEST(BufferStreamTest, read) {
  1987. detail::BufferStream strm1;
  1988. Stream &strm = strm1;
  1989. EXPECT_EQ(5, strm.write("hello"));
  1990. char buf[512];
  1991. EXPECT_EQ(2, strm.read(buf, 2));
  1992. EXPECT_EQ('h', buf[0]);
  1993. EXPECT_EQ('e', buf[1]);
  1994. EXPECT_EQ(2, strm.read(buf, 2));
  1995. EXPECT_EQ('l', buf[0]);
  1996. EXPECT_EQ('l', buf[1]);
  1997. EXPECT_EQ(1, strm.read(buf, 1));
  1998. EXPECT_EQ('o', buf[0]);
  1999. EXPECT_EQ(0, strm.read(buf, 1));
  2000. }
  2001. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2002. auto host = "www.httpwatch.com";
  2003. auto ip = hosted_at(host);
  2004. EXPECT_EQ("23.96.13.243", ip);
  2005. std::vector<std::string> addrs;
  2006. hosted_at(host, addrs);
  2007. EXPECT_EQ(1u, addrs.size());
  2008. }
  2009. #if 0 // It depends on each test environment...
  2010. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2011. auto host = "www.youtube.com";
  2012. std::vector<std::string> addrs;
  2013. hosted_at(host, addrs);
  2014. EXPECT_EQ(20u, addrs.size());
  2015. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2016. EXPECT_TRUE(it != addrs.end());
  2017. }
  2018. #endif
  2019. class ChunkedEncodingTest : public ::testing::Test {
  2020. protected:
  2021. ChunkedEncodingTest()
  2022. : cli_(HOST, PORT)
  2023. #ifdef CPPHTTPLIB_SSL_ENABLED
  2024. ,
  2025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2026. #endif
  2027. {
  2028. cli_.set_connection_timeout(2);
  2029. #ifdef CPPHTTPLIB_SSL_ENABLED
  2030. cli_.enable_server_certificate_verification(false);
  2031. #endif
  2032. }
  2033. virtual void SetUp() {
  2034. read_file("./image.jpg", image_data_);
  2035. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2036. res.set_content("Hello World!", "text/plain");
  2037. });
  2038. svr_.Get(
  2039. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2040. res.set_chunked_content_provider(
  2041. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2042. size_t remaining = image_data_.size() - offset;
  2043. if (remaining == 0) {
  2044. sink.done();
  2045. } else {
  2046. constexpr size_t CHUNK_SIZE = 1024;
  2047. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2048. sink.write(&image_data_[offset], send_size);
  2049. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2050. }
  2051. return true;
  2052. });
  2053. });
  2054. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2055. svr_.wait_until_ready();
  2056. }
  2057. virtual void TearDown() {
  2058. svr_.stop();
  2059. if (!request_threads_.empty()) {
  2060. std::this_thread::sleep_for(std::chrono::seconds(1));
  2061. for (auto &t : request_threads_) {
  2062. t.join();
  2063. }
  2064. }
  2065. t_.join();
  2066. }
  2067. #ifdef CPPHTTPLIB_SSL_ENABLED
  2068. SSLClient cli_;
  2069. SSLServer svr_;
  2070. #else
  2071. Client cli_;
  2072. Server svr_;
  2073. #endif
  2074. thread t_;
  2075. std::vector<thread> request_threads_;
  2076. std::string image_data_;
  2077. };
  2078. TEST_F(ChunkedEncodingTest, NormalGet) {
  2079. auto res = cli_.Get("/chunked");
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. std::string out;
  2082. read_file("./image.jpg", out);
  2083. EXPECT_EQ(StatusCode::OK_200, res->status);
  2084. EXPECT_EQ(out, res->body);
  2085. }
  2086. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2087. std::string body;
  2088. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2089. body.append(data, data_length);
  2090. return true;
  2091. });
  2092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2093. std::string out;
  2094. read_file("./image.jpg", out);
  2095. EXPECT_EQ(StatusCode::OK_200, res->status);
  2096. EXPECT_EQ(out, body);
  2097. }
  2098. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2099. std::string body;
  2100. auto res = cli_.Get(
  2101. "/chunked",
  2102. [&](const Response &response) {
  2103. EXPECT_EQ(StatusCode::OK_200, response.status);
  2104. return true;
  2105. },
  2106. [&](const char *data, size_t data_length) {
  2107. body.append(data, data_length);
  2108. return true;
  2109. });
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. std::string out;
  2112. read_file("./image.jpg", out);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. EXPECT_EQ(out, body);
  2115. }
  2116. TEST(RangeTest, FromHTTPBin_Online) {
  2117. auto host = "httpbingo.org";
  2118. auto path = std::string{"/range/32"};
  2119. #ifdef CPPHTTPLIB_SSL_ENABLED
  2120. auto port = 443;
  2121. SSLClient cli(host, port);
  2122. #else
  2123. auto port = 80;
  2124. Client cli(host, port);
  2125. #endif
  2126. cli.set_connection_timeout(5);
  2127. {
  2128. auto res = cli.Get(path);
  2129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2130. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2131. EXPECT_EQ(StatusCode::OK_200, res->status);
  2132. }
  2133. {
  2134. Headers headers = {make_range_header({{1, -1}})};
  2135. auto res = cli.Get(path, headers);
  2136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2137. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2139. }
  2140. {
  2141. Headers headers = {make_range_header({{1, 10}})};
  2142. auto res = cli.Get(path, headers);
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("bcdefghijk", res->body);
  2145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2146. }
  2147. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2148. // entire resource, while the original httpbin returned 200. Both are
  2149. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2150. {
  2151. Headers headers = {make_range_header({{0, 31}})};
  2152. auto res = cli.Get(path, headers);
  2153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2154. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2155. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2156. res->status == StatusCode::PartialContent_206);
  2157. }
  2158. {
  2159. Headers headers = {make_range_header({{0, -1}})};
  2160. auto res = cli.Get(path, headers);
  2161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2162. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2163. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2164. res->status == StatusCode::PartialContent_206);
  2165. }
  2166. // go-httpbin returns 206 with clamped range for over-range requests,
  2167. // while the original httpbin returned 416. Both behaviors are observed
  2168. // in real servers, so we only verify the request succeeds.
  2169. {
  2170. Headers headers = {make_range_header({{0, 32}})};
  2171. auto res = cli.Get(path, headers);
  2172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2173. }
  2174. }
  2175. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2176. auto host = "unresolvableaddress.local";
  2177. auto path = std::string{"/"};
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. auto port = 443;
  2180. SSLClient cli(host, port);
  2181. #else
  2182. auto port = 80;
  2183. Client cli(host, port);
  2184. #endif
  2185. cli.set_connection_timeout(1);
  2186. {
  2187. auto res = cli.Get(path);
  2188. ASSERT_FALSE(res);
  2189. }
  2190. std::this_thread::sleep_for(std::chrono::seconds(8));
  2191. }
  2192. #if defined(__linux__) && defined(__GLIBC__) && \
  2193. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2194. // Forward declaration: in split builds split.py strips `inline` and moves the
  2195. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2196. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2197. // against the symbol in both header-only and split builds.
  2198. namespace httplib {
  2199. namespace detail {
  2200. int getaddrinfo_with_timeout(const char *node, const char *service,
  2201. const struct addrinfo *hints,
  2202. struct addrinfo **res, time_t timeout_sec);
  2203. } // namespace detail
  2204. } // namespace httplib
  2205. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2206. //
  2207. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2208. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2209. // gai_suspend() call hits the connection timeout the function calls
  2210. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2211. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2212. // still alive and still references the now-destroyed stack frame.
  2213. //
  2214. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2215. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2216. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2217. // and runs them in a container.
  2218. namespace {
  2219. bool should_run_issue_2431_tests() {
  2220. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2221. return v && *v && std::string(v) != "0";
  2222. }
  2223. std::string unique_unresolvable_host(int n) {
  2224. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2225. // glibc still asks the configured nameserver — which is exactly the path
  2226. // we want to exercise. A unique label per call avoids the resolver cache.
  2227. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2228. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2229. std::to_string(n) + ".invalid";
  2230. }
  2231. } // namespace
  2232. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2233. if (!should_run_issue_2431_tests()) {
  2234. GTEST_SKIP()
  2235. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2236. }
  2237. for (int i = 0; i < 8; ++i) {
  2238. struct addrinfo hints;
  2239. memset(&hints, 0, sizeof(hints));
  2240. hints.ai_family = AF_UNSPEC;
  2241. hints.ai_socktype = SOCK_STREAM;
  2242. auto host = unique_unresolvable_host(i);
  2243. struct addrinfo *result = nullptr;
  2244. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2245. &result, /*timeout_sec=*/1);
  2246. if (rc == 0 && result) { freeaddrinfo(result); }
  2247. }
  2248. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2249. // stack region they still believe holds their gaicb.
  2250. std::this_thread::sleep_for(std::chrono::seconds(3));
  2251. }
  2252. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2253. if (!should_run_issue_2431_tests()) {
  2254. GTEST_SKIP()
  2255. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2256. }
  2257. std::atomic<bool> stop{false};
  2258. std::vector<std::thread> threads;
  2259. for (int t = 0; t < 8; ++t) {
  2260. threads.emplace_back([t, &stop] {
  2261. int i = 0;
  2262. while (!stop.load(std::memory_order_relaxed)) {
  2263. struct addrinfo hints;
  2264. memset(&hints, 0, sizeof(hints));
  2265. hints.ai_family = AF_UNSPEC;
  2266. hints.ai_socktype = SOCK_STREAM;
  2267. auto host = unique_unresolvable_host(t * 100000 + i++);
  2268. struct addrinfo *result = nullptr;
  2269. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2270. &result, /*timeout_sec=*/1);
  2271. if (rc == 0 && result) { freeaddrinfo(result); }
  2272. }
  2273. });
  2274. }
  2275. std::this_thread::sleep_for(std::chrono::seconds(8));
  2276. stop.store(true, std::memory_order_relaxed);
  2277. for (auto &th : threads) {
  2278. th.join();
  2279. }
  2280. std::this_thread::sleep_for(std::chrono::seconds(3));
  2281. }
  2282. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2283. if (!should_run_issue_2431_tests()) {
  2284. GTEST_SKIP()
  2285. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2286. }
  2287. std::atomic<bool> stop{false};
  2288. std::vector<std::thread> threads;
  2289. for (int t = 0; t < 8; ++t) {
  2290. threads.emplace_back([t, &stop] {
  2291. int i = 0;
  2292. while (!stop.load(std::memory_order_relaxed)) {
  2293. auto host = unique_unresolvable_host(t * 100000 + i++);
  2294. Client cli(host, 80);
  2295. cli.set_connection_timeout(1, 0);
  2296. cli.set_read_timeout(1, 0);
  2297. cli.set_write_timeout(1, 0);
  2298. (void)cli.Get("/");
  2299. }
  2300. });
  2301. }
  2302. std::this_thread::sleep_for(std::chrono::seconds(8));
  2303. stop.store(true, std::memory_order_relaxed);
  2304. for (auto &th : threads) {
  2305. th.join();
  2306. }
  2307. std::this_thread::sleep_for(std::chrono::seconds(3));
  2308. }
  2309. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2310. TEST(ConnectionErrorTest, InvalidHost) {
  2311. auto host = "-abcde.com";
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. auto port = 443;
  2314. SSLClient cli(host, port);
  2315. #else
  2316. auto port = 80;
  2317. Client cli(host, port);
  2318. #endif
  2319. cli.set_connection_timeout(std::chrono::seconds(2));
  2320. auto res = cli.Get("/");
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Connection, res.error());
  2323. }
  2324. TEST(ConnectionErrorTest, InvalidHost2) {
  2325. auto host = "httpcan.org/";
  2326. #ifdef CPPHTTPLIB_SSL_ENABLED
  2327. SSLClient cli(host);
  2328. #else
  2329. Client cli(host);
  2330. #endif
  2331. cli.set_connection_timeout(std::chrono::seconds(2));
  2332. auto res = cli.Get("/");
  2333. ASSERT_TRUE(!res);
  2334. EXPECT_EQ(Error::Connection, res.error());
  2335. }
  2336. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2337. auto host = "httpcan.org/";
  2338. #ifdef CPPHTTPLIB_SSL_ENABLED
  2339. SSLClient cli(host);
  2340. #else
  2341. Client cli(host);
  2342. #endif
  2343. cli.set_connection_timeout(std::chrono::seconds(2));
  2344. auto res = cli.Get("/");
  2345. ASSERT_TRUE(!res);
  2346. stringstream s;
  2347. s << "error code: " << res.error();
  2348. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2349. }
  2350. TEST(ConnectionErrorTest, InvalidPort) {
  2351. auto host = "localhost";
  2352. auto port = 44380;
  2353. #ifdef CPPHTTPLIB_SSL_ENABLED
  2354. SSLClient cli(host, port);
  2355. #else
  2356. Client cli(host, port);
  2357. #endif
  2358. cli.set_connection_timeout(std::chrono::seconds(2));
  2359. auto res = cli.Get("/");
  2360. ASSERT_TRUE(!res);
  2361. EXPECT_TRUE(Error::Connection == res.error() ||
  2362. Error::ConnectionTimeout == res.error());
  2363. }
  2364. TEST(ConnectionErrorTest, Timeout_Online) {
  2365. auto host = "google.com";
  2366. #ifdef CPPHTTPLIB_SSL_ENABLED
  2367. auto port = 44380;
  2368. SSLClient cli(host, port);
  2369. #else
  2370. auto port = 8080;
  2371. Client cli(host, port);
  2372. #endif
  2373. cli.set_connection_timeout(std::chrono::seconds(2));
  2374. // only probe one address type so that the error reason
  2375. // correlates to the timed-out IPv4, not the unsupported
  2376. // IPv6 connection attempt
  2377. cli.set_address_family(AF_INET);
  2378. auto res = cli.Get("/");
  2379. ASSERT_TRUE(!res);
  2380. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2381. }
  2382. TEST(CancelTest, NoCancel_Online) {
  2383. auto host = "httpbingo.org";
  2384. auto path = std::string{"/range/32"};
  2385. #ifdef CPPHTTPLIB_SSL_ENABLED
  2386. auto port = 443;
  2387. SSLClient cli(host, port);
  2388. #else
  2389. auto port = 80;
  2390. Client cli(host, port);
  2391. #endif
  2392. cli.set_connection_timeout(std::chrono::seconds(5));
  2393. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2395. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2396. EXPECT_EQ(StatusCode::OK_200, res->status);
  2397. }
  2398. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2399. // Use /bytes with a large payload so that the DownloadProgress callback
  2400. // (which only fires for Content-Length responses) is invoked before the
  2401. // entire body is received, giving cancellation a chance to fire.
  2402. auto host = "httpbingo.org";
  2403. auto path = std::string{"/bytes/524288"};
  2404. #ifdef CPPHTTPLIB_SSL_ENABLED
  2405. auto port = 443;
  2406. SSLClient cli(host, port);
  2407. #else
  2408. auto port = 80;
  2409. Client cli(host, port);
  2410. #endif
  2411. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2412. cli.set_connection_timeout(std::chrono::seconds(5));
  2413. ASSERT_TRUE(!res);
  2414. EXPECT_EQ(Error::Canceled, res.error());
  2415. }
  2416. TEST(CancelTest, WithCancelLargePayload_Online) {
  2417. auto host = "httpbingo.org";
  2418. auto path = std::string{"/bytes/524288"};
  2419. #ifdef CPPHTTPLIB_SSL_ENABLED
  2420. auto port = 443;
  2421. SSLClient cli(host, port);
  2422. #else
  2423. auto port = 80;
  2424. Client cli(host, port);
  2425. #endif
  2426. cli.set_connection_timeout(std::chrono::seconds(5));
  2427. uint32_t count = 0;
  2428. auto res =
  2429. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2430. ASSERT_TRUE(!res);
  2431. EXPECT_EQ(Error::Canceled, res.error());
  2432. }
  2433. TEST(CancelTest, NoCancelPost) {
  2434. Server svr;
  2435. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2436. res.set_content("Hello World!", "text/plain");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, PORT);
  2446. cli.set_connection_timeout(std::chrono::seconds(5));
  2447. auto res =
  2448. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2449. "application/json", [](uint64_t, uint64_t) { return true; });
  2450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2451. EXPECT_EQ("Hello World!", res->body);
  2452. EXPECT_EQ(StatusCode::OK_200, res->status);
  2453. }
  2454. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2455. Server svr;
  2456. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2457. res.set_content("Hello World!", "text/plain");
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. Client cli(HOST, PORT);
  2467. cli.set_connection_timeout(std::chrono::seconds(5));
  2468. auto res =
  2469. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2470. "application/json", [](uint64_t, uint64_t) { return false; });
  2471. ASSERT_TRUE(!res);
  2472. EXPECT_EQ(Error::Canceled, res.error());
  2473. }
  2474. TEST(CancelTest, WithCancelLargePayloadPost) {
  2475. Server svr;
  2476. svr.set_payload_max_length(200 * 1024 * 1024);
  2477. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2478. res.set_content(LARGE_DATA, "text/plain");
  2479. });
  2480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2481. auto se = detail::scope_exit([&] {
  2482. svr.stop();
  2483. thread.join();
  2484. ASSERT_FALSE(svr.is_running());
  2485. });
  2486. svr.wait_until_ready();
  2487. Client cli(HOST, PORT);
  2488. cli.set_payload_max_length(200 * 1024 * 1024);
  2489. cli.set_connection_timeout(std::chrono::seconds(5));
  2490. auto res =
  2491. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2492. "application/json", [](uint64_t, uint64_t) { return false; });
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::Canceled, res.error());
  2495. }
  2496. TEST(CancelTest, NoCancelPut) {
  2497. Server svr;
  2498. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2499. res.set_content("Hello World!", "text/plain");
  2500. });
  2501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2502. auto se = detail::scope_exit([&] {
  2503. svr.stop();
  2504. thread.join();
  2505. ASSERT_FALSE(svr.is_running());
  2506. });
  2507. svr.wait_until_ready();
  2508. Client cli(HOST, PORT);
  2509. cli.set_connection_timeout(std::chrono::seconds(5));
  2510. auto res =
  2511. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2512. "application/json", [](uint64_t, uint64_t) { return true; });
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ("Hello World!", res->body);
  2515. EXPECT_EQ(StatusCode::OK_200, res->status);
  2516. }
  2517. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2518. Server svr;
  2519. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2520. res.set_content("Hello World!", "text/plain");
  2521. });
  2522. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2523. auto se = detail::scope_exit([&] {
  2524. svr.stop();
  2525. thread.join();
  2526. ASSERT_FALSE(svr.is_running());
  2527. });
  2528. svr.wait_until_ready();
  2529. Client cli(HOST, PORT);
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. auto res =
  2532. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2533. "application/json", [](uint64_t, uint64_t) { return false; });
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::Canceled, res.error());
  2536. }
  2537. TEST(CancelTest, WithCancelLargePayloadPut) {
  2538. Server svr;
  2539. svr.set_payload_max_length(200 * 1024 * 1024);
  2540. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2541. res.set_content(LARGE_DATA, "text/plain");
  2542. });
  2543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2544. auto se = detail::scope_exit([&] {
  2545. svr.stop();
  2546. thread.join();
  2547. ASSERT_FALSE(svr.is_running());
  2548. });
  2549. svr.wait_until_ready();
  2550. Client cli(HOST, PORT);
  2551. cli.set_payload_max_length(200 * 1024 * 1024);
  2552. cli.set_connection_timeout(std::chrono::seconds(5));
  2553. auto res =
  2554. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2555. "application/json", [](uint64_t, uint64_t) { return false; });
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::Canceled, res.error());
  2558. }
  2559. TEST(CancelTest, NoCancelPatch) {
  2560. Server svr;
  2561. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("Hello World!", "text/plain");
  2563. });
  2564. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2565. auto se = detail::scope_exit([&] {
  2566. svr.stop();
  2567. thread.join();
  2568. ASSERT_FALSE(svr.is_running());
  2569. });
  2570. svr.wait_until_ready();
  2571. Client cli(HOST, PORT);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return true; });
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. EXPECT_EQ("Hello World!", res->body);
  2578. EXPECT_EQ(StatusCode::OK_200, res->status);
  2579. }
  2580. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2581. Server svr;
  2582. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2583. res.set_content("Hello World!", "text/plain");
  2584. });
  2585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2586. auto se = detail::scope_exit([&] {
  2587. svr.stop();
  2588. thread.join();
  2589. ASSERT_FALSE(svr.is_running());
  2590. });
  2591. svr.wait_until_ready();
  2592. Client cli(HOST, PORT);
  2593. cli.set_connection_timeout(std::chrono::seconds(5));
  2594. auto res =
  2595. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2596. "application/json", [](uint64_t, uint64_t) { return false; });
  2597. ASSERT_TRUE(!res);
  2598. EXPECT_EQ(Error::Canceled, res.error());
  2599. }
  2600. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2601. Server svr;
  2602. svr.set_payload_max_length(200 * 1024 * 1024);
  2603. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2604. res.set_content(LARGE_DATA, "text/plain");
  2605. });
  2606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2607. auto se = detail::scope_exit([&] {
  2608. svr.stop();
  2609. thread.join();
  2610. ASSERT_FALSE(svr.is_running());
  2611. });
  2612. svr.wait_until_ready();
  2613. Client cli(HOST, PORT);
  2614. cli.set_payload_max_length(200 * 1024 * 1024);
  2615. cli.set_connection_timeout(std::chrono::seconds(5));
  2616. auto res =
  2617. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2618. "application/json", [](uint64_t, uint64_t) { return false; });
  2619. ASSERT_TRUE(!res);
  2620. EXPECT_EQ(Error::Canceled, res.error());
  2621. }
  2622. TEST(CancelTest, NoCancelDelete) {
  2623. Server svr;
  2624. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2628. auto se = detail::scope_exit([&] {
  2629. svr.stop();
  2630. thread.join();
  2631. ASSERT_FALSE(svr.is_running());
  2632. });
  2633. svr.wait_until_ready();
  2634. Client cli(HOST, PORT);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return true; });
  2639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2640. EXPECT_EQ("Hello World!", res->body);
  2641. EXPECT_EQ(StatusCode::OK_200, res->status);
  2642. }
  2643. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2644. Server svr;
  2645. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2646. res.set_content("Hello World!", "text/plain");
  2647. });
  2648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. thread.join();
  2652. ASSERT_FALSE(svr.is_running());
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, PORT);
  2656. cli.set_connection_timeout(std::chrono::seconds(5));
  2657. auto res =
  2658. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2659. "application/json", [](uint64_t, uint64_t) { return false; });
  2660. ASSERT_TRUE(!res);
  2661. EXPECT_EQ(Error::Canceled, res.error());
  2662. }
  2663. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2664. Server svr;
  2665. svr.set_payload_max_length(200 * 1024 * 1024);
  2666. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2667. res.set_content(LARGE_DATA, "text/plain");
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. Client cli(HOST, PORT);
  2677. cli.set_payload_max_length(200 * 1024 * 1024);
  2678. cli.set_connection_timeout(std::chrono::seconds(5));
  2679. auto res =
  2680. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2681. "application/json", [](uint64_t, uint64_t) { return false; });
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::Canceled, res.error());
  2684. }
  2685. static std::string remove_whitespace(const std::string &input) {
  2686. std::string output;
  2687. output.reserve(input.size());
  2688. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2689. [](unsigned char c) { return !std::isspace(c); });
  2690. return output;
  2691. }
  2692. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2693. auto host = "httpbingo.org";
  2694. auto path = std::string{"/basic-auth/hello/world"};
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. auto port = 443;
  2697. SSLClient cli(host, port);
  2698. #else
  2699. auto port = 80;
  2700. Client cli(host, port);
  2701. #endif
  2702. {
  2703. auto res = cli.Get(path);
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2706. }
  2707. {
  2708. auto res = cli.Get(
  2709. path, Headers{make_basic_authentication_header("hello", "world")});
  2710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2711. auto body = remove_whitespace(res->body);
  2712. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2713. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2714. EXPECT_EQ(StatusCode::OK_200, res->status);
  2715. }
  2716. {
  2717. cli.set_basic_auth("hello", "world");
  2718. auto res = cli.Get(path);
  2719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2720. auto body = remove_whitespace(res->body);
  2721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2723. EXPECT_EQ(StatusCode::OK_200, res->status);
  2724. }
  2725. {
  2726. cli.set_basic_auth("hello", "bad");
  2727. auto res = cli.Get(path);
  2728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2730. }
  2731. {
  2732. cli.set_basic_auth("bad", "world");
  2733. auto res = cli.Get(path);
  2734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2735. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2736. }
  2737. }
  2738. #ifdef CPPHTTPLIB_SSL_ENABLED
  2739. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2740. auto host = "httpbingo.org";
  2741. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2742. auto paths = std::vector<std::string>{
  2743. "/digest-auth/auth/hello/world/MD5",
  2744. "/digest-auth/auth/hello/world/SHA-256",
  2745. };
  2746. auto port = 443;
  2747. SSLClient cli(host, port);
  2748. {
  2749. auto res = cli.Get(unauth_path);
  2750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2752. }
  2753. {
  2754. cli.set_digest_auth("hello", "world");
  2755. for (const auto &path : paths) {
  2756. auto res = cli.Get(path.c_str());
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. auto body = remove_whitespace(res->body);
  2759. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2760. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. }
  2763. cli.set_digest_auth("hello", "bad");
  2764. for (const auto &path : paths) {
  2765. auto res = cli.Get(path.c_str());
  2766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2767. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2768. }
  2769. }
  2770. }
  2771. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2772. // comma-separated list of challenges, and each challenge may itself carry a
  2773. // comma-separated auth-param list, so a server can legally offer Basic
  2774. // before Digest, either as two field lines or packed into one. Runs one 401
  2775. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2776. // value() joins them in receipt order) and checks that the retry carries a
  2777. // well-formed Digest Authorization header naming expected_realm.
  2778. static void
  2779. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2780. const std::string &expected_realm) {
  2781. std::atomic<int> hits{0};
  2782. Server svr;
  2783. svr.Get("/x", [&](const Request &req, Response &res) {
  2784. if (++hits == 1) {
  2785. res.status = StatusCode::Unauthorized_401;
  2786. for (const auto &challenge : challenges) {
  2787. res.set_header("WWW-Authenticate", challenge);
  2788. }
  2789. } else {
  2790. auto authorization = req.get_header_value("Authorization");
  2791. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2792. EXPECT_NE(std::string::npos,
  2793. authorization.find("realm=\"" + expected_realm + "\""));
  2794. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2795. res.set_content("ok", "text/plain");
  2796. }
  2797. });
  2798. auto port = svr.bind_to_any_port(HOST);
  2799. std::thread t([&]() { svr.listen_after_bind(); });
  2800. auto se = detail::scope_exit([&] {
  2801. svr.stop();
  2802. t.join();
  2803. });
  2804. svr.wait_until_ready();
  2805. Client cli(HOST, port);
  2806. cli.set_digest_auth("hello", "world");
  2807. auto res = cli.Get("/x");
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(2, hits.load());
  2810. }
  2811. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2812. static const char *kDigestChallenge =
  2813. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2814. "algorithm=MD5";
  2815. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2816. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2817. "testrealm");
  2818. }
  2819. // Same challenge list with the schemes in the opposite order, to make sure
  2820. // the fix above didn't just special-case "Basic first".
  2821. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2822. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2823. "testrealm");
  2824. }
  2825. // A comma inside a quoted auth-param value must not be mistaken for the
  2826. // separator between two challenges (or two auth-params).
  2827. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2828. run_digest_challenge_list_test(
  2829. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2830. "algorithm=MD5"},
  2831. "test,realm");
  2832. }
  2833. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2834. // make_digest_authentication_header() dereferences both unconditionally, so
  2835. // a server sending a challenge missing either one must not be treated as
  2836. // usable -- doing so used to crash the client with std::out_of_range.
  2837. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2838. Server svr;
  2839. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2840. res.status = StatusCode::Unauthorized_401;
  2841. res.set_header("WWW-Authenticate", challenge);
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. std::thread t([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. t.join();
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, port);
  2851. cli.set_digest_auth("hello", "world");
  2852. auto res = cli.Get("/x");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2855. }
  2856. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2857. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2858. }
  2859. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2860. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2861. }
  2862. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2863. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2864. }
  2865. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2866. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2867. // when storing the values, so the header builder has to re-escape them (and
  2868. // keep algorithm a bare token); otherwise the value breaks out of its
  2869. // quoted-string and injects extra auth-params into the client's Authorization.
  2870. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2871. std::atomic<int> hits{0};
  2872. std::string authorization;
  2873. Server svr;
  2874. svr.Get("/x", [&](const Request &req, Response &res) {
  2875. if (++hits == 1) {
  2876. res.status = StatusCode::Unauthorized_401;
  2877. // On the wire the quotes embedded in the values are backslash-escaped.
  2878. res.set_header("WWW-Authenticate",
  2879. "Digest realm=\"testrealm\", "
  2880. "nonce=\"n\\\"; injected=\\\"x\", "
  2881. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2882. } else {
  2883. authorization = req.get_header_value("Authorization");
  2884. res.set_content("ok", "text/plain");
  2885. }
  2886. });
  2887. auto port = svr.bind_to_any_port(HOST);
  2888. std::thread t([&]() { svr.listen_after_bind(); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. t.join();
  2892. });
  2893. svr.wait_until_ready();
  2894. Client cli(HOST, port);
  2895. cli.set_digest_auth("hello", "world");
  2896. auto res = cli.Get("/x");
  2897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2898. EXPECT_EQ(2, hits.load());
  2899. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2900. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2901. // inside its quoted-string rather than starting an "injected" auth-param.
  2902. EXPECT_NE(std::string::npos,
  2903. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2904. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2905. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2906. }
  2907. #endif
  2908. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2909. auto host = "google.com";
  2910. auto another_host = "example.com";
  2911. auto wrong_ip = "0.0.0.0";
  2912. #ifdef CPPHTTPLIB_SSL_ENABLED
  2913. SSLClient cli(host);
  2914. #else
  2915. Client cli(host);
  2916. #endif
  2917. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2918. auto res = cli.Get("/");
  2919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2920. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2921. }
  2922. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2923. auto host = "google.com";
  2924. auto wrong_ip = "0.0.0.0";
  2925. #ifdef CPPHTTPLIB_SSL_ENABLED
  2926. SSLClient cli(host);
  2927. #else
  2928. Client cli(host);
  2929. #endif
  2930. cli.set_hostname_addr_map({{host, wrong_ip}});
  2931. auto res = cli.Get("/");
  2932. ASSERT_TRUE(!res);
  2933. EXPECT_EQ(Error::Connection, res.error());
  2934. }
  2935. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2936. // A mapped value that is not an IP literal must be resolved. "localhost"
  2937. // resolves from the hosts file, so this test needs no external DNS.
  2938. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2939. auto host = "target.invalid";
  2940. Server svr;
  2941. std::string received_host;
  2942. svr.Get("/hi", [&](const Request &req, Response &res) {
  2943. received_host = req.get_header_value("Host");
  2944. res.set_content("Hello World!", "text/plain");
  2945. });
  2946. auto port = svr.bind_to_any_port(HOST);
  2947. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2948. auto se = detail::scope_exit([&] {
  2949. svr.stop();
  2950. thread.join();
  2951. ASSERT_FALSE(svr.is_running());
  2952. });
  2953. svr.wait_until_ready();
  2954. Client cli(host, port);
  2955. cli.set_hostname_addr_map({{host, HOST}});
  2956. auto res = cli.Get("/hi");
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. // The mapping only redirects the connection; the identity stays host_.
  2960. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2961. }
  2962. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2963. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2964. auto host = "target.invalid";
  2965. Server svr;
  2966. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2967. res.set_content("Hello World!", "text/plain");
  2968. });
  2969. auto port = svr.bind_to_any_port("127.0.0.1");
  2970. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. thread.join();
  2974. ASSERT_FALSE(svr.is_running());
  2975. });
  2976. svr.wait_until_ready();
  2977. Client cli(host, port);
  2978. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2979. auto res = cli.Get("/hi");
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(StatusCode::OK_200, res->status);
  2982. }
  2983. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2984. // An empty mapped value must leave host_ as the connection target. Without
  2985. // that guard the empty value would become the host argument, getaddrinfo
  2986. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2987. // loopback - silently connecting somewhere the caller never asked for.
  2988. // The server listens on loopback, so such a fallback would succeed and is
  2989. // therefore observable as a failure of this test.
  2990. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2991. Server svr;
  2992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2993. res.set_content("Hello World!", "text/plain");
  2994. });
  2995. auto port = svr.bind_to_any_port(HOST);
  2996. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2997. auto se = detail::scope_exit([&] {
  2998. svr.stop();
  2999. thread.join();
  3000. ASSERT_FALSE(svr.is_running());
  3001. });
  3002. svr.wait_until_ready();
  3003. Client cli(blackhole, port);
  3004. cli.set_hostname_addr_map({{blackhole, ""}});
  3005. cli.set_connection_timeout(1);
  3006. auto res = cli.Get("/hi");
  3007. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3008. }
  3009. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3010. auto host = "httpbingo.org";
  3011. auto path = std::string{"/absolute-redirect/3"};
  3012. #ifdef CPPHTTPLIB_SSL_ENABLED
  3013. SSLClient cli(host);
  3014. #else
  3015. Client cli(host);
  3016. #endif
  3017. cli.set_follow_location(true);
  3018. auto res = cli.Get(path);
  3019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3020. EXPECT_EQ(StatusCode::OK_200, res->status);
  3021. }
  3022. TEST(RedirectTest, Redirect_Online) {
  3023. auto host = "httpbingo.org";
  3024. auto path = std::string{"/redirect/3"};
  3025. #ifdef CPPHTTPLIB_SSL_ENABLED
  3026. SSLClient cli(host);
  3027. #else
  3028. Client cli(host);
  3029. #endif
  3030. cli.set_follow_location(true);
  3031. auto res = cli.Get(path);
  3032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3033. EXPECT_EQ(StatusCode::OK_200, res->status);
  3034. }
  3035. TEST(RelativeRedirectTest, Redirect_Online) {
  3036. auto host = "httpbingo.org";
  3037. auto path = std::string{"/relative-redirect/3"};
  3038. #ifdef CPPHTTPLIB_SSL_ENABLED
  3039. SSLClient cli(host);
  3040. #else
  3041. Client cli(host);
  3042. #endif
  3043. cli.set_follow_location(true);
  3044. auto res = cli.Get(path);
  3045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3046. EXPECT_EQ(StatusCode::OK_200, res->status);
  3047. }
  3048. TEST(TooManyRedirectTest, Redirect_Online) {
  3049. auto host = "httpbingo.org";
  3050. auto path = std::string{"/redirect/21"};
  3051. #ifdef CPPHTTPLIB_SSL_ENABLED
  3052. SSLClient cli(host);
  3053. #else
  3054. Client cli(host);
  3055. #endif
  3056. cli.set_follow_location(true);
  3057. auto res = cli.Get(path);
  3058. ASSERT_TRUE(!res);
  3059. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3060. }
  3061. #ifdef CPPHTTPLIB_SSL_ENABLED
  3062. TEST(YahooRedirectTest, Redirect_Online) {
  3063. Client cli("yahoo.com");
  3064. auto res = cli.Get("/");
  3065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3066. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3067. cli.set_follow_location(true);
  3068. res = cli.Get("/");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3072. }
  3073. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3074. #define REDIR_HOST "httpbingo.org"
  3075. #define REDIR_PATH "/redirect-to"
  3076. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3077. SSLClient cli(REDIR_HOST);
  3078. cli.set_follow_location(true);
  3079. auto res =
  3080. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3082. EXPECT_EQ(StatusCode::OK_200, res->status);
  3083. }
  3084. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3085. SSLClient cli(REDIR_HOST);
  3086. cli.set_follow_location(true);
  3087. Params params;
  3088. params.emplace("url", "http://example.com");
  3089. params.emplace("status_code", "302");
  3090. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. EXPECT_EQ(StatusCode::OK_200, res->status);
  3093. }
  3094. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3095. SSLClient cli(REDIR_HOST);
  3096. cli.set_follow_location(true);
  3097. Params params;
  3098. params.emplace("url", "http://example.com");
  3099. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3101. EXPECT_EQ(StatusCode::OK_200, res->status);
  3102. }
  3103. TEST(UrlWithSpace, Redirect_Online) {
  3104. SSLClient cli("edge.forgecdn.net");
  3105. cli.set_follow_location(true);
  3106. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. EXPECT_EQ(StatusCode::OK_200, res->status);
  3109. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3110. }
  3111. #endif
  3112. #if !defined(_WIN32) && !defined(_WIN64)
  3113. TEST(ReceiveSignals, Signal) {
  3114. auto setupSignalHandlers = []() {
  3115. struct sigaction act;
  3116. sigemptyset(&act.sa_mask);
  3117. act.sa_flags = SA_SIGINFO;
  3118. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3119. switch (sig) {
  3120. case SIGINT:
  3121. default: break;
  3122. }
  3123. };
  3124. ::sigaction(SIGINT, &act, nullptr);
  3125. };
  3126. Server svr;
  3127. int port = 0;
  3128. auto thread = std::thread([&]() {
  3129. setupSignalHandlers();
  3130. port = svr.bind_to_any_port(HOST);
  3131. svr.listen_after_bind();
  3132. });
  3133. auto se = detail::scope_exit([&] {
  3134. svr.stop();
  3135. thread.join();
  3136. ASSERT_FALSE(svr.is_running());
  3137. });
  3138. svr.wait_until_ready();
  3139. ASSERT_TRUE(svr.is_running());
  3140. pthread_kill(thread.native_handle(), SIGINT);
  3141. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3142. ASSERT_TRUE(svr.is_running());
  3143. }
  3144. #endif
  3145. TEST(RedirectToDifferentPort, Redirect) {
  3146. Server svr1;
  3147. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3148. res.set_content("Hello World!", "text/plain");
  3149. });
  3150. int svr1_port = 0;
  3151. auto thread1 = std::thread([&]() {
  3152. svr1_port = svr1.bind_to_any_port(HOST);
  3153. svr1.listen_after_bind();
  3154. });
  3155. Server svr2;
  3156. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3157. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3158. });
  3159. int svr2_port = 0;
  3160. auto thread2 = std::thread([&]() {
  3161. svr2_port = svr2.bind_to_any_port(HOST);
  3162. svr2.listen_after_bind();
  3163. });
  3164. auto se = detail::scope_exit([&] {
  3165. svr2.stop();
  3166. thread2.join();
  3167. svr1.stop();
  3168. thread1.join();
  3169. ASSERT_FALSE(svr2.is_running());
  3170. ASSERT_FALSE(svr1.is_running());
  3171. });
  3172. svr1.wait_until_ready();
  3173. svr2.wait_until_ready();
  3174. Client cli("localhost", svr2_port);
  3175. cli.set_follow_location(true);
  3176. auto res = cli.Get("/2");
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("Hello World!", res->body);
  3180. }
  3181. static void
  3182. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3183. Server svr1;
  3184. std::string captured_authorization;
  3185. svr1.Get("/target", [&](const Request &req, Response &res) {
  3186. captured_authorization = req.get_header_value("Authorization");
  3187. res.set_content("OK", "text/plain");
  3188. });
  3189. int svr1_port = 0;
  3190. auto thread1 = std::thread([&]() {
  3191. svr1_port = svr1.bind_to_any_port(HOST);
  3192. svr1.listen_after_bind();
  3193. });
  3194. Server svr2;
  3195. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3196. res.set_redirect(
  3197. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3198. });
  3199. int svr2_port = 0;
  3200. auto thread2 = std::thread([&]() {
  3201. svr2_port = svr2.bind_to_any_port(HOST);
  3202. svr2.listen_after_bind();
  3203. });
  3204. auto se = detail::scope_exit([&] {
  3205. svr2.stop();
  3206. thread2.join();
  3207. svr1.stop();
  3208. thread1.join();
  3209. ASSERT_FALSE(svr2.is_running());
  3210. ASSERT_FALSE(svr1.is_running());
  3211. });
  3212. svr1.wait_until_ready();
  3213. svr2.wait_until_ready();
  3214. Client cli("localhost", svr2_port);
  3215. cli.set_follow_location(true);
  3216. set_auth(cli);
  3217. auto res = cli.Get("/redir");
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3221. EXPECT_TRUE(captured_authorization.empty());
  3222. }
  3223. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3224. TestDoNotForwardCredentialsOnRedirect(
  3225. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3226. }
  3227. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3228. TestDoNotForwardCredentialsOnRedirect(
  3229. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3230. }
  3231. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3232. Server svr1;
  3233. std::string captured_cookie;
  3234. bool target_hit = false;
  3235. svr1.Get("/target", [&](const Request &req, Response &res) {
  3236. captured_cookie = req.get_header_value("Cookie");
  3237. target_hit = true;
  3238. res.set_content("OK", "text/plain");
  3239. });
  3240. int svr1_port = 0;
  3241. auto thread1 = std::thread([&]() {
  3242. svr1_port = svr1.bind_to_any_port(HOST);
  3243. svr1.listen_after_bind();
  3244. });
  3245. Server svr2;
  3246. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3247. res.set_redirect(
  3248. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3249. });
  3250. int svr2_port = 0;
  3251. auto thread2 = std::thread([&]() {
  3252. svr2_port = svr2.bind_to_any_port(HOST);
  3253. svr2.listen_after_bind();
  3254. });
  3255. auto se = detail::scope_exit([&] {
  3256. svr2.stop();
  3257. thread2.join();
  3258. svr1.stop();
  3259. thread1.join();
  3260. ASSERT_FALSE(svr2.is_running());
  3261. ASSERT_FALSE(svr1.is_running());
  3262. });
  3263. svr1.wait_until_ready();
  3264. svr2.wait_until_ready();
  3265. Client cli("localhost", svr2_port);
  3266. cli.set_follow_location(true);
  3267. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3268. auto res = cli.Get("/redir", headers);
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. EXPECT_TRUE(target_hit);
  3272. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3273. EXPECT_TRUE(captured_cookie.empty());
  3274. }
  3275. TEST(RedirectToSamePort, ForwardCookie) {
  3276. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3277. // header so that ordinary session flows keep working.
  3278. Server svr;
  3279. std::string captured_cookie;
  3280. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3281. res.set_redirect("/target", 302);
  3282. });
  3283. svr.Get("/target", [&](const Request &req, Response &res) {
  3284. captured_cookie = req.get_header_value("Cookie");
  3285. res.set_content("OK", "text/plain");
  3286. });
  3287. auto port = svr.bind_to_any_port(HOST);
  3288. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3289. auto se = detail::scope_exit([&] {
  3290. svr.stop();
  3291. thread.join();
  3292. ASSERT_FALSE(svr.is_running());
  3293. });
  3294. svr.wait_until_ready();
  3295. Client cli(HOST, port);
  3296. cli.set_follow_location(true);
  3297. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3298. auto res = cli.Get("/redir", headers);
  3299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3302. }
  3303. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3304. Server svr;
  3305. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3306. // Port number that overflows int — should not crash
  3307. res.set_redirect("http://localhost:99999999999999999999/target");
  3308. });
  3309. auto port = svr.bind_to_any_port(HOST);
  3310. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. thread.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. svr.wait_until_ready();
  3317. Client cli(HOST, port);
  3318. cli.set_follow_location(true);
  3319. auto res = cli.Get("/redir");
  3320. // Should fail gracefully, not crash (no valid response due to bad port)
  3321. EXPECT_FALSE(res);
  3322. }
  3323. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3324. Server svr;
  3325. auto port = svr.bind_to_any_port(HOST);
  3326. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3327. // The server's own port followed by junk must not be followed
  3328. res.set_redirect("http://" + std::string(HOST) + ":" +
  3329. std::to_string(port) + "junk/target");
  3330. });
  3331. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3332. res.set_content("target", "text/plain");
  3333. });
  3334. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. Client cli(HOST, port);
  3342. cli.set_follow_location(true);
  3343. auto res = cli.Get("/redir");
  3344. EXPECT_FALSE(res);
  3345. }
  3346. TEST(RedirectFromPageWithContent, Redirect) {
  3347. Server svr;
  3348. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3349. res.set_content("___", "text/plain");
  3350. res.set_redirect("/2");
  3351. });
  3352. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3353. res.set_content("Hello World!", "text/plain");
  3354. });
  3355. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3356. auto se = detail::scope_exit([&] {
  3357. svr.stop();
  3358. th.join();
  3359. ASSERT_FALSE(svr.is_running());
  3360. });
  3361. svr.wait_until_ready();
  3362. {
  3363. Client cli("localhost", PORT);
  3364. cli.set_follow_location(true);
  3365. std::string body;
  3366. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3367. body.append(data, data_length);
  3368. return true;
  3369. });
  3370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3371. EXPECT_EQ(StatusCode::OK_200, res->status);
  3372. EXPECT_EQ("Hello World!", body);
  3373. }
  3374. {
  3375. Client cli("localhost", PORT);
  3376. std::string body;
  3377. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3378. body.append(data, data_length);
  3379. return true;
  3380. });
  3381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3382. EXPECT_EQ(StatusCode::Found_302, res->status);
  3383. EXPECT_EQ("___", body);
  3384. }
  3385. }
  3386. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3387. Server svr;
  3388. auto port_str = std::to_string(PORT);
  3389. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3390. auto expected_host = "[::1]:" + port_str;
  3391. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3392. res.set_content("___", "text/plain");
  3393. // res.set_redirect("/2");
  3394. res.set_redirect(redirect_url);
  3395. });
  3396. svr.Get("/2", [&](const Request &req, Response &res) {
  3397. auto host_header = req.headers.find("Host");
  3398. ASSERT_TRUE(host_header != req.headers.end());
  3399. EXPECT_EQ(expected_host, host_header->second);
  3400. res.set_content("Hello World!", "text/plain");
  3401. });
  3402. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3403. auto se = detail::scope_exit([&] {
  3404. svr.stop();
  3405. th.join();
  3406. ASSERT_FALSE(svr.is_running());
  3407. });
  3408. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3409. // actually starts anything, so the condition !svr.is_running() will
  3410. // always remain true, and the loop never stops.
  3411. // This basically counts how many milliseconds have passed since the
  3412. // call to svr.listen(), and if after 5 seconds nothing started yet
  3413. // aborts the test.
  3414. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3415. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3416. ASSERT_LT(milliseconds, 5000U);
  3417. }
  3418. {
  3419. Client cli("::1", PORT);
  3420. cli.set_follow_location(true);
  3421. std::string body;
  3422. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3423. body.append(data, data_length);
  3424. return true;
  3425. });
  3426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("Hello World!", body);
  3429. }
  3430. {
  3431. Client cli("::1", PORT);
  3432. std::string body;
  3433. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3434. body.append(data, data_length);
  3435. return true;
  3436. });
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(StatusCode::Found_302, res->status);
  3439. EXPECT_EQ("___", body);
  3440. }
  3441. }
  3442. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3443. Server svr;
  3444. svr.Get("/foo", [](const Request &req, Response &res) {
  3445. auto a = req.params.find("a");
  3446. if (a != req.params.end()) {
  3447. res.set_content((*a).second, "text/plain");
  3448. res.status = StatusCode::OK_200;
  3449. } else {
  3450. res.status = StatusCode::BadRequest_400;
  3451. }
  3452. });
  3453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. thread.join();
  3457. ASSERT_FALSE(svr.is_running());
  3458. });
  3459. svr.wait_until_ready();
  3460. {
  3461. Client cli(HOST, PORT);
  3462. cli.set_path_encode(false);
  3463. auto res = cli.Get("/foo?a=explicitly+encoded");
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ(StatusCode::OK_200, res->status);
  3466. // This expects it back with a space, as the `+` won't have been
  3467. // url-encoded, and server-side the params get decoded turning `+`
  3468. // into spaces.
  3469. EXPECT_EQ("explicitly encoded", res->body);
  3470. }
  3471. }
  3472. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3473. // When path encoding is disabled the client must transmit the supplied
  3474. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3475. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3476. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3477. // than a space (0x20). Assert on the raw wire target to catch this.
  3478. Server svr;
  3479. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3480. svr.Get("/foo", [&](const Request &req, Response &res) {
  3481. EXPECT_EQ(expected_target, req.target);
  3482. res.status = StatusCode::OK_200;
  3483. });
  3484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. thread.join();
  3488. ASSERT_FALSE(svr.is_running());
  3489. });
  3490. svr.wait_until_ready();
  3491. {
  3492. Client cli(HOST, PORT);
  3493. cli.set_path_encode(false);
  3494. auto res = cli.Get(expected_target.c_str());
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. }
  3498. }
  3499. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3500. // `open_stream()` used to skip the path encoding that the buffered send
  3501. // path applies, so the same `path` produced different bytes in the request
  3502. // line depending on which API was used. Assert the two agree.
  3503. Server svr;
  3504. std::string target;
  3505. svr.Get(".*", [&](const Request &req, Response &res) {
  3506. target = req.target;
  3507. res.status = StatusCode::OK_200;
  3508. });
  3509. auto port = svr.bind_to_any_port(HOST);
  3510. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3511. auto se = detail::scope_exit([&] {
  3512. svr.stop();
  3513. thread.join();
  3514. ASSERT_FALSE(svr.is_running());
  3515. });
  3516. svr.wait_until_ready();
  3517. struct {
  3518. const char *path;
  3519. const char *expected;
  3520. } cases[] = {
  3521. {"/a b?x=1", "/a%20b?x=1"},
  3522. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3523. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3524. };
  3525. for (const auto &c : cases) {
  3526. Client cli(HOST, port);
  3527. target.clear();
  3528. auto res = cli.Get(c.path);
  3529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3530. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3531. auto buffered_target = target;
  3532. target.clear();
  3533. auto handle = cli.open_stream("GET", c.path);
  3534. EXPECT_TRUE(handle.is_valid())
  3535. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3536. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3537. }
  3538. }
  3539. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3540. // The `set_path_encode(false)` contract — transmit the supplied target
  3541. // verbatim — must hold for the streaming API too.
  3542. Server svr;
  3543. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3544. std::string target;
  3545. svr.Get("/foo", [&](const Request &req, Response &res) {
  3546. target = req.target;
  3547. res.status = StatusCode::OK_200;
  3548. });
  3549. auto port = svr.bind_to_any_port(HOST);
  3550. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. svr.wait_until_ready();
  3557. {
  3558. Client cli(HOST, port);
  3559. cli.set_path_encode(false);
  3560. auto handle = cli.open_stream("GET", expected_target);
  3561. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3562. EXPECT_EQ(expected_target, target);
  3563. }
  3564. }
  3565. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3566. // With path encoding enabled a CR/LF in the target is percent-encoded
  3567. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3568. // write_request_line still backstops `set_path_encode(false)`, which is
  3569. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3570. Server svr;
  3571. // Captured before routing: the decoded path contains a newline, which a
  3572. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3573. std::string target;
  3574. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3575. target = req.target;
  3576. res.status = StatusCode::OK_200;
  3577. return Server::HandlerResponse::Handled;
  3578. });
  3579. auto port = svr.bind_to_any_port(HOST);
  3580. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3581. auto se = detail::scope_exit([&] {
  3582. svr.stop();
  3583. thread.join();
  3584. ASSERT_FALSE(svr.is_running());
  3585. });
  3586. svr.wait_until_ready();
  3587. {
  3588. Client cli(HOST, port);
  3589. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3590. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3591. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3592. }
  3593. }
  3594. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3595. // Every control character is percent-encoded, not just CR/LF, so the target
  3596. // passes the request-target check in write_request_line.
  3597. Server svr;
  3598. std::string target;
  3599. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3600. target = req.target;
  3601. res.status = StatusCode::OK_200;
  3602. return Server::HandlerResponse::Handled;
  3603. });
  3604. auto port = svr.bind_to_any_port(HOST);
  3605. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. thread.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. svr.wait_until_ready();
  3612. {
  3613. Client cli(HOST, port);
  3614. auto res = cli.Get("/a\tb\x1b\x7f");
  3615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3616. EXPECT_EQ("/a%09b%1B%7F", target);
  3617. }
  3618. }
  3619. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3620. // Nothing may reach the wire: a raw CR/LF target would split the request
  3621. // line and inject headers.
  3622. Server svr;
  3623. // Pre-routing so that "not called" means nothing reached the server at all,
  3624. // rather than merely failing to match a handler pattern.
  3625. auto handler_called = false;
  3626. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3627. handler_called = true;
  3628. res.status = StatusCode::OK_200;
  3629. return Server::HandlerResponse::Handled;
  3630. });
  3631. auto port = svr.bind_to_any_port(HOST);
  3632. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3633. auto se = detail::scope_exit([&] {
  3634. svr.stop();
  3635. thread.join();
  3636. ASSERT_FALSE(svr.is_running());
  3637. });
  3638. svr.wait_until_ready();
  3639. {
  3640. Client cli(HOST, port);
  3641. cli.set_path_encode(false);
  3642. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3643. EXPECT_FALSE(handle.is_valid());
  3644. EXPECT_EQ(Error::Write, handle.error);
  3645. EXPECT_FALSE(handler_called);
  3646. }
  3647. }
  3648. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3649. // Which of the two branches runs is decided by whether the query component
  3650. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3651. // an empty query and must still fall back to building one from
  3652. // `req.params`, while a non-empty query must win over `req.params`.
  3653. Server svr;
  3654. std::string target;
  3655. svr.Get("/foo", [&](const Request &req, Response &res) {
  3656. target = req.target;
  3657. res.status = StatusCode::OK_200;
  3658. });
  3659. auto port = svr.bind_to_any_port(HOST);
  3660. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3661. auto se = detail::scope_exit([&] {
  3662. svr.stop();
  3663. thread.join();
  3664. ASSERT_FALSE(svr.is_running());
  3665. });
  3666. svr.wait_until_ready();
  3667. {
  3668. // Trailing `?` -> empty query component -> `req.params` is used.
  3669. Client cli(HOST, port);
  3670. Request req;
  3671. req.method = "GET";
  3672. req.path = "/foo?";
  3673. req.params.emplace("a", "1");
  3674. target.clear();
  3675. auto res = cli.send(req);
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ("/foo?a=1", target);
  3678. }
  3679. {
  3680. // Non-empty query in `req.path` -> `req.params` is not appended.
  3681. Client cli(HOST, port);
  3682. Request req;
  3683. req.method = "GET";
  3684. req.path = "/foo?b=2";
  3685. req.params.emplace("a", "1");
  3686. target.clear();
  3687. auto res = cli.send(req);
  3688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3689. EXPECT_EQ("/foo?b=2", target);
  3690. }
  3691. }
  3692. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3693. Server svr;
  3694. svr.Get("/", [](const Request &req, Response &) {
  3695. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3696. });
  3697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3698. auto se = detail::scope_exit([&] {
  3699. svr.stop();
  3700. thread.join();
  3701. ASSERT_FALSE(svr.is_running());
  3702. });
  3703. svr.wait_until_ready();
  3704. {
  3705. Client cli(HOST, PORT);
  3706. cli.set_path_encode(false);
  3707. auto res = cli.Get("/?something=%0A");
  3708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3709. EXPECT_EQ(StatusCode::OK_200, res->status);
  3710. }
  3711. }
  3712. TEST(BindServerTest, BindDualStack) {
  3713. Server svr;
  3714. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3715. res.set_content("Hello World!", "text/plain");
  3716. });
  3717. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3718. auto se = detail::scope_exit([&] {
  3719. svr.stop();
  3720. thread.join();
  3721. ASSERT_FALSE(svr.is_running());
  3722. });
  3723. svr.wait_until_ready();
  3724. {
  3725. Client cli("127.0.0.1", PORT);
  3726. auto res = cli.Get("/1");
  3727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3728. EXPECT_EQ(StatusCode::OK_200, res->status);
  3729. EXPECT_EQ("Hello World!", res->body);
  3730. }
  3731. {
  3732. Client cli("::1", PORT);
  3733. auto res = cli.Get("/1");
  3734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3735. EXPECT_EQ(StatusCode::OK_200, res->status);
  3736. EXPECT_EQ("Hello World!", res->body);
  3737. }
  3738. }
  3739. TEST(BindServerTest, BindAndListenSeparately) {
  3740. Server svr;
  3741. int port = svr.bind_to_any_port("0.0.0.0");
  3742. ASSERT_TRUE(svr.is_valid());
  3743. ASSERT_TRUE(port > 0);
  3744. svr.stop();
  3745. }
  3746. // Reports whether anything is still listening on a loopback port. A plain
  3747. // connect() is used instead of a Client request because a socket left bound by
  3748. // mistake accepts the connection into its backlog and never answers, which
  3749. // would hang the test instead of failing it.
  3750. static bool is_loopback_port_accepting(int port) {
  3751. sockaddr_in addr{};
  3752. addr.sin_family = AF_INET;
  3753. addr.sin_port = htons(static_cast<uint16_t>(port));
  3754. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3755. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3756. EXPECT_NE(sock, INVALID_SOCKET);
  3757. if (sock == INVALID_SOCKET) { return false; }
  3758. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3759. static_cast<socklen_t>(sizeof(addr)));
  3760. detail::close_socket(sock);
  3761. return ret == 0;
  3762. }
  3763. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3764. Server svr;
  3765. auto port = svr.bind_to_any_port("127.0.0.1");
  3766. ASSERT_TRUE(port > 0);
  3767. svr.stop();
  3768. // bind_to_any_port() already called listen(2), so until stop() closed the
  3769. // descriptor the port kept accepting connections into the backlog. ASSERT
  3770. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3771. // below blocks forever in the accept loop.
  3772. ASSERT_FALSE(is_loopback_port_accepting(port));
  3773. // Nothing is left to accept on, so listen_after_bind() must report failure
  3774. // instead of returning success without ever serving.
  3775. EXPECT_FALSE(svr.listen_after_bind());
  3776. // The failed listen marks the server decommissioned, so a waiter returns
  3777. // instead of spinning forever.
  3778. svr.wait_until_ready();
  3779. }
  3780. #ifdef CPPHTTPLIB_SSL_ENABLED
  3781. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3782. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3783. CLIENT_CA_CERT_DIR);
  3784. int port = svr.bind_to_any_port("0.0.0.0");
  3785. ASSERT_TRUE(svr.is_valid());
  3786. ASSERT_TRUE(port > 0);
  3787. svr.stop();
  3788. }
  3789. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3790. // or a rejected CustomRoute() registration would not stop the server binding.
  3791. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3793. CLIENT_CA_CERT_DIR);
  3794. ASSERT_TRUE(svr.is_valid());
  3795. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3796. EXPECT_FALSE(svr.is_valid());
  3797. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3798. }
  3799. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3800. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3801. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3802. int port = svr.bind_to_any_port("0.0.0.0");
  3803. ASSERT_TRUE(svr.is_valid());
  3804. ASSERT_TRUE(port > 0);
  3805. svr.stop();
  3806. }
  3807. TEST(BindServerTest, UpdateCertsPem) {
  3808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3809. int port = svr.bind_to_any_port("0.0.0.0");
  3810. ASSERT_TRUE(svr.is_valid());
  3811. ASSERT_TRUE(port > 0);
  3812. // Read PEM files
  3813. std::string cert_pem, key_pem, ca_pem;
  3814. read_file(SERVER_CERT_FILE, cert_pem);
  3815. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3816. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3817. // Update server certificates using PEM API
  3818. ASSERT_TRUE(
  3819. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3820. ASSERT_TRUE(svr.is_valid());
  3821. svr.stop();
  3822. }
  3823. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3824. // Start server with client CA (enables client auth)
  3825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3826. ASSERT_TRUE(svr.is_valid());
  3827. bool handler_called = false;
  3828. svr.Get("/test", [&](const Request &req, Response &res) {
  3829. handler_called = true;
  3830. // Verify client certificate is present
  3831. auto cert = req.peer_cert();
  3832. EXPECT_TRUE(static_cast<bool>(cert));
  3833. res.set_content("ok", "text/plain");
  3834. });
  3835. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. t.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. // Read PEM files
  3843. std::string cert_pem, key_pem, ca_pem;
  3844. read_file(SERVER_CERT_FILE, cert_pem);
  3845. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3846. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3847. // Update server certificates and client CA using PEM API while server running
  3848. ASSERT_TRUE(
  3849. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3850. // Connect with client certificate
  3851. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3852. cli.enable_server_certificate_verification(false);
  3853. cli.set_connection_timeout(30);
  3854. auto res = cli.Get("/test");
  3855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3856. ASSERT_EQ(StatusCode::OK_200, res->status);
  3857. ASSERT_TRUE(handler_called);
  3858. EXPECT_EQ("ok", res->body);
  3859. }
  3860. #endif
  3861. TEST(ErrorHandlerTest, ContentLength) {
  3862. Server svr;
  3863. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3864. res.status = StatusCode::OK_200;
  3865. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3866. "text/html"); // <= Content-Length still 13
  3867. });
  3868. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3869. res.set_content("Hello World!\n", "text/plain");
  3870. res.status = 524;
  3871. });
  3872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3873. auto se = detail::scope_exit([&] {
  3874. svr.stop();
  3875. thread.join();
  3876. ASSERT_FALSE(svr.is_running());
  3877. });
  3878. svr.wait_until_ready();
  3879. {
  3880. Client cli(HOST, PORT);
  3881. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3883. EXPECT_EQ(StatusCode::OK_200, res->status);
  3884. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3885. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3886. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3887. }
  3888. }
  3889. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3890. TEST(ExceptionTest, WithoutExceptionHandler) {
  3891. Server svr;
  3892. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3893. throw std::runtime_error("exception...");
  3894. });
  3895. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3896. throw std::runtime_error("exception\r\n...");
  3897. });
  3898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3899. auto se = detail::scope_exit([&] {
  3900. svr.stop();
  3901. listen_thread.join();
  3902. ASSERT_FALSE(svr.is_running());
  3903. });
  3904. svr.wait_until_ready();
  3905. Client cli("localhost", PORT);
  3906. {
  3907. auto res = cli.Get("/exception");
  3908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3909. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3910. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3911. }
  3912. {
  3913. auto res = cli.Get("/unknown");
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3916. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3917. }
  3918. }
  3919. TEST(ExceptionTest, WithExceptionHandler) {
  3920. Server svr;
  3921. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3922. std::exception_ptr ep) {
  3923. EXPECT_FALSE(ep == nullptr);
  3924. try {
  3925. std::rethrow_exception(ep);
  3926. } catch (std::exception &e) {
  3927. EXPECT_EQ("abc", std::string(e.what()));
  3928. } catch (...) {}
  3929. res.status = StatusCode::InternalServerError_500;
  3930. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3931. "text/html"); // <= Content-Length still 13 at this point
  3932. });
  3933. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3934. res.set_content("Hello World!\n", "text/plain");
  3935. throw std::runtime_error("abc");
  3936. });
  3937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3938. auto se = detail::scope_exit([&] {
  3939. svr.stop();
  3940. thread.join();
  3941. ASSERT_FALSE(svr.is_running());
  3942. });
  3943. svr.wait_until_ready();
  3944. for (size_t i = 0; i < 10; i++) {
  3945. Client cli(HOST, PORT);
  3946. for (size_t j = 0; j < 100; j++) {
  3947. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3949. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3950. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3951. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3952. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3953. }
  3954. cli.set_keep_alive(true);
  3955. for (size_t j = 0; j < 100; j++) {
  3956. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3958. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3959. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3960. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3961. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3962. }
  3963. }
  3964. }
  3965. TEST(ExceptionTest, AndErrorHandler) {
  3966. Server svr;
  3967. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3968. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3969. });
  3970. svr.set_exception_handler(
  3971. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3972. EXPECT_FALSE(ep == nullptr);
  3973. try {
  3974. std::rethrow_exception(ep);
  3975. } catch (std::exception &e) {
  3976. res.set_content(e.what(), "text/html");
  3977. } catch (...) {}
  3978. res.status = StatusCode::InternalServerError_500;
  3979. });
  3980. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3981. throw std::runtime_error("EXCEPTION");
  3982. });
  3983. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3984. res.set_content("ERROR", "text/html");
  3985. res.status = StatusCode::InternalServerError_500;
  3986. });
  3987. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3988. auto se = detail::scope_exit([&] {
  3989. svr.stop();
  3990. thread.join();
  3991. ASSERT_FALSE(svr.is_running());
  3992. });
  3993. svr.wait_until_ready();
  3994. Client cli(HOST, PORT);
  3995. {
  3996. auto res = cli.Get("/exception");
  3997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3998. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3999. EXPECT_EQ("EXCEPTION", res->body);
  4000. }
  4001. {
  4002. auto res = cli.Get("/error");
  4003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4004. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4005. EXPECT_EQ("ERROR", res->body);
  4006. }
  4007. {
  4008. auto res = cli.Get("/invalid");
  4009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4011. EXPECT_EQ("NOT_FOUND", res->body);
  4012. }
  4013. }
  4014. #endif
  4015. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4016. // process_request() wraps only routing() in a try/catch, so an exception from
  4017. // any other user callback used to unwind into the task queue - which does not
  4018. // catch - and terminate the process. Each test below runs the server on a
  4019. // single worker thread: a guard that catches the exception but still loses the
  4020. // thread would otherwise be hidden by a spare worker serving the follow-up
  4021. // request. Note that a regression here aborts the whole test binary rather
  4022. // than failing one test.
  4023. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4024. Server svr;
  4025. svr.new_task_queue = [] { return new ThreadPool(1); };
  4026. std::atomic<int> reported{0};
  4027. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4028. if (err == Error::UserCallbackException) { reported++; }
  4029. });
  4030. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4031. res.set_content_provider(
  4032. 1024, "text/plain",
  4033. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4034. sink.write("hello", 5);
  4035. throw std::runtime_error("from the content provider");
  4036. });
  4037. });
  4038. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4039. res.set_content("ok", "text/plain");
  4040. });
  4041. auto port = svr.bind_to_any_port(HOST);
  4042. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4043. auto se = detail::scope_exit([&] {
  4044. svr.stop();
  4045. listen_thread.join();
  4046. ASSERT_FALSE(svr.is_running());
  4047. });
  4048. svr.wait_until_ready();
  4049. {
  4050. Client cli(HOST, port);
  4051. cli.set_read_timeout(5, 0);
  4052. EXPECT_FALSE(cli.Get("/throw"));
  4053. }
  4054. EXPECT_TRUE(svr.is_running());
  4055. EXPECT_EQ(1, reported.load());
  4056. // A request on a fresh connection is still served.
  4057. {
  4058. Client cli(HOST, port);
  4059. auto res = cli.Get("/ok");
  4060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4061. EXPECT_EQ(StatusCode::OK_200, res->status);
  4062. EXPECT_EQ("ok", res->body);
  4063. }
  4064. }
  4065. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4066. Server svr;
  4067. svr.new_task_queue = [] { return new ThreadPool(1); };
  4068. std::atomic<bool> should_throw{true};
  4069. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4070. res.set_content("hi", "text/plain");
  4071. });
  4072. svr.set_post_routing_handler(
  4073. [&](const Request & /*req*/, Response & /*res*/) {
  4074. if (should_throw) {
  4075. throw std::runtime_error("from the post-routing handler");
  4076. }
  4077. });
  4078. auto port = svr.bind_to_any_port(HOST);
  4079. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. listen_thread.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. {
  4087. Client cli(HOST, port);
  4088. cli.set_read_timeout(5, 0);
  4089. EXPECT_FALSE(cli.Get("/hi"));
  4090. }
  4091. EXPECT_TRUE(svr.is_running());
  4092. should_throw = false;
  4093. {
  4094. Client cli(HOST, port);
  4095. auto res = cli.Get("/hi");
  4096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4097. EXPECT_EQ(StatusCode::OK_200, res->status);
  4098. EXPECT_EQ("hi", res->body);
  4099. }
  4100. }
  4101. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4102. // The guard reports the caught exception through the error logger, which is
  4103. // a user callback too. A logger that throws has to be contained as well, or
  4104. // the process would terminate from inside the catch.
  4105. Server svr;
  4106. svr.new_task_queue = [] { return new ThreadPool(1); };
  4107. std::atomic<int> reported{0};
  4108. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4109. if (err == Error::UserCallbackException) {
  4110. reported++;
  4111. throw std::runtime_error("from the error logger");
  4112. }
  4113. });
  4114. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4115. res.set_content_provider(
  4116. 1024, "text/plain",
  4117. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4118. sink.write("hello", 5);
  4119. throw std::runtime_error("from the content provider");
  4120. });
  4121. });
  4122. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4123. res.set_content("ok", "text/plain");
  4124. });
  4125. auto port = svr.bind_to_any_port(HOST);
  4126. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4127. auto se = detail::scope_exit([&] {
  4128. svr.stop();
  4129. listen_thread.join();
  4130. ASSERT_FALSE(svr.is_running());
  4131. });
  4132. svr.wait_until_ready();
  4133. {
  4134. Client cli(HOST, port);
  4135. cli.set_read_timeout(5, 0);
  4136. EXPECT_FALSE(cli.Get("/throw"));
  4137. }
  4138. EXPECT_TRUE(svr.is_running());
  4139. EXPECT_EQ(1, reported.load());
  4140. {
  4141. Client cli(HOST, port);
  4142. auto res = cli.Get("/ok");
  4143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4144. EXPECT_EQ(StatusCode::OK_200, res->status);
  4145. EXPECT_EQ("ok", res->body);
  4146. }
  4147. }
  4148. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4149. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4150. // so the exception unwinds through the ws::WebSocket object on its way to
  4151. // the guard. None of the HTTP cases above cross that.
  4152. Server svr;
  4153. svr.new_task_queue = [] { return new ThreadPool(1); };
  4154. std::atomic<int> reported{0};
  4155. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4156. if (err == Error::UserCallbackException) { reported++; }
  4157. });
  4158. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4159. throw std::runtime_error("from the WebSocket handler");
  4160. });
  4161. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4162. res.set_content("ok", "text/plain");
  4163. });
  4164. auto port = svr.bind_to_any_port(HOST);
  4165. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4166. auto se = detail::scope_exit([&] {
  4167. svr.stop();
  4168. listen_thread.join();
  4169. ASSERT_FALSE(svr.is_running());
  4170. });
  4171. svr.wait_until_ready();
  4172. {
  4173. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4174. "/ws");
  4175. auto res = client.connect();
  4176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4177. // The server dropped the connection instead of dying.
  4178. std::string msg;
  4179. EXPECT_FALSE(client.read(msg));
  4180. client.close();
  4181. }
  4182. EXPECT_TRUE(svr.is_running());
  4183. EXPECT_EQ(1, reported.load());
  4184. {
  4185. Client cli(HOST, port);
  4186. auto res = cli.Get("/ok");
  4187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. EXPECT_EQ("ok", res->body);
  4190. }
  4191. }
  4192. #ifdef CPPHTTPLIB_SSL_ENABLED
  4193. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4194. // SSLServer::process_and_close_socket() is a separate overload with its own
  4195. // guard, so it is exercised on its own.
  4196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4197. ASSERT_TRUE(svr.is_valid());
  4198. svr.new_task_queue = [] { return new ThreadPool(1); };
  4199. std::atomic<int> reported{0};
  4200. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4201. if (err == Error::UserCallbackException) { reported++; }
  4202. });
  4203. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4204. res.set_content_provider(
  4205. 1024, "text/plain",
  4206. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4207. sink.write("hello", 5);
  4208. throw std::runtime_error("from the content provider");
  4209. });
  4210. });
  4211. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4212. res.set_content("ok", "text/plain");
  4213. });
  4214. auto port = svr.bind_to_any_port(HOST);
  4215. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4216. auto se = detail::scope_exit([&] {
  4217. svr.stop();
  4218. listen_thread.join();
  4219. ASSERT_FALSE(svr.is_running());
  4220. });
  4221. svr.wait_until_ready();
  4222. {
  4223. SSLClient cli(HOST, port);
  4224. cli.enable_server_certificate_verification(false);
  4225. cli.set_read_timeout(5, 0);
  4226. EXPECT_FALSE(cli.Get("/throw"));
  4227. }
  4228. EXPECT_TRUE(svr.is_running());
  4229. EXPECT_EQ(1, reported.load());
  4230. {
  4231. SSLClient cli(HOST, port);
  4232. cli.enable_server_certificate_verification(false);
  4233. auto res = cli.Get("/ok");
  4234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ("ok", res->body);
  4237. }
  4238. }
  4239. #endif
  4240. #endif
  4241. TEST(NoContentTest, ContentLength) {
  4242. Server svr;
  4243. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4244. res.status = StatusCode::NoContent_204;
  4245. });
  4246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4247. auto se = detail::scope_exit([&] {
  4248. svr.stop();
  4249. thread.join();
  4250. ASSERT_FALSE(svr.is_running());
  4251. });
  4252. svr.wait_until_ready();
  4253. {
  4254. Client cli(HOST, PORT);
  4255. auto res = cli.Get("/hi");
  4256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4257. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4259. }
  4260. }
  4261. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4262. #ifdef CPPHTTPLIB_SSL_ENABLED
  4263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4264. ASSERT_TRUE(svr.is_valid());
  4265. #else
  4266. Server svr;
  4267. #endif
  4268. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4269. if (req.path == "/routing_handler") {
  4270. res.set_header("PRE_ROUTING", "on");
  4271. res.set_content("Routing Handler", "text/plain");
  4272. return httplib::Server::HandlerResponse::Handled;
  4273. }
  4274. return httplib::Server::HandlerResponse::Unhandled;
  4275. });
  4276. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4277. res.set_content("Error", "text/html");
  4278. });
  4279. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4280. if (req.path == "/routing_handler") {
  4281. res.set_header("POST_ROUTING", "on");
  4282. }
  4283. });
  4284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4285. res.set_content("Hello World!\n", "text/plain");
  4286. });
  4287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4288. auto se = detail::scope_exit([&] {
  4289. svr.stop();
  4290. thread.join();
  4291. ASSERT_FALSE(svr.is_running());
  4292. });
  4293. svr.wait_until_ready();
  4294. {
  4295. #ifdef CPPHTTPLIB_SSL_ENABLED
  4296. SSLClient cli(HOST, PORT);
  4297. cli.enable_server_certificate_verification(false);
  4298. #else
  4299. Client cli(HOST, PORT);
  4300. #endif
  4301. auto res = cli.Get("/routing_handler");
  4302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ("Routing Handler", res->body);
  4305. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4306. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4307. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4308. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4309. }
  4310. {
  4311. #ifdef CPPHTTPLIB_SSL_ENABLED
  4312. SSLClient cli(HOST, PORT);
  4313. cli.enable_server_certificate_verification(false);
  4314. #else
  4315. Client cli(HOST, PORT);
  4316. #endif
  4317. auto res = cli.Get("/hi");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. EXPECT_EQ("Hello World!\n", res->body);
  4321. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4322. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4323. }
  4324. {
  4325. #ifdef CPPHTTPLIB_SSL_ENABLED
  4326. SSLClient cli(HOST, PORT);
  4327. cli.enable_server_certificate_verification(false);
  4328. #else
  4329. Client cli(HOST, PORT);
  4330. #endif
  4331. auto res = cli.Get("/aaa");
  4332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4334. EXPECT_EQ("Error", res->body);
  4335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4337. }
  4338. }
  4339. TEST(RequestHandlerTest, PreRequestHandler) {
  4340. auto route_path = "/user/:user";
  4341. Server svr;
  4342. svr.Get("/hi", [](const Request &, Response &res) {
  4343. res.set_content("hi", "text/plain");
  4344. });
  4345. svr.Get(route_path, [](const Request &req, Response &res) {
  4346. res.set_content(req.path_params.at("user"), "text/plain");
  4347. });
  4348. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4349. if (req.matched_route == route_path) {
  4350. auto user = req.path_params.at("user");
  4351. if (user != "john") {
  4352. res.status = StatusCode::Forbidden_403;
  4353. res.set_content("error", "text/html");
  4354. return Server::HandlerResponse::Handled;
  4355. }
  4356. }
  4357. return Server::HandlerResponse::Unhandled;
  4358. });
  4359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4360. auto se = detail::scope_exit([&] {
  4361. svr.stop();
  4362. thread.join();
  4363. ASSERT_FALSE(svr.is_running());
  4364. });
  4365. svr.wait_until_ready();
  4366. Client cli(HOST, PORT);
  4367. {
  4368. auto res = cli.Get("/hi");
  4369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4370. EXPECT_EQ(StatusCode::OK_200, res->status);
  4371. EXPECT_EQ("hi", res->body);
  4372. }
  4373. {
  4374. auto res = cli.Get("/user/john");
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ(StatusCode::OK_200, res->status);
  4377. EXPECT_EQ("john", res->body);
  4378. }
  4379. {
  4380. auto res = cli.Get("/user/invalid-user");
  4381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4382. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4383. EXPECT_EQ("error", res->body);
  4384. }
  4385. }
  4386. // The pre-request handler must run before the request body is read, so a
  4387. // rejected request never forces the server to buffer a (potentially large)
  4388. // body. Here the posted body is larger than the payload limit: if the body
  4389. // were read first the server would answer 413, but because the pre-request
  4390. // handler runs first it answers 403 and the body is never read.
  4391. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4392. Server svr;
  4393. svr.set_payload_max_length(8);
  4394. auto handler_ran = false;
  4395. svr.Post("/reject", [&](const Request &req, Response &res) {
  4396. handler_ran = true;
  4397. res.set_content(req.body, "text/plain");
  4398. });
  4399. svr.Post("/accept", [](const Request &req, Response &res) {
  4400. res.set_content(req.body, "text/plain");
  4401. });
  4402. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4403. if (req.matched_route == "/reject") {
  4404. res.status = StatusCode::Forbidden_403;
  4405. res.set_content("denied", "text/plain");
  4406. return Server::HandlerResponse::Handled;
  4407. }
  4408. return Server::HandlerResponse::Unhandled;
  4409. });
  4410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4411. auto se = detail::scope_exit([&] {
  4412. svr.stop();
  4413. thread.join();
  4414. ASSERT_FALSE(svr.is_running());
  4415. });
  4416. svr.wait_until_ready();
  4417. Client cli(HOST, PORT);
  4418. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4419. // rejects with 403 before the body is read, so 413 is never reached.
  4420. {
  4421. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4424. EXPECT_EQ("denied", res->body);
  4425. EXPECT_FALSE(handler_ran);
  4426. }
  4427. // An approved route still reads the body and enforces the payload limit.
  4428. {
  4429. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4432. }
  4433. }
  4434. TEST(UserDataTest, BasicOperations) {
  4435. httplib::UserData ud;
  4436. // Initially empty
  4437. EXPECT_FALSE(ud.has("key"));
  4438. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4439. // set and get
  4440. ud.set("key", 42);
  4441. EXPECT_TRUE(ud.has("key"));
  4442. auto *p = ud.get<int>("key");
  4443. ASSERT_NE(nullptr, p);
  4444. EXPECT_EQ(42, *p);
  4445. // Type mismatch → nullptr
  4446. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4447. // Overwrite with different type
  4448. ud.set("key", std::string("hello"));
  4449. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4450. auto *s = ud.get<std::string>("key");
  4451. ASSERT_NE(nullptr, s);
  4452. EXPECT_EQ("hello", *s);
  4453. // erase
  4454. ud.erase("key");
  4455. EXPECT_FALSE(ud.has("key"));
  4456. // clear
  4457. ud.set("a", 1);
  4458. ud.set("b", 2);
  4459. ud.clear();
  4460. EXPECT_FALSE(ud.has("a"));
  4461. EXPECT_FALSE(ud.has("b"));
  4462. }
  4463. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4464. struct AuthCtx {
  4465. std::string user_id;
  4466. };
  4467. Server svr;
  4468. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4469. res.user_data.set("auth", AuthCtx{"alice"});
  4470. return Server::HandlerResponse::Unhandled;
  4471. });
  4472. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4473. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4474. ASSERT_NE(nullptr, ctx);
  4475. res.set_content("Hello " + ctx->user_id, "text/plain");
  4476. });
  4477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4478. auto se = detail::scope_exit([&] {
  4479. svr.stop();
  4480. thread.join();
  4481. ASSERT_FALSE(svr.is_running());
  4482. });
  4483. svr.wait_until_ready();
  4484. Client cli(HOST, PORT);
  4485. auto res = cli.Get("/me");
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("Hello alice", res->body);
  4489. }
  4490. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4491. struct RoleCtx {
  4492. std::string role;
  4493. };
  4494. Server svr;
  4495. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4496. res.user_data.set("role", RoleCtx{"admin"});
  4497. return Server::HandlerResponse::Unhandled;
  4498. });
  4499. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4500. auto *ctx = res.user_data.get<RoleCtx>("role");
  4501. ASSERT_NE(nullptr, ctx);
  4502. res.set_content(ctx->role, "text/plain");
  4503. });
  4504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4505. auto se = detail::scope_exit([&] {
  4506. svr.stop();
  4507. thread.join();
  4508. ASSERT_FALSE(svr.is_running());
  4509. });
  4510. svr.wait_until_ready();
  4511. Client cli(HOST, PORT);
  4512. auto res = cli.Get("/role");
  4513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4514. EXPECT_EQ(StatusCode::OK_200, res->status);
  4515. EXPECT_EQ("admin", res->body);
  4516. }
  4517. TEST(InvalidFormatTest, StatusCode) {
  4518. Server svr;
  4519. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4520. res.set_content("Hello World!\n", "text/plain");
  4521. res.status = 9999; // Status should be a three-digit code...
  4522. });
  4523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4524. auto se = detail::scope_exit([&] {
  4525. svr.stop();
  4526. thread.join();
  4527. ASSERT_FALSE(svr.is_running());
  4528. });
  4529. svr.wait_until_ready();
  4530. {
  4531. Client cli(HOST, PORT);
  4532. auto res = cli.Get("/hi");
  4533. ASSERT_FALSE(res);
  4534. }
  4535. }
  4536. TEST(URLFragmentTest, WithFragment) {
  4537. Server svr;
  4538. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4539. EXPECT_TRUE(req.target == "/hi");
  4540. });
  4541. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4542. auto se = detail::scope_exit([&] {
  4543. svr.stop();
  4544. thread.join();
  4545. ASSERT_FALSE(svr.is_running());
  4546. });
  4547. svr.wait_until_ready();
  4548. {
  4549. Client cli(HOST, PORT);
  4550. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4551. EXPECT_TRUE(res);
  4552. EXPECT_EQ(StatusCode::OK_200, res->status);
  4553. res = cli.Get("/hi%23key1=val1=key2=val2");
  4554. EXPECT_TRUE(res);
  4555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4556. }
  4557. }
  4558. TEST(HeaderWriter, SetHeaderWriter) {
  4559. Server svr;
  4560. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4561. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4562. return detail::write_headers(strm, hdrs);
  4563. });
  4564. svr.Get("/hi", [](const Request &req, Response &res) {
  4565. auto it = req.headers.find("CustomClientHeader");
  4566. EXPECT_TRUE(it != req.headers.end());
  4567. EXPECT_EQ(it->second, "CustomClientValue");
  4568. res.set_content("Hello World!\n", "text/plain");
  4569. });
  4570. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4571. auto se = detail::scope_exit([&] {
  4572. svr.stop();
  4573. thread.join();
  4574. ASSERT_FALSE(svr.is_running());
  4575. });
  4576. svr.wait_until_ready();
  4577. {
  4578. Client cli(HOST, PORT);
  4579. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4580. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4581. return detail::write_headers(strm, hdrs);
  4582. });
  4583. auto res = cli.Get("/hi");
  4584. EXPECT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. auto it = res->headers.find("CustomServerHeader");
  4587. EXPECT_TRUE(it != res->headers.end());
  4588. EXPECT_EQ(it->second, "CustomServerValue");
  4589. }
  4590. }
  4591. class ServerTest : public ::testing::Test {
  4592. protected:
  4593. ServerTest()
  4594. : cli_(HOST, PORT)
  4595. #ifdef CPPHTTPLIB_SSL_ENABLED
  4596. ,
  4597. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4598. #endif
  4599. {
  4600. #ifdef CPPHTTPLIB_SSL_ENABLED
  4601. cli_.enable_server_certificate_verification(false);
  4602. #endif
  4603. // Allow LARGE_DATA (100MB) responses
  4604. cli_.set_payload_max_length(200 * 1024 * 1024);
  4605. }
  4606. virtual void SetUp() {
  4607. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4608. svr_.set_payload_max_length(200 * 1024 * 1024);
  4609. svr_.set_mount_point("/", "./www");
  4610. svr_.set_mount_point("/mount", "./www2");
  4611. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4612. svr_.Get("/hi",
  4613. [&](const Request & /*req*/, Response &res) {
  4614. res.set_content("Hello World!", "text/plain");
  4615. })
  4616. .Get("/file_content",
  4617. [&](const Request & /*req*/, Response &res) {
  4618. res.set_file_content("./www/dir/test.html");
  4619. })
  4620. .Get("/file_content_with_content_type",
  4621. [&](const Request & /*req*/, Response &res) {
  4622. res.set_file_content("./www/file", "text/plain");
  4623. })
  4624. .Get("/invalid_file_content",
  4625. [&](const Request & /*req*/, Response &res) {
  4626. res.set_file_content("./www/dir/invalid_file_path");
  4627. })
  4628. .Get("/http_response_splitting",
  4629. [&](const Request & /*req*/, Response &res) {
  4630. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4631. EXPECT_EQ(0U, res.headers.size());
  4632. EXPECT_FALSE(res.has_header("a"));
  4633. res.set_header("a", "1\nSet-Cookie: a=1");
  4634. EXPECT_EQ(0U, res.headers.size());
  4635. EXPECT_FALSE(res.has_header("a"));
  4636. res.set_header("a", "1\rSet-Cookie: a=1");
  4637. EXPECT_EQ(0U, res.headers.size());
  4638. EXPECT_FALSE(res.has_header("a"));
  4639. res.set_header("a\r\nb", "0");
  4640. EXPECT_EQ(0U, res.headers.size());
  4641. EXPECT_FALSE(res.has_header("a"));
  4642. res.set_header("a\rb", "0");
  4643. EXPECT_EQ(0U, res.headers.size());
  4644. EXPECT_FALSE(res.has_header("a"));
  4645. res.set_header("a\nb", "0");
  4646. EXPECT_EQ(0U, res.headers.size());
  4647. EXPECT_FALSE(res.has_header("a"));
  4648. res.set_redirect("1\r\nSet-Cookie: a=1");
  4649. EXPECT_EQ(0U, res.headers.size());
  4650. EXPECT_FALSE(res.has_header("Location"));
  4651. })
  4652. .Get("/slow",
  4653. [&](const Request & /*req*/, Response &res) {
  4654. std::this_thread::sleep_for(std::chrono::seconds(4));
  4655. res.set_content("slow", "text/plain");
  4656. })
  4657. #if 0
  4658. .Post("/slowpost",
  4659. [&](const Request & /*req*/, Response &res) {
  4660. std::this_thread::sleep_for(std::chrono::seconds(2));
  4661. res.set_content("slow", "text/plain");
  4662. })
  4663. #endif
  4664. .Get("/remote_addr",
  4665. [&](const Request &req, Response &res) {
  4666. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4667. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4668. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4669. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4670. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4671. #endif
  4672. res.set_content(req.remote_addr, "text/plain");
  4673. })
  4674. .Get("/local_addr",
  4675. [&](const Request &req, Response &res) {
  4676. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4677. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4678. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4679. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4680. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4681. #endif
  4682. auto local_addr = req.local_addr;
  4683. auto local_port = std::to_string(req.local_port);
  4684. res.set_content(local_addr.append(":").append(local_port),
  4685. "text/plain");
  4686. })
  4687. .Get("/endwith%",
  4688. [&](const Request & /*req*/, Response &res) {
  4689. res.set_content("Hello World!", "text/plain");
  4690. })
  4691. .Get("/a\\+\\+b",
  4692. [&](const Request &req, Response &res) {
  4693. ASSERT_TRUE(req.has_param("a +b"));
  4694. auto val = req.get_param_value("a +b");
  4695. res.set_content(val, "text/plain");
  4696. })
  4697. .Get("/", [&](const Request & /*req*/,
  4698. Response &res) { res.set_redirect("/hi"); })
  4699. .Post("/1",
  4700. [](const Request & /*req*/, Response &res) {
  4701. res.set_redirect("/2", StatusCode::SeeOther_303);
  4702. })
  4703. .Get("/2",
  4704. [](const Request & /*req*/, Response &res) {
  4705. res.set_content("redirected.", "text/plain");
  4706. res.status = StatusCode::OK_200;
  4707. })
  4708. .Post("/person",
  4709. [&](const Request &req, Response &res) {
  4710. if (req.has_param("name") && req.has_param("note")) {
  4711. persons_[req.get_param_value("name")] =
  4712. req.get_param_value("note");
  4713. } else {
  4714. res.status = StatusCode::BadRequest_400;
  4715. }
  4716. })
  4717. .Put("/person",
  4718. [&](const Request &req, Response &res) {
  4719. if (req.has_param("name") && req.has_param("note")) {
  4720. persons_[req.get_param_value("name")] =
  4721. req.get_param_value("note");
  4722. } else {
  4723. res.status = StatusCode::BadRequest_400;
  4724. }
  4725. })
  4726. .Get("/person/(.*)",
  4727. [&](const Request &req, Response &res) {
  4728. string name = req.matches[1];
  4729. if (persons_.find(name) != persons_.end()) {
  4730. auto note = persons_[name];
  4731. res.set_content(note, "text/plain");
  4732. } else {
  4733. res.status = StatusCode::NotFound_404;
  4734. }
  4735. })
  4736. .Delete("/person",
  4737. [&](const Request &req, Response &res) {
  4738. if (req.has_param("name")) {
  4739. string name = req.get_param_value("name");
  4740. if (persons_.find(name) != persons_.end()) {
  4741. persons_.erase(name);
  4742. res.set_content("DELETED", "text/plain");
  4743. } else {
  4744. res.status = StatusCode::NotFound_404;
  4745. }
  4746. } else {
  4747. res.status = StatusCode::BadRequest_400;
  4748. }
  4749. })
  4750. .Post("/x-www-form-urlencoded-json",
  4751. [&](const Request &req, Response &res) {
  4752. auto json = req.get_param_value("json");
  4753. ASSERT_EQ(JSON_DATA, json);
  4754. res.set_content(json, "appliation/json");
  4755. res.status = StatusCode::OK_200;
  4756. })
  4757. .Get("/streamed-chunked",
  4758. [&](const Request & /*req*/, Response &res) {
  4759. res.set_chunked_content_provider(
  4760. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4761. sink.os << "123";
  4762. sink.os << "456";
  4763. sink.os << "789";
  4764. sink.done();
  4765. return true;
  4766. });
  4767. })
  4768. .Get("/streamed-chunked-with-prohibited-trailer",
  4769. [&](const Request & /*req*/, Response &res) {
  4770. auto i = new int(0);
  4771. // Declare both a prohibited trailer (Content-Length) and an
  4772. // allowed one
  4773. res.set_header("Trailer", "Content-Length, X-Allowed");
  4774. res.set_chunked_content_provider(
  4775. "text/plain",
  4776. [i](size_t /*offset*/, DataSink &sink) {
  4777. switch (*i) {
  4778. case 0: sink.os << "123"; break;
  4779. case 1: sink.os << "456"; break;
  4780. case 2: sink.os << "789"; break;
  4781. case 3: {
  4782. sink.done_with_trailer(
  4783. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4784. } break;
  4785. }
  4786. (*i)++;
  4787. return true;
  4788. },
  4789. [i](bool success) {
  4790. EXPECT_TRUE(success);
  4791. delete i;
  4792. });
  4793. })
  4794. .Get("/streamed-chunked2",
  4795. [&](const Request & /*req*/, Response &res) {
  4796. auto i = new int(0);
  4797. res.set_chunked_content_provider(
  4798. "text/plain",
  4799. [i](size_t /*offset*/, DataSink &sink) {
  4800. switch (*i) {
  4801. case 0: sink.os << "123"; break;
  4802. case 1: sink.os << "456"; break;
  4803. case 2: sink.os << "789"; break;
  4804. case 3: sink.done(); break;
  4805. }
  4806. (*i)++;
  4807. return true;
  4808. },
  4809. [i](bool success) {
  4810. EXPECT_TRUE(success);
  4811. delete i;
  4812. });
  4813. })
  4814. .Get("/streamed-chunked-with-trailer",
  4815. [&](const Request & /*req*/, Response &res) {
  4816. auto i = new int(0);
  4817. res.set_header("Trailer", "Dummy1, Dummy2");
  4818. res.set_chunked_content_provider(
  4819. "text/plain",
  4820. [i](size_t /*offset*/, DataSink &sink) {
  4821. switch (*i) {
  4822. case 0: sink.os << "123"; break;
  4823. case 1: sink.os << "456"; break;
  4824. case 2: sink.os << "789"; break;
  4825. case 3: {
  4826. sink.done_with_trailer(
  4827. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4828. } break;
  4829. }
  4830. (*i)++;
  4831. return true;
  4832. },
  4833. [i](bool success) {
  4834. EXPECT_TRUE(success);
  4835. delete i;
  4836. });
  4837. })
  4838. .Get("/streamed",
  4839. [&](const Request & /*req*/, Response &res) {
  4840. res.set_content_provider(
  4841. 6, "text/plain",
  4842. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4843. sink.os << (offset < 3 ? "a" : "b");
  4844. return true;
  4845. });
  4846. })
  4847. .Get("/streamed-without-length",
  4848. [&](const Request & /*req*/, Response &res) {
  4849. auto data = new std::string("abcdefg");
  4850. res.set_content_provider(
  4851. "text/plain",
  4852. [data](size_t offset, DataSink &sink) {
  4853. if (offset < data->size()) {
  4854. sink.os << data->substr(offset);
  4855. }
  4856. sink.done();
  4857. return true;
  4858. },
  4859. [data](bool success) {
  4860. EXPECT_TRUE(success);
  4861. delete data;
  4862. });
  4863. })
  4864. .Get("/streamed-with-range",
  4865. [&](const Request &req, Response &res) {
  4866. auto data = new std::string("abcdefg");
  4867. // An explicit status keeps the server from picking the 206 it
  4868. // would otherwise choose for a ranged request, so the response
  4869. // is not a partial representation.
  4870. auto status = req.get_param_value("status");
  4871. if (status == "200") {
  4872. res.status = StatusCode::OK_200;
  4873. } else if (status == "403") {
  4874. res.status = StatusCode::Forbidden_403;
  4875. }
  4876. res.set_content_provider(
  4877. data->size(), "text/plain",
  4878. [data](size_t offset, size_t length, DataSink &sink) {
  4879. size_t DATA_CHUNK_SIZE = 4;
  4880. const auto &d = *data;
  4881. auto out_len =
  4882. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4883. auto ret =
  4884. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4885. EXPECT_TRUE(ret);
  4886. return true;
  4887. },
  4888. [data, &req](bool success) {
  4889. EXPECT_EQ(success, !req.has_param("error"));
  4890. delete data;
  4891. });
  4892. })
  4893. .Get("/streamed-cancel",
  4894. [&](const Request & /*req*/, Response &res) {
  4895. res.set_content_provider(
  4896. size_t(-1), "text/plain",
  4897. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4898. sink.os << "data_chunk";
  4899. return true;
  4900. });
  4901. })
  4902. .Get("/regex-with-delimiter",
  4903. [&](const Request &req, Response & /*res*/) {
  4904. ASSERT_TRUE(req.has_param("key"));
  4905. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4906. })
  4907. .Get("/with-range",
  4908. [&](const Request & /*req*/, Response &res) {
  4909. res.set_content("abcdefg", "text/plain");
  4910. })
  4911. .Get("/test-start-time",
  4912. [&](const Request &req, Response & /*res*/) {
  4913. EXPECT_NE(req.start_time_,
  4914. std::chrono::steady_clock::time_point::min());
  4915. })
  4916. .Get("/with-range-customized-response",
  4917. [&](const Request & /*req*/, Response &res) {
  4918. res.status = StatusCode::BadRequest_400;
  4919. res.set_content(JSON_DATA, "application/json");
  4920. })
  4921. .Post("/chunked",
  4922. [&](const Request &req, Response & /*res*/) {
  4923. EXPECT_EQ(req.body, "dechunked post body");
  4924. })
  4925. .Post("/large-chunked",
  4926. [&](const Request &req, Response & /*res*/) {
  4927. std::string expected(6 * 30 * 1024u, 'a');
  4928. EXPECT_EQ(req.body, expected);
  4929. })
  4930. .Post("/multipart",
  4931. [&](const Request &req, Response & /*res*/) {
  4932. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4933. req.form.get_field_count("text2") +
  4934. req.form.get_field_count("file3") +
  4935. req.form.get_field_count("file4"));
  4936. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4937. req.form.get_file_count("file2"));
  4938. ASSERT_TRUE(!req.form.has_file("???"));
  4939. ASSERT_TRUE(!req.form.has_field("???"));
  4940. ASSERT_TRUE(req.body.empty());
  4941. {
  4942. const auto &text = req.form.get_field("text1");
  4943. EXPECT_EQ("text default", text);
  4944. }
  4945. {
  4946. const auto &text = req.form.get_field("text2");
  4947. EXPECT_EQ("aωb", text);
  4948. }
  4949. {
  4950. const auto &file = req.form.get_file("file1");
  4951. EXPECT_EQ("hello.txt", file.filename);
  4952. EXPECT_EQ("text/plain", file.content_type);
  4953. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4954. }
  4955. {
  4956. const auto &file = req.form.get_file("file2");
  4957. EXPECT_EQ("world.json", file.filename);
  4958. EXPECT_EQ("application/json", file.content_type);
  4959. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4960. }
  4961. {
  4962. const auto &text = req.form.get_field("file3");
  4963. EXPECT_EQ(0u, text.size());
  4964. }
  4965. {
  4966. const auto &text = req.form.get_field("file4");
  4967. EXPECT_EQ(0u, text.size());
  4968. }
  4969. })
  4970. .Post("/multipart/multi_file_values",
  4971. [&](const Request &req, Response & /*res*/) {
  4972. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4973. req.form.get_field_count("multi_text1"));
  4974. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4975. ASSERT_TRUE(!req.form.has_file("???"));
  4976. ASSERT_TRUE(!req.form.has_field("???"));
  4977. ASSERT_TRUE(req.body.empty());
  4978. {
  4979. const auto &text = req.form.get_field("text");
  4980. EXPECT_EQ("default text", text);
  4981. }
  4982. {
  4983. const auto &text1_values = req.form.get_fields("multi_text1");
  4984. EXPECT_EQ(2u, text1_values.size());
  4985. EXPECT_EQ("aaaaa", text1_values[0]);
  4986. EXPECT_EQ("bbbbb", text1_values[1]);
  4987. }
  4988. {
  4989. const auto &file1_values = req.form.get_files("multi_file1");
  4990. EXPECT_EQ(2u, file1_values.size());
  4991. auto file1 = file1_values[0];
  4992. EXPECT_EQ(file1.filename, "hello.txt");
  4993. EXPECT_EQ(file1.content_type, "text/plain");
  4994. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4995. auto file2 = file1_values[1];
  4996. EXPECT_EQ(file2.filename, "world.json");
  4997. EXPECT_EQ(file2.content_type, "application/json");
  4998. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4999. }
  5000. })
  5001. .Post("/empty",
  5002. [&](const Request &req, Response &res) {
  5003. EXPECT_EQ(req.body, "");
  5004. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5005. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5006. res.set_content("empty", "text/plain");
  5007. })
  5008. .Post("/empty-no-content-type",
  5009. [&](const Request &req, Response &res) {
  5010. EXPECT_EQ(req.body, "");
  5011. EXPECT_FALSE(req.has_header("Content-Type"));
  5012. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5013. res.set_content("empty-no-content-type", "text/plain");
  5014. })
  5015. .Post("/path-only",
  5016. [&](const Request &req, Response &res) {
  5017. EXPECT_EQ(req.body, "");
  5018. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5019. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5020. res.set_content("path-only", "text/plain");
  5021. })
  5022. .Post("/path-headers-only",
  5023. [&](const Request &req, Response &res) {
  5024. EXPECT_EQ(req.body, "");
  5025. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5026. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5027. EXPECT_EQ("world", req.get_header_value("hello"));
  5028. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5029. res.set_content("path-headers-only", "text/plain");
  5030. })
  5031. .Post("/post-large",
  5032. [&](const Request &req, Response &res) {
  5033. EXPECT_EQ(req.body, LARGE_DATA);
  5034. res.set_content(req.body, "text/plain");
  5035. })
  5036. .Post("/post-loopback",
  5037. [&](const Request &, Response &res,
  5038. ContentReader const &content_reader) {
  5039. std::string body;
  5040. content_reader([&](const char *data, size_t data_length) {
  5041. body.append(data, data_length);
  5042. return true;
  5043. });
  5044. res.set_content(body, "text/plain");
  5045. })
  5046. .Put("/put-loopback",
  5047. [&](const Request &, Response &res,
  5048. ContentReader const &content_reader) {
  5049. std::string body;
  5050. content_reader([&](const char *data, size_t data_length) {
  5051. body.append(data, data_length);
  5052. return true;
  5053. });
  5054. res.set_content(body, "text/plain");
  5055. })
  5056. .Patch("/patch-loopback",
  5057. [&](const Request &, Response &res,
  5058. ContentReader const &content_reader) {
  5059. std::string body;
  5060. content_reader([&](const char *data, size_t data_length) {
  5061. body.append(data, data_length);
  5062. return true;
  5063. });
  5064. res.set_content(body, "text/plain");
  5065. })
  5066. .Put("/empty-no-content-type",
  5067. [&](const Request &req, Response &res) {
  5068. EXPECT_EQ(req.body, "");
  5069. EXPECT_FALSE(req.has_header("Content-Type"));
  5070. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5071. res.set_content("empty-no-content-type", "text/plain");
  5072. })
  5073. .Put("/put",
  5074. [&](const Request &req, Response &res) {
  5075. EXPECT_EQ(req.body, "PUT");
  5076. res.set_content(req.body, "text/plain");
  5077. })
  5078. .Put("/put-large",
  5079. [&](const Request &req, Response &res) {
  5080. EXPECT_EQ(req.body, LARGE_DATA);
  5081. res.set_content(req.body, "text/plain");
  5082. })
  5083. .Patch("/patch",
  5084. [&](const Request &req, Response &res) {
  5085. EXPECT_EQ(req.body, "PATCH");
  5086. res.set_content(req.body, "text/plain");
  5087. })
  5088. .Delete("/delete",
  5089. [&](const Request & /*req*/, Response &res) {
  5090. res.set_content("DELETE", "text/plain");
  5091. })
  5092. .Delete("/delete-body",
  5093. [&](const Request &req, Response &res) {
  5094. EXPECT_EQ(req.body, "content");
  5095. res.set_content(req.body, "text/plain");
  5096. })
  5097. .Options(R"(\*)",
  5098. [&](const Request & /*req*/, Response &res) {
  5099. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5100. })
  5101. .CustomRoute("PROPFIND", "/dav/:id",
  5102. [&](const Request &req, Response &res) {
  5103. res.set_header("x-body-size",
  5104. std::to_string(req.body.size()));
  5105. res.set_header("x-matched-route", req.matched_route);
  5106. res.set_header("x-dav-id", req.path_params.at("id"));
  5107. res.status = StatusCode::MultiStatus_207;
  5108. res.set_content(req.body, "application/xml");
  5109. })
  5110. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5111. [&](const Request &req, Response &res) {
  5112. res.set_header("x-dav-match", req.matches[1]);
  5113. res.status = StatusCode::MultiStatus_207;
  5114. })
  5115. .CustomRoute("MKCOL", "/dav-mkcol",
  5116. [&](const Request &req, Response &res) {
  5117. EXPECT_TRUE(req.body.empty());
  5118. res.status = StatusCode::Created_201;
  5119. })
  5120. .CustomRoute(
  5121. "REPORT", "/dav-report",
  5122. [&](const Request & /*req*/, Response &res,
  5123. const ContentReader &content_reader) {
  5124. std::string body;
  5125. content_reader([&](const char *data, size_t data_length) {
  5126. body.append(data, data_length);
  5127. return true;
  5128. });
  5129. res.set_header("x-body-size", std::to_string(body.size()));
  5130. res.status = StatusCode::MultiStatus_207;
  5131. res.set_content(body, "application/xml");
  5132. })
  5133. .Get("/request-target",
  5134. [&](const Request &req, Response & /*res*/) {
  5135. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5136. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5137. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5138. })
  5139. .Get("/long-query-value",
  5140. [&](const Request &req, Response & /*res*/) {
  5141. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5142. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5143. })
  5144. .Get("/too-long-query-value",
  5145. [&](const Request &req, Response & /*res*/) {
  5146. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5147. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5148. })
  5149. .Get("/array-param",
  5150. [&](const Request &req, Response & /*res*/) {
  5151. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5152. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5153. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5154. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5155. })
  5156. .Get("/array-param-values",
  5157. [&](const Request &req, Response & /*res*/) {
  5158. auto values = req.get_param_values("array");
  5159. EXPECT_EQ(3u, values.size());
  5160. EXPECT_EQ("value1", values[0]);
  5161. EXPECT_EQ("value2", values[1]);
  5162. EXPECT_EQ("value3", values[2]);
  5163. auto empty = req.get_param_values("nonexistent");
  5164. EXPECT_TRUE(empty.empty());
  5165. })
  5166. .Post("/validate-no-multiple-headers",
  5167. [&](const Request &req, Response & /*res*/) {
  5168. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5169. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5170. })
  5171. .Post("/content_receiver",
  5172. [&](const Request &req, Response &res,
  5173. const ContentReader &content_reader) {
  5174. if (req.is_multipart_form_data()) {
  5175. std::vector<FormData> items;
  5176. content_reader(
  5177. [&](const FormData &file) {
  5178. items.push_back(file);
  5179. return true;
  5180. },
  5181. [&](const char *data, size_t data_length) {
  5182. items.back().content.append(data, data_length);
  5183. return true;
  5184. });
  5185. EXPECT_EQ(5u, items.size());
  5186. {
  5187. const auto &file = get_file_value(items, "text1");
  5188. EXPECT_TRUE(file.filename.empty());
  5189. EXPECT_EQ("text default", file.content);
  5190. }
  5191. {
  5192. const auto &file = get_file_value(items, "text2");
  5193. EXPECT_TRUE(file.filename.empty());
  5194. EXPECT_EQ("aωb", file.content);
  5195. }
  5196. {
  5197. const auto &file = get_file_value(items, "file1");
  5198. EXPECT_EQ("hello.txt", file.filename);
  5199. EXPECT_EQ("text/plain", file.content_type);
  5200. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5201. }
  5202. {
  5203. const auto &file = get_file_value(items, "file2");
  5204. EXPECT_EQ("world.json", file.filename);
  5205. EXPECT_EQ("application/json", file.content_type);
  5206. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5207. }
  5208. {
  5209. const auto &file = get_file_value(items, "file3");
  5210. EXPECT_TRUE(file.filename.empty());
  5211. EXPECT_EQ("application/octet-stream", file.content_type);
  5212. EXPECT_EQ(0u, file.content.size());
  5213. }
  5214. } else {
  5215. std::string body;
  5216. content_reader([&](const char *data, size_t data_length) {
  5217. EXPECT_EQ(7U, data_length);
  5218. body.append(data, data_length);
  5219. return true;
  5220. });
  5221. EXPECT_EQ(body, "content");
  5222. res.set_content(body, "text/plain");
  5223. }
  5224. })
  5225. .Put("/content_receiver",
  5226. [&](const Request & /*req*/, Response &res,
  5227. const ContentReader &content_reader) {
  5228. std::string body;
  5229. content_reader([&](const char *data, size_t data_length) {
  5230. body.append(data, data_length);
  5231. return true;
  5232. });
  5233. EXPECT_EQ(body, "content");
  5234. res.set_content(body, "text/plain");
  5235. })
  5236. .Patch("/content_receiver",
  5237. [&](const Request & /*req*/, Response &res,
  5238. const ContentReader &content_reader) {
  5239. std::string body;
  5240. content_reader([&](const char *data, size_t data_length) {
  5241. body.append(data, data_length);
  5242. return true;
  5243. });
  5244. EXPECT_EQ(body, "content");
  5245. res.set_content(body, "text/plain");
  5246. })
  5247. .Post("/query-string-and-body",
  5248. [&](const Request &req, Response & /*res*/) {
  5249. ASSERT_TRUE(req.has_param("key"));
  5250. EXPECT_EQ(req.get_param_value("key"), "value");
  5251. EXPECT_EQ(req.body, "content");
  5252. })
  5253. .Get("/last-request",
  5254. [&](const Request &req, Response & /*res*/) {
  5255. EXPECT_EQ("close", req.get_header_value("Connection"));
  5256. })
  5257. .Get(R"(/redirect/(\d+))",
  5258. [&](const Request &req, Response &res) {
  5259. auto num = std::stoi(req.matches[1]) + 1;
  5260. std::string url = "/redirect/" + std::to_string(num);
  5261. res.set_redirect(url);
  5262. })
  5263. .Post("/binary",
  5264. [&](const Request &req, Response &res) {
  5265. EXPECT_EQ(4U, req.body.size());
  5266. EXPECT_EQ("application/octet-stream",
  5267. req.get_header_value("Content-Type"));
  5268. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5269. res.set_content(req.body, "application/octet-stream");
  5270. })
  5271. .Put("/binary",
  5272. [&](const Request &req, Response &res) {
  5273. EXPECT_EQ(4U, req.body.size());
  5274. EXPECT_EQ("application/octet-stream",
  5275. req.get_header_value("Content-Type"));
  5276. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5277. res.set_content(req.body, "application/octet-stream");
  5278. })
  5279. .Patch("/binary",
  5280. [&](const Request &req, Response &res) {
  5281. EXPECT_EQ(4U, req.body.size());
  5282. EXPECT_EQ("application/octet-stream",
  5283. req.get_header_value("Content-Type"));
  5284. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5285. res.set_content(req.body, "application/octet-stream");
  5286. })
  5287. .Delete("/binary",
  5288. [&](const Request &req, Response &res) {
  5289. EXPECT_EQ(4U, req.body.size());
  5290. EXPECT_EQ("application/octet-stream",
  5291. req.get_header_value("Content-Type"));
  5292. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5293. res.set_content(req.body, "application/octet-stream");
  5294. })
  5295. .Get("/issue1772",
  5296. [&](const Request & /*req*/, Response &res) {
  5297. res.status = 401;
  5298. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5299. })
  5300. .Delete("/issue609",
  5301. [](const httplib::Request &, httplib::Response &res,
  5302. const httplib::ContentReader &) {
  5303. res.set_content("ok", "text/plain");
  5304. })
  5305. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5306. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5307. .Get("/compress",
  5308. [&](const Request & /*req*/, Response &res) {
  5309. res.set_content(
  5310. "12345678901234567890123456789012345678901234567890123456789"
  5311. "01234567890123456789012345678901234567890",
  5312. "text/plain");
  5313. })
  5314. .Get("/compress-with-charset",
  5315. [&](const Request & /*req*/, Response &res) {
  5316. res.set_content(
  5317. "12345678901234567890123456789012345678901234567890123456789"
  5318. "01234567890123456789012345678901234567890",
  5319. "application/json; charset=utf-8");
  5320. })
  5321. .Get("/nocompress",
  5322. [&](const Request & /*req*/, Response &res) {
  5323. res.set_content(
  5324. "12345678901234567890123456789012345678901234567890123456789"
  5325. "01234567890123456789012345678901234567890",
  5326. "application/octet-stream");
  5327. })
  5328. .Post("/compress-multipart",
  5329. [&](const Request &req, Response & /*res*/) {
  5330. EXPECT_EQ(2u, req.form.fields.size());
  5331. ASSERT_TRUE(!req.form.has_field("???"));
  5332. {
  5333. const auto &text = req.form.get_field("key1");
  5334. EXPECT_EQ("test", text);
  5335. }
  5336. {
  5337. const auto &text = req.form.get_field("key2");
  5338. EXPECT_EQ("--abcdefg123", text);
  5339. }
  5340. })
  5341. #endif
  5342. ;
  5343. persons_["john"] = "programmer";
  5344. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5345. svr_.wait_until_ready();
  5346. }
  5347. virtual void TearDown() {
  5348. svr_.stop();
  5349. if (!request_threads_.empty()) {
  5350. std::this_thread::sleep_for(std::chrono::seconds(1));
  5351. for (auto &t : request_threads_) {
  5352. t.join();
  5353. }
  5354. }
  5355. t_.join();
  5356. }
  5357. map<string, string> persons_;
  5358. #ifdef CPPHTTPLIB_SSL_ENABLED
  5359. SSLClient cli_;
  5360. SSLServer svr_;
  5361. #else
  5362. Client cli_;
  5363. Server svr_;
  5364. #endif
  5365. thread t_;
  5366. std::vector<thread> request_threads_;
  5367. };
  5368. TEST_F(ServerTest, GetMethod200) {
  5369. auto res = cli_.Get("/hi");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ("HTTP/1.1", res->version);
  5372. EXPECT_EQ(StatusCode::OK_200, res->status);
  5373. EXPECT_EQ("OK", res->reason);
  5374. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5375. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5376. EXPECT_EQ("Hello World!", res->body);
  5377. }
  5378. TEST_F(ServerTest, GetEmptyFile) {
  5379. auto res = cli_.Get("/empty_file");
  5380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5383. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5384. EXPECT_EQ("", res->body);
  5385. }
  5386. TEST_F(ServerTest, GetFileContent) {
  5387. auto res = cli_.Get("/file_content");
  5388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5391. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5392. EXPECT_EQ("test.html", res->body);
  5393. }
  5394. TEST_F(ServerTest, GetFileContentWithRange) {
  5395. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5397. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5398. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5400. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5401. EXPECT_EQ("est", res->body);
  5402. }
  5403. TEST_F(ServerTest, GetFileContentWithContentType) {
  5404. auto res = cli_.Get("/file_content_with_content_type");
  5405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5406. EXPECT_EQ(StatusCode::OK_200, res->status);
  5407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5408. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5409. EXPECT_EQ("file\n", res->body);
  5410. }
  5411. TEST_F(ServerTest, GetInvalidFileContent) {
  5412. auto res = cli_.Get("/invalid_file_content");
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5415. }
  5416. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5417. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5419. EXPECT_EQ("HTTP/1.1", res->version);
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5423. EXPECT_EQ("Hello World!", res->body);
  5424. }
  5425. TEST_F(ServerTest, GetMethod302) {
  5426. auto res = cli_.Get("/");
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::Found_302, res->status);
  5429. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5430. }
  5431. TEST_F(ServerTest, GetMethod302Redirect) {
  5432. cli_.set_follow_location(true);
  5433. auto res = cli_.Get("/");
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ("Hello World!", res->body);
  5437. EXPECT_EQ("/hi", res->location);
  5438. }
  5439. TEST_F(ServerTest, GetMethod404) {
  5440. auto res = cli_.Get("/invalid");
  5441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5442. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5443. }
  5444. TEST_F(ServerTest, HeadMethod200) {
  5445. auto res = cli_.Head("/hi");
  5446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5449. EXPECT_TRUE(res->body.empty());
  5450. }
  5451. TEST_F(ServerTest, HeadMethod200Static) {
  5452. auto res = cli_.Head("/mount/dir/index.html");
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5456. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5457. EXPECT_TRUE(res->body.empty());
  5458. }
  5459. TEST_F(ServerTest, HeadMethod404) {
  5460. auto res = cli_.Head("/invalid");
  5461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5463. EXPECT_TRUE(res->body.empty());
  5464. }
  5465. TEST_F(ServerTest, GetMethodPersonJohn) {
  5466. auto res = cli_.Get("/person/john");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5470. EXPECT_EQ("programmer", res->body);
  5471. }
  5472. TEST_F(ServerTest, PostMethod1) {
  5473. auto res = cli_.Get("/person/john1");
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5476. res = cli_.Post("/person", "name=john1&note=coder",
  5477. "application/x-www-form-urlencoded");
  5478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5479. ASSERT_EQ(StatusCode::OK_200, res->status);
  5480. res = cli_.Get("/person/john1");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::OK_200, res->status);
  5483. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5484. ASSERT_EQ("coder", res->body);
  5485. }
  5486. TEST_F(ServerTest, PostMethod2) {
  5487. auto res = cli_.Get("/person/john2");
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5490. Params params;
  5491. params.emplace("name", "john2");
  5492. params.emplace("note", "coder");
  5493. res = cli_.Post("/person", params);
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. ASSERT_EQ(StatusCode::OK_200, res->status);
  5496. res = cli_.Get("/person/john2");
  5497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5498. ASSERT_EQ(StatusCode::OK_200, res->status);
  5499. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5500. ASSERT_EQ("coder", res->body);
  5501. }
  5502. TEST_F(ServerTest, PutMethod3) {
  5503. auto res = cli_.Get("/person/john3");
  5504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5505. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5506. Params params;
  5507. params.emplace("name", "john3");
  5508. params.emplace("note", "coder");
  5509. res = cli_.Put("/person", params);
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. ASSERT_EQ(StatusCode::OK_200, res->status);
  5512. res = cli_.Get("/person/john3");
  5513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5514. ASSERT_EQ(StatusCode::OK_200, res->status);
  5515. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5516. ASSERT_EQ("coder", res->body);
  5517. }
  5518. TEST_F(ServerTest, DeleteMethod1) {
  5519. auto res = cli_.Get("/person/john4");
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5522. Params params;
  5523. params.emplace("name", "john4");
  5524. params.emplace("note", "coder");
  5525. res = cli_.Post("/person", params);
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. ASSERT_EQ(StatusCode::OK_200, res->status);
  5528. res = cli_.Get("/person/john4");
  5529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5530. ASSERT_EQ(StatusCode::OK_200, res->status);
  5531. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5532. ASSERT_EQ("coder", res->body);
  5533. Params delete_params;
  5534. delete_params.emplace("name", "john4");
  5535. res = cli_.Delete("/person", delete_params);
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. ASSERT_EQ(StatusCode::OK_200, res->status);
  5538. ASSERT_EQ("DELETED", res->body);
  5539. res = cli_.Get("/person/john4");
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5542. }
  5543. TEST_F(ServerTest, DeleteMethod2) {
  5544. auto res = cli_.Get("/person/john5");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5547. Params params;
  5548. params.emplace("name", "john5");
  5549. params.emplace("note", "developer");
  5550. res = cli_.Post("/person", params);
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. ASSERT_EQ(StatusCode::OK_200, res->status);
  5553. res = cli_.Get("/person/john5");
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. ASSERT_EQ(StatusCode::OK_200, res->status);
  5556. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5557. ASSERT_EQ("developer", res->body);
  5558. Params delete_params;
  5559. delete_params.emplace("name", "john5");
  5560. Headers headers;
  5561. headers.emplace("Custom-Header", "test-value");
  5562. res = cli_.Delete("/person", headers, delete_params);
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. ASSERT_EQ(StatusCode::OK_200, res->status);
  5565. ASSERT_EQ("DELETED", res->body);
  5566. res = cli_.Get("/person/john5");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, DeleteMethod3) {
  5571. auto res = cli_.Get("/person/john6");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5574. Params params;
  5575. params.emplace("name", "john6");
  5576. params.emplace("note", "tester");
  5577. res = cli_.Post("/person", params);
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. res = cli_.Get("/person/john6");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. ASSERT_EQ(StatusCode::OK_200, res->status);
  5583. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5584. ASSERT_EQ("tester", res->body);
  5585. Params delete_params;
  5586. delete_params.emplace("name", "john6");
  5587. Headers headers;
  5588. headers.emplace("Custom-Header", "test-value");
  5589. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5591. ASSERT_EQ(StatusCode::OK_200, res->status);
  5592. ASSERT_EQ("DELETED", res->body);
  5593. res = cli_.Get("/person/john6");
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5596. }
  5597. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5598. Params params;
  5599. params.emplace("json", JSON_DATA);
  5600. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. ASSERT_EQ(StatusCode::OK_200, res->status);
  5603. ASSERT_EQ(JSON_DATA, res->body);
  5604. }
  5605. TEST_F(ServerTest, PostEmptyContent) {
  5606. auto res = cli_.Post("/empty", "", "text/plain");
  5607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5608. ASSERT_EQ(StatusCode::OK_200, res->status);
  5609. ASSERT_EQ("empty", res->body);
  5610. }
  5611. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5612. auto res = cli_.Post("/empty-no-content-type");
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. ASSERT_EQ(StatusCode::OK_200, res->status);
  5615. ASSERT_EQ("empty-no-content-type", res->body);
  5616. }
  5617. TEST_F(ServerTest, PostPathOnly) {
  5618. auto res = cli_.Post("/path-only");
  5619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5620. ASSERT_EQ(StatusCode::OK_200, res->status);
  5621. ASSERT_EQ("path-only", res->body);
  5622. }
  5623. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5624. auto res = cli_.Post("/path-headers-only",
  5625. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. ASSERT_EQ(StatusCode::OK_200, res->status);
  5628. ASSERT_EQ("path-headers-only", res->body);
  5629. }
  5630. TEST_F(ServerTest, PostLarge) {
  5631. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. ASSERT_EQ(StatusCode::OK_200, res->status);
  5634. EXPECT_EQ(LARGE_DATA, res->body);
  5635. }
  5636. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5637. auto res = cli_.Put("/empty-no-content-type");
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. ASSERT_EQ(StatusCode::OK_200, res->status);
  5640. ASSERT_EQ("empty-no-content-type", res->body);
  5641. }
  5642. TEST_F(ServerTest, GetMethodDir) {
  5643. auto res = cli_.Get("/dir/");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. EXPECT_EQ(StatusCode::OK_200, res->status);
  5646. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5647. auto body = R"(<html>
  5648. <head>
  5649. </head>
  5650. <body>
  5651. <a href="/dir/test.html">Test</a>
  5652. <a href="/hi">hi</a>
  5653. </body>
  5654. </html>
  5655. )";
  5656. EXPECT_EQ(body, res->body);
  5657. }
  5658. TEST_F(ServerTest, GetMethodDirTest) {
  5659. auto res = cli_.Get("/dir/test.html");
  5660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5661. EXPECT_EQ(StatusCode::OK_200, res->status);
  5662. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5663. EXPECT_EQ("test.html", res->body);
  5664. }
  5665. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5666. auto res = cli_.Get("/dir/../dir/test.html");
  5667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5670. EXPECT_EQ("test.html", res->body);
  5671. }
  5672. TEST_F(ServerTest, GetMethodInvalidPath) {
  5673. auto res = cli_.Get("/dir/../test.html");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5676. }
  5677. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5678. auto res = cli_.Get("/../www/dir/test.html");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5681. }
  5682. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5683. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5685. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5686. }
  5687. TEST_F(ServerTest, GetMethodDirMountTest) {
  5688. auto res = cli_.Get("/mount/dir/test.html");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5692. EXPECT_EQ("test.html", res->body);
  5693. }
  5694. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5695. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5697. EXPECT_EQ(StatusCode::OK_200, res->status);
  5698. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5699. EXPECT_EQ("test.html", res->body);
  5700. }
  5701. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5702. auto res = cli_.Get("/mount/dir/../test.html");
  5703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5705. }
  5706. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5707. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5710. }
  5711. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5712. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5715. }
  5716. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5717. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5720. }
  5721. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5722. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5725. }
  5726. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5727. auto res = cli_.Get("/mount/dir");
  5728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5730. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5731. }
  5732. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5733. auto res = cli_.Get("//dir");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5736. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5737. }
  5738. TEST_F(ServerTest, PostMethod303) {
  5739. auto res = cli_.Post("/1", "body", "text/plain");
  5740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5741. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5742. EXPECT_EQ("/2", res->get_header_value("Location"));
  5743. }
  5744. TEST_F(ServerTest, PostMethod303Redirect) {
  5745. cli_.set_follow_location(true);
  5746. auto res = cli_.Post("/1", "body", "text/plain");
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. EXPECT_EQ(StatusCode::OK_200, res->status);
  5749. EXPECT_EQ("redirected.", res->body);
  5750. EXPECT_EQ("/2", res->location);
  5751. }
  5752. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5753. auto res = cli_.Get("/dir/test.abcde");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5757. EXPECT_EQ("abcde", res->body);
  5758. }
  5759. TEST_F(ServerTest, StaticFileRange) {
  5760. auto res =
  5761. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5763. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5764. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5765. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5766. EXPECT_EQ(true, res->has_header("Content-Range"));
  5767. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5768. EXPECT_EQ(std::string("cd"), res->body);
  5769. }
  5770. TEST_F(ServerTest, StaticFileRanges) {
  5771. auto res = cli_.Get("/dir/test.abcde",
  5772. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5774. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5775. EXPECT_TRUE(
  5776. res->get_header_value("Content-Type")
  5777. .find(
  5778. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5779. 0);
  5780. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5781. }
  5782. TEST_F(ServerTest, StaticFileRangeHead) {
  5783. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5786. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5787. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5788. EXPECT_EQ(true, res->has_header("Content-Range"));
  5789. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5790. }
  5791. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5792. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5795. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5796. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5797. EXPECT_EQ(true, res->has_header("Content-Range"));
  5798. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5799. res->get_header_value("Content-Range"));
  5800. EXPECT_EQ("LAST\n", res->body);
  5801. }
  5802. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5803. auto res =
  5804. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5807. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5808. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5809. EXPECT_EQ(true, res->has_header("Content-Range"));
  5810. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5811. }
  5812. TEST_F(ServerTest, StaticFileBigFile) {
  5813. auto res = cli_.Get("/dir/1MB.txt");
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::OK_200, res->status);
  5816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5817. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5818. }
  5819. TEST_F(ServerTest, InvalidBaseDirMount) {
  5820. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5821. }
  5822. TEST_F(ServerTest, Binary) {
  5823. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5824. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5825. "application/octet-stream");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. ASSERT_EQ(StatusCode::OK_200, res->status);
  5828. ASSERT_EQ(4U, res->body.size());
  5829. res = cli_.Put("/binary", binary.data(), binary.size(),
  5830. "application/octet-stream");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. ASSERT_EQ(StatusCode::OK_200, res->status);
  5833. ASSERT_EQ(4U, res->body.size());
  5834. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5835. "application/octet-stream");
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. ASSERT_EQ(StatusCode::OK_200, res->status);
  5838. ASSERT_EQ(4U, res->body.size());
  5839. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5840. "application/octet-stream");
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. ASSERT_EQ(StatusCode::OK_200, res->status);
  5843. ASSERT_EQ(4U, res->body.size());
  5844. }
  5845. TEST_F(ServerTest, BinaryString) {
  5846. auto binary = std::string("\x00\x01\x02\x03", 4);
  5847. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5849. ASSERT_EQ(StatusCode::OK_200, res->status);
  5850. ASSERT_EQ(4U, res->body.size());
  5851. res = cli_.Put("/binary", binary, "application/octet-stream");
  5852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5853. ASSERT_EQ(StatusCode::OK_200, res->status);
  5854. ASSERT_EQ(4U, res->body.size());
  5855. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. ASSERT_EQ(StatusCode::OK_200, res->status);
  5858. ASSERT_EQ(4U, res->body.size());
  5859. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5861. ASSERT_EQ(StatusCode::OK_200, res->status);
  5862. ASSERT_EQ(4U, res->body.size());
  5863. }
  5864. TEST_F(ServerTest, EmptyRequest) {
  5865. auto res = cli_.Get("");
  5866. ASSERT_TRUE(!res);
  5867. EXPECT_EQ(Error::Connection, res.error());
  5868. }
  5869. TEST_F(ServerTest, LongRequest) {
  5870. std::string request;
  5871. for (size_t i = 0; i < 545; i++) {
  5872. request += "/TooLongRequest";
  5873. }
  5874. request += "OK";
  5875. auto res = cli_.Get(request.c_str());
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5878. }
  5879. TEST_F(ServerTest, TooLongRequest) {
  5880. std::string request;
  5881. for (size_t i = 0; i < 546; i++) {
  5882. request += "/TooLongRequest";
  5883. }
  5884. request += "_NG";
  5885. auto start = std::chrono::high_resolution_clock::now();
  5886. cli_.set_keep_alive(true);
  5887. auto res = cli_.Get(request.c_str());
  5888. auto end = std::chrono::high_resolution_clock::now();
  5889. auto elapsed =
  5890. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5891. .count();
  5892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5893. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5894. EXPECT_LE(elapsed, 1000);
  5895. EXPECT_EQ("close", res->get_header_value("Connection"));
  5896. EXPECT_FALSE(cli_.is_socket_open());
  5897. }
  5898. TEST_F(ServerTest, AlmostTooLongRequest) {
  5899. // test for #2046 - URI length check shouldn't include other content on req
  5900. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5901. // leading /, space, HTTP/1.1)
  5902. std::string request =
  5903. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5904. auto res = cli_.Get(request.c_str());
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5907. }
  5908. TEST_F(ServerTest, LongHeader) {
  5909. Request req;
  5910. req.method = "GET";
  5911. req.path = "/hi";
  5912. std::string host_and_port;
  5913. host_and_port += HOST;
  5914. host_and_port += ":";
  5915. host_and_port += std::to_string(PORT);
  5916. req.headers.emplace("Host", host_and_port.c_str());
  5917. req.headers.emplace("Accept", "*/*");
  5918. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5919. req.headers.emplace(
  5920. "Header-Name",
  5921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5949. "@@@@@@@@@@@@@@@@");
  5950. auto res = std::make_shared<Response>();
  5951. auto error = Error::Success;
  5952. auto ret = cli_.send(req, *res, error);
  5953. ASSERT_TRUE(ret);
  5954. EXPECT_EQ(StatusCode::OK_200, res->status);
  5955. }
  5956. TEST_F(ServerTest, LongQueryValue) {
  5957. auto start = std::chrono::high_resolution_clock::now();
  5958. cli_.set_keep_alive(true);
  5959. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5960. auto end = std::chrono::high_resolution_clock::now();
  5961. auto elapsed =
  5962. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5963. .count();
  5964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5965. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5966. EXPECT_LE(elapsed, 1000);
  5967. EXPECT_EQ("close", res->get_header_value("Connection"));
  5968. EXPECT_FALSE(cli_.is_socket_open());
  5969. }
  5970. TEST_F(ServerTest, TooLongQueryValue) {
  5971. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5972. ASSERT_FALSE(res);
  5973. EXPECT_EQ(Error::Read, res.error());
  5974. }
  5975. TEST_F(ServerTest, TooLongHeader) {
  5976. Request req;
  5977. req.method = "GET";
  5978. req.path = "/hi";
  5979. std::string host_and_port;
  5980. host_and_port += HOST;
  5981. host_and_port += ":";
  5982. host_and_port += std::to_string(PORT);
  5983. req.headers.emplace("Host", host_and_port.c_str());
  5984. req.headers.emplace("Accept", "*/*");
  5985. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5986. req.headers.emplace(
  5987. "Header-Name",
  5988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6016. "@@@@@@@@@@@@@@@@@");
  6017. auto res = std::make_shared<Response>();
  6018. auto error = Error::Success;
  6019. auto ret = cli_.send(req, *res, error);
  6020. ASSERT_TRUE(ret);
  6021. EXPECT_EQ(StatusCode::OK_200, res->status);
  6022. }
  6023. TEST_F(ServerTest, HeaderCountAtLimit) {
  6024. // Test with headers just under the 100 limit
  6025. httplib::Headers headers;
  6026. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6027. // This should keep us just under the 100 header limit
  6028. for (int i = 0; i < 95; i++) {
  6029. std::string name = "X-Test-Header-" + std::to_string(i);
  6030. std::string value = "value" + std::to_string(i);
  6031. headers.emplace(name, value);
  6032. }
  6033. // This should work fine as we're under the limit
  6034. auto res = cli_.Get("/hi", headers);
  6035. EXPECT_TRUE(res);
  6036. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6037. }
  6038. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6039. // Test with many headers to exceed the 100 limit
  6040. httplib::Headers headers;
  6041. // Add 150 headers to definitely exceed the 100 limit
  6042. for (int i = 0; i < 150; i++) {
  6043. std::string name = "X-Test-Header-" + std::to_string(i);
  6044. std::string value = "value" + std::to_string(i);
  6045. headers.emplace(name, value);
  6046. }
  6047. // This should fail due to exceeding header count limit
  6048. cli_.set_keep_alive(true);
  6049. auto res = cli_.Get("/hi", headers);
  6050. // The server should respond with 400 Bad Request
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6053. EXPECT_EQ("close", res->get_header_value("Connection"));
  6054. EXPECT_FALSE(cli_.is_socket_open());
  6055. }
  6056. TEST_F(ServerTest, PercentEncoding) {
  6057. auto res = cli_.Get("/e%6edwith%");
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. }
  6061. TEST_F(ServerTest, PercentEncodingUnicode) {
  6062. auto res = cli_.Get("/e%u006edwith%");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. }
  6066. TEST_F(ServerTest, InvalidPercentEncoding) {
  6067. auto res = cli_.Get("/%endwith%");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6070. }
  6071. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6072. auto res = cli_.Get("/%uendwith%");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6075. }
  6076. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6077. auto res = cli_.Get("/hello?aaa=bbb%");
  6078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6079. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6080. }
  6081. TEST_F(ServerTest, PlusSignEncoding) {
  6082. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ("a +b", res->body);
  6086. }
  6087. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6088. // This test simulates a potential DoS attack using many headers
  6089. // to verify our security fix prevents memory exhaustion
  6090. httplib::Headers attack_headers;
  6091. // Attempt to add many headers like an attacker would (200 headers to far
  6092. // exceed limit)
  6093. for (int i = 0; i < 200; i++) {
  6094. std::string name = "X-Attack-Header-" + std::to_string(i);
  6095. std::string value = "attack_payload_" + std::to_string(i);
  6096. attack_headers.emplace(name, value);
  6097. }
  6098. // Try to POST with excessive headers
  6099. cli_.set_keep_alive(true);
  6100. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6101. // Should either fail or return 400 Bad Request due to security limit
  6102. if (res) {
  6103. // If we get a response, it should be 400 Bad Request
  6104. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6105. EXPECT_EQ("close", res->get_header_value("Connection"));
  6106. }
  6107. EXPECT_FALSE(cli_.is_socket_open());
  6108. }
  6109. TEST_F(ServerTest, MultipartFormData) {
  6110. UploadFormDataItems items = {
  6111. {"text1", "text default", "", ""},
  6112. {"text2", "aωb", "", ""},
  6113. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6114. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6115. {"file3", "", "", "application/octet-stream"},
  6116. {"file4", "", "", " application/json tmp-string "}};
  6117. auto res = cli_.Post("/multipart", items);
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. EXPECT_EQ(StatusCode::OK_200, res->status);
  6120. }
  6121. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6122. UploadFormDataItems items = {
  6123. {"text", "default text", "", ""},
  6124. {"multi_text1", "aaaaa", "", ""},
  6125. {"multi_text1", "bbbbb", "", ""},
  6126. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6127. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6128. "application/json"},
  6129. };
  6130. auto res = cli_.Post("/multipart/multi_file_values", items);
  6131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6132. EXPECT_EQ(StatusCode::OK_200, res->status);
  6133. }
  6134. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6135. auto res = cli_.Get("/hi");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::OK_200, res->status);
  6138. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6139. EXPECT_EQ("Hello World!", res->body);
  6140. }
  6141. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6142. Request req;
  6143. req.method = "POST";
  6144. req.path = "/chunked";
  6145. std::string host_and_port;
  6146. host_and_port += HOST;
  6147. host_and_port += ":";
  6148. host_and_port += std::to_string(PORT);
  6149. req.headers.emplace("Host", host_and_port.c_str());
  6150. req.headers.emplace("Accept", "*/*");
  6151. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6152. req.headers.emplace("Content-Type", "text/plain");
  6153. req.headers.emplace("Content-Length", "0");
  6154. req.headers.emplace(
  6155. "Transfer-Encoding",
  6156. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6157. // Client does not chunk, so make a chunked body manually.
  6158. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6159. auto res = std::make_shared<Response>();
  6160. auto error = Error::Success;
  6161. auto ret = cli_.send(req, *res, error);
  6162. ASSERT_TRUE(ret);
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. }
  6165. template <typename ClientT>
  6166. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6167. int expected_status) {
  6168. Request req;
  6169. req.method = "POST";
  6170. req.path = "/chunked";
  6171. std::string host_and_port;
  6172. host_and_port += HOST;
  6173. host_and_port += ":";
  6174. host_and_port += std::to_string(PORT);
  6175. req.headers.emplace("Host", host_and_port.c_str());
  6176. req.headers.emplace("Content-Length", "0");
  6177. req.headers.emplace("Transfer-Encoding", "chunked");
  6178. req.body = body;
  6179. auto res = std::make_shared<Response>();
  6180. auto error = Error::Success;
  6181. ASSERT_TRUE(cli.send(req, *res, error));
  6182. EXPECT_EQ(expected_status, res->status);
  6183. }
  6184. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6185. // rather than treat them as valid lengths.
  6186. template <typename ClientT>
  6187. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6188. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6189. }
  6190. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6191. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6192. }
  6193. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6194. expect_chunked_body_rejected(
  6195. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6196. }
  6197. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6198. // chunk-size line carries no CR, LF or other control character ahead of its
  6199. // terminator. Such a line must be refused rather than read as extension text.
  6200. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6201. expect_chunked_body_rejected(
  6202. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6203. }
  6204. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6205. expect_chunked_body_rejected(
  6206. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6207. }
  6208. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6209. expect_chunked_body_rejected(
  6210. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6211. }
  6212. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6213. // The literal stays split: a hex escape consumes every hex digit that
  6214. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6215. expect_chunked_body_rejected(
  6216. cli_, "4;a\x01"
  6217. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6218. }
  6219. TEST_F(ServerTest, AcceptsChunkExtension) {
  6220. expect_chunked_body_status(cli_,
  6221. "4;name=value\r\ndech\r\n"
  6222. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6223. "0;last\r\n\r\n",
  6224. StatusCode::OK_200);
  6225. }
  6226. TEST_F(ServerTest, GetStreamed2) {
  6227. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6230. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6231. EXPECT_EQ(true, res->has_header("Content-Range"));
  6232. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6233. EXPECT_EQ(std::string("ab"), res->body);
  6234. }
  6235. TEST_F(ServerTest, GetStreamed) {
  6236. auto res = cli_.Get("/streamed");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. EXPECT_EQ(StatusCode::OK_200, res->status);
  6239. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6240. EXPECT_EQ(std::string("aaabbb"), res->body);
  6241. }
  6242. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6243. auto res = cli_.Get("/streamed-without-length",
  6244. Headers{make_range_header({{0, -1}})});
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. EXPECT_EQ(false, res->has_header("Content-Length"));
  6248. EXPECT_EQ(false, res->has_header("Content-Range"));
  6249. EXPECT_EQ(std::string("abcdefg"), res->body);
  6250. }
  6251. TEST_F(ServerTest, GetStreamedWithRange1) {
  6252. auto res =
  6253. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6256. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6257. EXPECT_EQ(true, res->has_header("Content-Range"));
  6258. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6259. EXPECT_EQ(std::string("def"), res->body);
  6260. }
  6261. TEST_F(ServerTest, GetStreamedWithRange2) {
  6262. auto res =
  6263. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6265. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6266. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6267. EXPECT_EQ(true, res->has_header("Content-Range"));
  6268. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6269. EXPECT_EQ(std::string("bcdefg"), res->body);
  6270. }
  6271. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6272. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6275. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6276. EXPECT_EQ(true, res->has_header("Content-Range"));
  6277. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6278. EXPECT_EQ(std::string("efg"), res->body);
  6279. }
  6280. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6281. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6282. // the entire representation.
  6283. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6284. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6287. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6288. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6289. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6290. }
  6291. }
  6292. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6293. auto res =
  6294. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6297. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6298. EXPECT_EQ(false, res->has_header("Content-Range"));
  6299. EXPECT_EQ(0U, res->body.size());
  6300. }
  6301. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6302. // Only a 206 is served as a partial representation. Under any other status
  6303. // `apply_ranges()` reported the full content length, so the body must match
  6304. // that header, and the content provider must never be asked for an offset
  6305. // outside the representation.
  6306. auto check = [&](int status, const char *range) {
  6307. auto path =
  6308. std::string("/streamed-with-range?status=") + std::to_string(status);
  6309. auto ctx = path + " Range: " + range;
  6310. auto res = cli_.Get(path, Headers{{"Range", range}});
  6311. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6312. EXPECT_EQ(status, res->status) << ctx;
  6313. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6315. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6316. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6317. };
  6318. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6319. check(403, "bytes=3-5");
  6320. // The offset is far past the representation.
  6321. check(403, "bytes=100000-100200");
  6322. // `first_pos` is still -1 here, and the bounds asserts in
  6323. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6324. check(403, "bytes=-3");
  6325. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6326. // multipart branch would have written one that is empty.
  6327. check(403, "bytes=1-2, 4-5");
  6328. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6329. // covers the whole representation.
  6330. check(200, "bytes=3-5");
  6331. check(200, "bytes=1-2, 4-5");
  6332. }
  6333. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6334. auto res =
  6335. cli_.Get("/streamed-with-range",
  6336. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6337. "92233720368547758079223372036854775807"}});
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6340. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6341. EXPECT_EQ(false, res->has_header("Content-Range"));
  6342. EXPECT_EQ(0U, res->body.size());
  6343. }
  6344. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6345. auto res = cli_.Get(
  6346. "/with-range",
  6347. Headers{{"Range",
  6348. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6349. {"Accept-Encoding", ""}});
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6352. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6353. EXPECT_EQ(true, res->has_header("Content-Range"));
  6354. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6355. EXPECT_EQ(std::string("abcdefg"), res->body);
  6356. }
  6357. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6358. auto res = cli_.Get("/with-range", Headers{
  6359. {"Range", "bytes=0-"},
  6360. {"Accept-Encoding", ""},
  6361. });
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6364. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6365. EXPECT_EQ(true, res->has_header("Content-Range"));
  6366. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6367. EXPECT_EQ(std::string("abcdefg"), res->body);
  6368. }
  6369. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6370. auto res = cli_.Get("/streamed-with-range",
  6371. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6374. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6375. EXPECT_EQ(false, res->has_header("Content-Range"));
  6376. EXPECT_EQ(267U, res->body.size());
  6377. // Check that both range contents are present
  6378. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6379. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6380. // Check that Content-Range headers are present for both ranges
  6381. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6382. std::string::npos);
  6383. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6384. std::string::npos);
  6385. }
  6386. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6387. Ranges ranges;
  6388. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6389. ranges.emplace_back(0, -1);
  6390. }
  6391. auto res = cli_.Get("/streamed-with-range?error",
  6392. Headers{{make_range_header(ranges)}});
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6395. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6396. EXPECT_EQ(false, res->has_header("Content-Range"));
  6397. EXPECT_EQ(0U, res->body.size());
  6398. }
  6399. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6400. auto res = cli_.Get("/streamed-with-range",
  6401. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6404. EXPECT_EQ(5U, res->body.size());
  6405. // Check that overlapping ranges are coalesced into a single range
  6406. EXPECT_EQ("bcdef", res->body);
  6407. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6408. // Should be single range, not multipart
  6409. EXPECT_TRUE(res->has_header("Content-Range"));
  6410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6411. }
  6412. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6413. auto res = cli_.Get("/streamed-with-range",
  6414. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6417. EXPECT_EQ(268U, res->body.size());
  6418. // Check that both range contents are present
  6419. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6420. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6421. // Check that Content-Range headers are present for both ranges
  6422. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6423. std::string::npos);
  6424. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6425. std::string::npos);
  6426. }
  6427. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6428. auto res = cli_.Get("/streamed-with-range",
  6429. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6432. EXPECT_EQ(269U, res->body.size());
  6433. // Check that both duplicate range contents are present
  6434. size_t first_abc = res->body.find("abc\r\n");
  6435. EXPECT_TRUE(first_abc != std::string::npos);
  6436. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6437. EXPECT_TRUE(second_abc != std::string::npos);
  6438. // Check that Content-Range headers are present for both ranges
  6439. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6440. EXPECT_TRUE(first_range != std::string::npos);
  6441. size_t second_range =
  6442. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6443. EXPECT_TRUE(second_range != std::string::npos);
  6444. }
  6445. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6446. auto res =
  6447. cli_.Get("/streamed-with-range?error",
  6448. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6451. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6452. EXPECT_EQ(false, res->has_header("Content-Range"));
  6453. EXPECT_EQ(0U, res->body.size());
  6454. }
  6455. TEST_F(ServerTest, GetStreamedEndless) {
  6456. uint64_t offset = 0;
  6457. auto res = cli_.Get("/streamed-cancel",
  6458. [&](const char * /*data*/, uint64_t data_length) {
  6459. if (offset < 100) {
  6460. offset += data_length;
  6461. return true;
  6462. }
  6463. return false;
  6464. });
  6465. ASSERT_TRUE(!res);
  6466. EXPECT_EQ(Error::Canceled, res.error());
  6467. }
  6468. TEST_F(ServerTest, ClientStop) {
  6469. std::atomic_size_t count{4};
  6470. std::vector<std::thread> threads;
  6471. for (auto i = count.load(); i != 0; --i) {
  6472. threads.emplace_back([&]() {
  6473. auto res = cli_.Get("/streamed-cancel",
  6474. [&](const char *, uint64_t) { return true; });
  6475. --count;
  6476. ASSERT_TRUE(!res);
  6477. EXPECT_TRUE(res.error() == Error::Canceled ||
  6478. res.error() == Error::Read || res.error() == Error::Write);
  6479. });
  6480. }
  6481. std::this_thread::sleep_for(std::chrono::seconds(2));
  6482. while (count != 0) {
  6483. cli_.stop();
  6484. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6485. }
  6486. for (auto &t : threads) {
  6487. t.join();
  6488. }
  6489. }
  6490. TEST_F(ServerTest, GetWithRange1) {
  6491. auto res = cli_.Get("/with-range", Headers{
  6492. make_range_header({{3, 5}}),
  6493. {"Accept-Encoding", ""},
  6494. });
  6495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6496. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6497. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6498. EXPECT_EQ(true, res->has_header("Content-Range"));
  6499. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6500. EXPECT_EQ(std::string("def"), res->body);
  6501. }
  6502. TEST_F(ServerTest, GetWithRange2) {
  6503. auto res = cli_.Get("/with-range", Headers{
  6504. make_range_header({{1, -1}}),
  6505. {"Accept-Encoding", ""},
  6506. });
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6509. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6510. EXPECT_EQ(true, res->has_header("Content-Range"));
  6511. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6512. EXPECT_EQ(std::string("bcdefg"), res->body);
  6513. }
  6514. TEST_F(ServerTest, GetWithRange3) {
  6515. auto res = cli_.Get("/with-range", Headers{
  6516. make_range_header({{0, 0}}),
  6517. {"Accept-Encoding", ""},
  6518. });
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6521. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6522. EXPECT_EQ(true, res->has_header("Content-Range"));
  6523. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6524. EXPECT_EQ(std::string("a"), res->body);
  6525. }
  6526. TEST_F(ServerTest, GetWithRange4) {
  6527. auto res = cli_.Get("/with-range", Headers{
  6528. make_range_header({{-1, 2}}),
  6529. {"Accept-Encoding", ""},
  6530. });
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6533. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6534. EXPECT_EQ(true, res->has_header("Content-Range"));
  6535. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6536. EXPECT_EQ(std::string("fg"), res->body);
  6537. }
  6538. TEST_F(ServerTest, GetWithRange5) {
  6539. auto res = cli_.Get("/with-range", Headers{
  6540. make_range_header({{0, 5}}),
  6541. {"Accept-Encoding", ""},
  6542. });
  6543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6545. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6546. EXPECT_EQ(true, res->has_header("Content-Range"));
  6547. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6548. EXPECT_EQ(std::string("abcdef"), res->body);
  6549. }
  6550. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6551. auto res =
  6552. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6554. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6555. }
  6556. TEST_F(ServerTest, GetWithRangeMultipart) {
  6557. auto res =
  6558. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6561. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6562. EXPECT_EQ(false, res->has_header("Content-Range"));
  6563. EXPECT_EQ(267U, res->body.size());
  6564. }
  6565. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6566. auto res = cli_.Get("/with-range",
  6567. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6570. }
  6571. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6572. auto res = cli_.Get("/with-range-customized-response",
  6573. Headers{{make_range_header({{1, 2}})}});
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6576. EXPECT_EQ(true, res->has_header("Content-Length"));
  6577. EXPECT_EQ(false, res->has_header("Content-Range"));
  6578. EXPECT_EQ(JSON_DATA, res->body);
  6579. }
  6580. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6581. auto res = cli_.Get("/with-range-customized-response",
  6582. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6584. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6585. EXPECT_EQ(true, res->has_header("Content-Length"));
  6586. EXPECT_EQ(false, res->has_header("Content-Range"));
  6587. EXPECT_EQ(JSON_DATA, res->body);
  6588. }
  6589. TEST_F(ServerTest, Issue1772) {
  6590. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6593. }
  6594. TEST_F(ServerTest, Issue609) {
  6595. auto res = cli_.Delete("/issue609");
  6596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6597. EXPECT_EQ(StatusCode::OK_200, res->status);
  6598. EXPECT_EQ(std::string("ok"), res->body);
  6599. }
  6600. TEST_F(ServerTest, GetStreamedChunked) {
  6601. auto res = cli_.Get("/streamed-chunked");
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::OK_200, res->status);
  6604. EXPECT_EQ(std::string("123456789"), res->body);
  6605. }
  6606. TEST_F(ServerTest, GetStreamedChunked2) {
  6607. auto res = cli_.Get("/streamed-chunked2");
  6608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6609. EXPECT_EQ(StatusCode::OK_200, res->status);
  6610. EXPECT_EQ(std::string("123456789"), res->body);
  6611. }
  6612. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6613. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::OK_200, res->status);
  6616. EXPECT_EQ(std::string("123456789"), res->body);
  6617. EXPECT_TRUE(res->has_header("Trailer"));
  6618. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6619. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6620. // Trailers are now stored separately from headers (security fix)
  6621. EXPECT_EQ(2U, res->trailers.size());
  6622. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6623. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6624. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6625. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6626. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6627. // Verify trailers are NOT in headers (security verification)
  6628. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6629. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6630. }
  6631. TEST_F(ServerTest, LargeChunkedPost) {
  6632. Request req;
  6633. req.method = "POST";
  6634. req.path = "/large-chunked";
  6635. std::string host_and_port;
  6636. host_and_port += HOST;
  6637. host_and_port += ":";
  6638. host_and_port += std::to_string(PORT);
  6639. req.headers.emplace("Host", host_and_port.c_str());
  6640. req.headers.emplace("Accept", "*/*");
  6641. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6642. req.headers.emplace("Content-Type", "text/plain");
  6643. req.headers.emplace("Content-Length", "0");
  6644. req.headers.emplace("Transfer-Encoding", "chunked");
  6645. std::string long_string(30 * 1024u, 'a');
  6646. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6647. // Attempt to make a large enough post to exceed OS buffers, to test that
  6648. // the server handles short reads if the full chunk data isn't available.
  6649. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6650. auto res = std::make_shared<Response>();
  6651. auto error = Error::Success;
  6652. auto ret = cli_.send(req, *res, error);
  6653. ASSERT_TRUE(ret);
  6654. EXPECT_EQ(StatusCode::OK_200, res->status);
  6655. }
  6656. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6657. auto res = cli_.Get("/remote_addr");
  6658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6659. EXPECT_EQ(StatusCode::OK_200, res->status);
  6660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6661. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6662. }
  6663. TEST_F(ServerTest, GetMethodLocalAddr) {
  6664. auto res = cli_.Get("/local_addr");
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::OK_200, res->status);
  6667. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6668. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6669. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6670. }
  6671. TEST_F(ServerTest, HTTPResponseSplitting) {
  6672. auto res = cli_.Get("/http_response_splitting");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. }
  6676. TEST_F(ServerTest, SlowRequest) {
  6677. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6678. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6679. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6680. }
  6681. #if 0
  6682. TEST_F(ServerTest, SlowPost) {
  6683. char buffer[64 * 1024];
  6684. memset(buffer, 0x42, sizeof(buffer));
  6685. auto res = cli_.Post(
  6686. "/slowpost", 64 * 1024 * 1024,
  6687. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6688. auto ret = sink.write(buffer, sizeof(buffer));
  6689. EXPECT_TRUE(ret);
  6690. return true;
  6691. },
  6692. "text/plain");
  6693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. }
  6696. TEST_F(ServerTest, SlowPostFail) {
  6697. char buffer[64 * 1024];
  6698. memset(buffer, 0x42, sizeof(buffer));
  6699. cli_.set_write_timeout(std::chrono::seconds(0));
  6700. auto res = cli_.Post(
  6701. "/slowpost", 64 * 1024 * 1024,
  6702. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6703. sink.write(buffer, sizeof(buffer));
  6704. return true;
  6705. },
  6706. "text/plain");
  6707. ASSERT_TRUE(!res);
  6708. EXPECT_EQ(Error::Write, res.error());
  6709. }
  6710. #endif
  6711. TEST_F(ServerTest, Put) {
  6712. auto res = cli_.Put("/put", "PUT", "text/plain");
  6713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6714. EXPECT_EQ(StatusCode::OK_200, res->status);
  6715. EXPECT_EQ("PUT", res->body);
  6716. }
  6717. TEST_F(ServerTest, PutWithContentProvider) {
  6718. auto res = cli_.Put(
  6719. "/put", 3,
  6720. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6721. sink.os << "PUT";
  6722. return true;
  6723. },
  6724. "text/plain");
  6725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6726. EXPECT_EQ(StatusCode::OK_200, res->status);
  6727. EXPECT_EQ("PUT", res->body);
  6728. }
  6729. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6730. auto res = cli_.Post(
  6731. "/post", 42,
  6732. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6733. return false;
  6734. },
  6735. "text/plain");
  6736. ASSERT_TRUE(!res);
  6737. EXPECT_EQ(Error::Canceled, res.error());
  6738. }
  6739. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6740. auto res = cli_.Put(
  6741. "/put",
  6742. [](size_t /*offset*/, DataSink &sink) {
  6743. sink.os << "PUT";
  6744. sink.done();
  6745. return true;
  6746. },
  6747. "text/plain");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ(StatusCode::OK_200, res->status);
  6750. EXPECT_EQ("PUT", res->body);
  6751. }
  6752. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6753. auto res = cli_.Post(
  6754. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6755. "text/plain");
  6756. ASSERT_TRUE(!res);
  6757. EXPECT_EQ(Error::Canceled, res.error());
  6758. }
  6759. TEST_F(ServerTest, PostLoopBack) {
  6760. std::string body;
  6761. auto res = cli_.Post(
  6762. "/post-loopback", 9,
  6763. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6764. EXPECT_EQ(9u, length);
  6765. sink.write("123", 3);
  6766. sink.write("456", 3);
  6767. sink.write("789", 3);
  6768. return true;
  6769. },
  6770. "text/plain",
  6771. [&body](const char *data, size_t data_length) {
  6772. body.append(data, data_length);
  6773. return true;
  6774. });
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(StatusCode::OK_200, res->status);
  6777. EXPECT_EQ("123456789", body);
  6778. }
  6779. TEST_F(ServerTest, PutLoopBack) {
  6780. std::string body;
  6781. auto res = cli_.Put(
  6782. "/put-loopback", 9,
  6783. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6784. EXPECT_EQ(9u, length);
  6785. sink.write("123", 3);
  6786. sink.write("456", 3);
  6787. sink.write("789", 3);
  6788. return true;
  6789. },
  6790. "text/plain",
  6791. [&body](const char *data, size_t data_length) {
  6792. body.append(data, data_length);
  6793. return true;
  6794. });
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. EXPECT_EQ("123456789", body);
  6798. }
  6799. TEST_F(ServerTest, PatchLoopBack) {
  6800. std::string body;
  6801. auto res = cli_.Patch(
  6802. "/patch-loopback", 9,
  6803. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6804. EXPECT_EQ(9u, length);
  6805. sink.write("123", 3);
  6806. sink.write("456", 3);
  6807. sink.write("789", 3);
  6808. return true;
  6809. },
  6810. "text/plain",
  6811. [&body](const char *data, size_t data_length) {
  6812. body.append(data, data_length);
  6813. return true;
  6814. });
  6815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6816. EXPECT_EQ(StatusCode::OK_200, res->status);
  6817. EXPECT_EQ("123456789", body);
  6818. }
  6819. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6820. std::string body;
  6821. auto res = cli_.Post(
  6822. "/post-loopback",
  6823. [](size_t /*offset*/, DataSink &sink) {
  6824. sink.write("123", 3);
  6825. sink.write("456", 3);
  6826. sink.write("789", 3);
  6827. sink.done();
  6828. return true;
  6829. },
  6830. "text/plain",
  6831. [&body](const char *data, size_t data_length) {
  6832. body.append(data, data_length);
  6833. return true;
  6834. });
  6835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6836. EXPECT_EQ(StatusCode::OK_200, res->status);
  6837. EXPECT_EQ("123456789", body);
  6838. }
  6839. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6840. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6841. cli_.set_compress(true);
  6842. auto res = cli_.Put(
  6843. "/put", 3,
  6844. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6845. sink.os << "PUT";
  6846. return true;
  6847. },
  6848. "text/plain");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ(StatusCode::OK_200, res->status);
  6851. EXPECT_EQ("PUT", res->body);
  6852. }
  6853. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6854. cli_.set_compress(true);
  6855. auto res = cli_.Post(
  6856. "/post", 42,
  6857. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6858. return false;
  6859. },
  6860. "text/plain");
  6861. ASSERT_TRUE(!res);
  6862. EXPECT_EQ(Error::Canceled, res.error());
  6863. }
  6864. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6865. cli_.set_compress(true);
  6866. auto res = cli_.Put(
  6867. "/put",
  6868. [](size_t /*offset*/, DataSink &sink) {
  6869. sink.os << "PUT";
  6870. sink.done();
  6871. return true;
  6872. },
  6873. "text/plain");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("PUT", res->body);
  6877. }
  6878. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6879. cli_.set_compress(true);
  6880. auto res = cli_.Post(
  6881. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6882. "text/plain");
  6883. ASSERT_TRUE(!res);
  6884. EXPECT_EQ(Error::Canceled, res.error());
  6885. }
  6886. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6887. cli_.set_compress(true);
  6888. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::OK_200, res->status);
  6891. EXPECT_EQ(LARGE_DATA, res->body);
  6892. }
  6893. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6894. #ifdef CPPHTTPLIB_SSL_ENABLED
  6895. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6896. Client cli(s.c_str());
  6897. cli.enable_server_certificate_verification(false);
  6898. #else
  6899. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6900. Client cli(s.c_str());
  6901. #endif
  6902. cli.set_compress(true);
  6903. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. EXPECT_EQ(StatusCode::OK_200, res->status);
  6906. EXPECT_EQ(LARGE_DATA, res->body);
  6907. // The compressed size should be less than a 10th of the original. May vary
  6908. // depending on the zlib library.
  6909. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6910. static_cast<uint64_t>(10 * 1024 * 1024));
  6911. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6912. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6913. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6914. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6915. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6916. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6917. #endif
  6918. }
  6919. TEST_F(ServerTest, PutContentWithDeflate) {
  6920. cli_.set_compress(false);
  6921. Headers headers;
  6922. headers.emplace("Content-Encoding", "deflate");
  6923. // PUT in deflate format:
  6924. auto res = cli_.Put("/put", headers,
  6925. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::OK_200, res->status);
  6928. EXPECT_EQ("PUT", res->body);
  6929. }
  6930. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6931. Headers headers;
  6932. headers.emplace("Accept-Encoding", "gzip, deflate");
  6933. auto res = cli_.Get("/streamed-chunked", headers);
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ(std::string("123456789"), res->body);
  6937. }
  6938. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6939. Headers headers;
  6940. headers.emplace("Accept-Encoding", "gzip, deflate");
  6941. auto res = cli_.Get("/streamed-chunked2", headers);
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::OK_200, res->status);
  6944. EXPECT_EQ(std::string("123456789"), res->body);
  6945. }
  6946. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6947. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. }
  6951. TEST(GzipDecompressor, ChunkedDecompression) {
  6952. std::string data;
  6953. for (size_t i = 0; i < 32 * 1024; ++i) {
  6954. data.push_back(static_cast<char>('a' + i % 26));
  6955. }
  6956. std::string compressed_data;
  6957. {
  6958. httplib::detail::gzip_compressor compressor;
  6959. bool result = compressor.compress(
  6960. data.data(), data.size(),
  6961. /*last=*/true,
  6962. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6963. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6964. compressed_data_size);
  6965. return true;
  6966. });
  6967. ASSERT_TRUE(result);
  6968. }
  6969. std::string decompressed_data;
  6970. {
  6971. httplib::detail::gzip_decompressor decompressor;
  6972. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6973. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6974. size_t chunk_size = 130;
  6975. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6976. chunk_begin += chunk_size) {
  6977. size_t current_chunk_size =
  6978. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6979. bool result = decompressor.decompress(
  6980. compressed_data.data() + chunk_begin, current_chunk_size,
  6981. [&](const char *decompressed_data_chunk,
  6982. size_t decompressed_data_chunk_size) {
  6983. decompressed_data.insert(decompressed_data.size(),
  6984. decompressed_data_chunk,
  6985. decompressed_data_chunk_size);
  6986. return true;
  6987. });
  6988. ASSERT_TRUE(result);
  6989. }
  6990. }
  6991. ASSERT_EQ(data, decompressed_data);
  6992. }
  6993. TEST(GzipDecompressor, DeflateDecompression) {
  6994. std::string original_text = "Raw deflate without gzip";
  6995. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6996. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6997. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6998. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6999. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7000. std::string decompressed_data;
  7001. {
  7002. httplib::detail::gzip_decompressor decompressor;
  7003. bool result = decompressor.decompress(
  7004. compressed_data.data(), compressed_data.size(),
  7005. [&](const char *decompressed_data_chunk,
  7006. size_t decompressed_data_chunk_size) {
  7007. decompressed_data.insert(decompressed_data.size(),
  7008. decompressed_data_chunk,
  7009. decompressed_data_chunk_size);
  7010. return true;
  7011. });
  7012. ASSERT_TRUE(result);
  7013. }
  7014. ASSERT_EQ(original_text, decompressed_data);
  7015. }
  7016. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7017. std::string original_text = "Raw deflate without gzip";
  7018. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7019. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7020. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7021. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7022. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7023. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7024. std::string decompressed_data;
  7025. {
  7026. httplib::detail::gzip_decompressor decompressor;
  7027. bool result = decompressor.decompress(
  7028. compressed_data.data(), compressed_data.size(),
  7029. [&](const char *decompressed_data_chunk,
  7030. size_t decompressed_data_chunk_size) {
  7031. decompressed_data.insert(decompressed_data.size(),
  7032. decompressed_data_chunk,
  7033. decompressed_data_chunk_size);
  7034. return true;
  7035. });
  7036. ASSERT_TRUE(result);
  7037. }
  7038. ASSERT_EQ(original_text, decompressed_data);
  7039. }
  7040. #endif
  7041. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7042. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7043. Headers headers;
  7044. headers.emplace("Accept-Encoding", "br");
  7045. auto res = cli_.Get("/streamed-chunked", headers);
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. EXPECT_EQ(StatusCode::OK_200, res->status);
  7048. EXPECT_EQ(std::string("123456789"), res->body);
  7049. }
  7050. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7051. Headers headers;
  7052. headers.emplace("Accept-Encoding", "br");
  7053. auto res = cli_.Get("/streamed-chunked2", headers);
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::OK_200, res->status);
  7056. EXPECT_EQ(std::string("123456789"), res->body);
  7057. }
  7058. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7059. cli_.set_compress(true);
  7060. auto res = cli_.Put(
  7061. "/put", 3,
  7062. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7063. sink.os << "PUT";
  7064. return true;
  7065. },
  7066. "text/plain");
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::OK_200, res->status);
  7069. EXPECT_EQ("PUT", res->body);
  7070. }
  7071. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7072. cli_.set_compress(true);
  7073. auto res = cli_.Put(
  7074. "/put",
  7075. [](size_t /*offset*/, DataSink &sink) {
  7076. sink.os << "PUT";
  7077. sink.done();
  7078. return true;
  7079. },
  7080. "text/plain");
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::OK_200, res->status);
  7083. EXPECT_EQ("PUT", res->body);
  7084. }
  7085. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7086. cli_.set_compress(true);
  7087. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::OK_200, res->status);
  7090. EXPECT_EQ(LARGE_DATA, res->body);
  7091. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7092. }
  7093. #endif
  7094. TEST_F(ServerTest, Patch) {
  7095. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::OK_200, res->status);
  7098. EXPECT_EQ("PATCH", res->body);
  7099. }
  7100. TEST_F(ServerTest, Delete) {
  7101. auto res = cli_.Delete("/delete");
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. EXPECT_EQ(StatusCode::OK_200, res->status);
  7104. EXPECT_EQ("DELETE", res->body);
  7105. }
  7106. TEST_F(ServerTest, DeleteContentReceiver) {
  7107. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7109. EXPECT_EQ(StatusCode::OK_200, res->status);
  7110. EXPECT_EQ("content", res->body);
  7111. }
  7112. TEST_F(ServerTest, Options) {
  7113. auto res = cli_.Options("*");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::OK_200, res->status);
  7116. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7117. EXPECT_TRUE(res->body.empty());
  7118. }
  7119. TEST_F(ServerTest, URL) {
  7120. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7122. EXPECT_EQ(StatusCode::OK_200, res->status);
  7123. }
  7124. TEST_F(ServerTest, ArrayParam) {
  7125. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7127. EXPECT_EQ(StatusCode::OK_200, res->status);
  7128. }
  7129. TEST_F(ServerTest, ArrayParamValues) {
  7130. auto res =
  7131. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ(StatusCode::OK_200, res->status);
  7134. }
  7135. TEST_F(ServerTest, NoMultipleHeaders) {
  7136. Headers headers = {{"Content-Length", "5"}};
  7137. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7138. "text/plain");
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. TEST_F(ServerTest, PostContentReceiver) {
  7143. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7145. ASSERT_EQ(StatusCode::OK_200, res->status);
  7146. ASSERT_EQ("content", res->body);
  7147. }
  7148. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7149. UploadFormDataItems items = {
  7150. {"text1", "text default", "", ""},
  7151. {"text2", "aωb", "", ""},
  7152. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7153. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7154. {"file3", "", "", "application/octet-stream"},
  7155. };
  7156. auto res = cli_.Post("/content_receiver", items);
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. }
  7160. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7161. UploadFormDataItems items = {
  7162. {"text1", "text default", "", ""},
  7163. {"text2", "aωb", "", ""},
  7164. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7165. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7166. {"file3", "", "", "application/octet-stream"},
  7167. };
  7168. auto boundary = std::string("+++++");
  7169. std::string body;
  7170. for (const auto &item : items) {
  7171. body += "--" + boundary + "\r\n";
  7172. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7173. if (!item.filename.empty()) {
  7174. body += "; filename=\"" + item.filename + "\"";
  7175. }
  7176. body += "\r\n";
  7177. if (!item.content_type.empty()) {
  7178. body += "Content-Type: " + item.content_type + "\r\n";
  7179. }
  7180. body += "\r\n";
  7181. body += item.content + "\r\n";
  7182. }
  7183. body += "--" + boundary + "--\r\n";
  7184. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7185. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7187. EXPECT_EQ(StatusCode::OK_200, res->status);
  7188. }
  7189. TEST(MultipartFormDataTest, FieldEscaping) {
  7190. Server svr;
  7191. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7192. const ContentReader &content_reader) {
  7193. ASSERT_TRUE(req.is_multipart_form_data());
  7194. std::vector<FormData> received;
  7195. content_reader(
  7196. [&](const FormData &file) {
  7197. received.push_back(file);
  7198. return true;
  7199. },
  7200. [&](const char *data, size_t data_length) {
  7201. received.back().content.append(data, data_length);
  7202. return true;
  7203. });
  7204. // '"', CR and LF in names and filenames are escaped following the
  7205. // WHATWG HTML standard, so each part still parses as a single part
  7206. // with no injected headers. Content types get CR/LF escaped too,
  7207. // while '"' (legal there, e.g. quoted charset) is preserved.
  7208. ASSERT_EQ(4U, received.size());
  7209. EXPECT_EQ("na%22me", received[0].name);
  7210. EXPECT_EQ("quoted name", received[0].content);
  7211. EXPECT_EQ("file", received[1].name);
  7212. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7213. received[1].filename);
  7214. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7215. EXPECT_EQ("injected", received[1].content);
  7216. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7217. EXPECT_EQ("my%22file.txt", received[2].filename);
  7218. EXPECT_EQ("cr lf name", received[2].content);
  7219. EXPECT_EQ("typed", received[3].name);
  7220. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7221. received[3].content_type);
  7222. EXPECT_EQ("typed content", received[3].content);
  7223. });
  7224. auto port = svr.bind_to_any_port("localhost");
  7225. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7226. auto se = detail::scope_exit([&] {
  7227. svr.stop();
  7228. t.join();
  7229. ASSERT_FALSE(svr.is_running());
  7230. });
  7231. svr.wait_until_ready();
  7232. Client cli("localhost", port);
  7233. UploadFormDataItems items = {
  7234. {"na\"me", "quoted name", "", ""},
  7235. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7236. "application/octet-stream"},
  7237. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7238. {"typed", "typed content", "",
  7239. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7240. };
  7241. auto res = cli.Post("/post", items);
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. EXPECT_EQ(StatusCode::OK_200, res->status);
  7244. }
  7245. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7246. const UploadFormDataItems items = {
  7247. {"name1", "Content 1", "", ""},
  7248. {"name2", "Content 2", "file2.txt", "text/plain"},
  7249. };
  7250. Server svr;
  7251. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7252. const ContentReader &content_reader) {
  7253. ASSERT_TRUE(req.is_multipart_form_data());
  7254. std::vector<FormData> received;
  7255. content_reader(
  7256. [&](const FormData &file) {
  7257. received.push_back(file);
  7258. return true;
  7259. },
  7260. [&](const char *data, size_t data_length) {
  7261. received.back().content.append(data, data_length);
  7262. return true;
  7263. });
  7264. ASSERT_EQ(2U, received.size());
  7265. EXPECT_EQ("name1", received[0].name);
  7266. EXPECT_EQ("Content 1", received[0].content);
  7267. EXPECT_EQ("name2", received[1].name);
  7268. EXPECT_EQ("Content 2", received[1].content);
  7269. EXPECT_EQ("file2.txt", received[1].filename);
  7270. EXPECT_EQ("text/plain", received[1].content_type);
  7271. });
  7272. auto port = svr.bind_to_any_port("localhost");
  7273. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7274. auto se = detail::scope_exit([&] {
  7275. svr.stop();
  7276. t.join();
  7277. ASSERT_FALSE(svr.is_running());
  7278. });
  7279. svr.wait_until_ready();
  7280. Client cli("localhost", port);
  7281. // Whole-body serialization with a generated boundary
  7282. {
  7283. MultipartFormDataWriter writer;
  7284. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7285. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7286. writer.content_type());
  7287. auto body = writer.serialize(items);
  7288. EXPECT_EQ(body.size(), writer.content_length(items));
  7289. auto res = cli.Post("/post", body, writer.content_type());
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. }
  7293. // Per-part framing with a custom boundary via a content provider
  7294. {
  7295. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7296. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7297. MultipartFormDataWriter writer("custom-boundary_123");
  7298. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7299. std::string body;
  7300. for (const auto &item : items) {
  7301. body += writer.item_begin(item);
  7302. body += item.content;
  7303. body += MultipartFormDataWriter::item_end();
  7304. }
  7305. body += writer.finish();
  7306. EXPECT_EQ(body.size(), writer.content_length(items));
  7307. auto res = cli.Post(
  7308. "/post", body.size(),
  7309. [&](size_t offset, size_t length, DataSink &sink) {
  7310. sink.write(body.data() + offset, length);
  7311. return true;
  7312. },
  7313. writer.content_type());
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::OK_200, res->status);
  7316. }
  7317. }
  7318. TEST_F(ServerTest, PostContentReceiverGzip) {
  7319. cli_.set_compress(true);
  7320. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. ASSERT_EQ(StatusCode::OK_200, res->status);
  7323. ASSERT_EQ("content", res->body);
  7324. }
  7325. TEST_F(ServerTest, PutContentReceiver) {
  7326. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. ASSERT_EQ(StatusCode::OK_200, res->status);
  7329. ASSERT_EQ("content", res->body);
  7330. }
  7331. TEST_F(ServerTest, PatchContentReceiver) {
  7332. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. ASSERT_EQ(StatusCode::OK_200, res->status);
  7335. ASSERT_EQ("content", res->body);
  7336. }
  7337. template <typename ClientType>
  7338. void TestWithHeadersAndContentReceiver(
  7339. ClientType &cli,
  7340. std::function<Result(ClientType &, const std::string &, const Headers &,
  7341. const std::string &, const std::string &,
  7342. ContentReceiver, DownloadProgress)>
  7343. request_func) {
  7344. Headers headers;
  7345. headers.emplace("X-Custom-Header", "test-value");
  7346. std::string received_body;
  7347. auto res = request_func(
  7348. cli, "/content_receiver", headers, "content", "application/json",
  7349. [&](const char *data, size_t data_length) {
  7350. received_body.append(data, data_length);
  7351. return true;
  7352. },
  7353. nullptr);
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_EQ("content", received_body);
  7357. }
  7358. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7359. #ifdef CPPHTTPLIB_SSL_ENABLED
  7360. using ClientT = SSLClient;
  7361. #else
  7362. using ClientT = Client;
  7363. #endif
  7364. TestWithHeadersAndContentReceiver<ClientT>(
  7365. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7366. const std::string &body, const std::string &content_type,
  7367. ContentReceiver receiver, DownloadProgress progress) {
  7368. return cli.Post(path, headers, body, content_type, receiver, progress);
  7369. });
  7370. }
  7371. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7372. #ifdef CPPHTTPLIB_SSL_ENABLED
  7373. using ClientT = SSLClient;
  7374. #else
  7375. using ClientT = Client;
  7376. #endif
  7377. TestWithHeadersAndContentReceiver<ClientT>(
  7378. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7379. const std::string &body, const std::string &content_type,
  7380. ContentReceiver receiver, DownloadProgress progress) {
  7381. return cli.Put(path, headers, body, content_type, receiver, progress);
  7382. });
  7383. }
  7384. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7385. #ifdef CPPHTTPLIB_SSL_ENABLED
  7386. using ClientT = SSLClient;
  7387. #else
  7388. using ClientT = Client;
  7389. #endif
  7390. TestWithHeadersAndContentReceiver<ClientT>(
  7391. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7392. const std::string &body, const std::string &content_type,
  7393. ContentReceiver receiver, DownloadProgress progress) {
  7394. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7395. });
  7396. }
  7397. template <typename ClientType>
  7398. void TestWithHeadersAndContentReceiverWithProgress(
  7399. ClientType &cli,
  7400. std::function<Result(ClientType &, const std::string &, const Headers &,
  7401. const std::string &, const std::string &,
  7402. ContentReceiver, DownloadProgress)>
  7403. request_func) {
  7404. Headers headers;
  7405. headers.emplace("X-Test-Header", "progress-test");
  7406. std::string received_body;
  7407. auto progress_called = false;
  7408. auto res = request_func(
  7409. cli, "/content_receiver", headers, "content", "text/plain",
  7410. [&](const char *data, size_t data_length) {
  7411. received_body.append(data, data_length);
  7412. return true;
  7413. },
  7414. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7415. progress_called = true;
  7416. return true;
  7417. });
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ(StatusCode::OK_200, res->status);
  7420. EXPECT_EQ("content", received_body);
  7421. EXPECT_TRUE(progress_called);
  7422. }
  7423. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7424. #ifdef CPPHTTPLIB_SSL_ENABLED
  7425. using ClientT = SSLClient;
  7426. #else
  7427. using ClientT = Client;
  7428. #endif
  7429. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7430. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7431. const std::string &body, const std::string &content_type,
  7432. ContentReceiver receiver, DownloadProgress progress) {
  7433. return cli.Post(path, headers, body, content_type, receiver, progress);
  7434. });
  7435. }
  7436. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7437. #ifdef CPPHTTPLIB_SSL_ENABLED
  7438. using ClientT = SSLClient;
  7439. #else
  7440. using ClientT = Client;
  7441. #endif
  7442. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7443. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7444. const std::string &body, const std::string &content_type,
  7445. ContentReceiver receiver, DownloadProgress progress) {
  7446. return cli.Put(path, headers, body, content_type, receiver, progress);
  7447. });
  7448. }
  7449. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7450. #ifdef CPPHTTPLIB_SSL_ENABLED
  7451. using ClientT = SSLClient;
  7452. #else
  7453. using ClientT = Client;
  7454. #endif
  7455. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7456. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7457. const std::string &body, const std::string &content_type,
  7458. ContentReceiver receiver, DownloadProgress progress) {
  7459. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7460. });
  7461. }
  7462. template <typename ClientType>
  7463. void TestWithHeadersAndContentReceiverError(
  7464. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7465. const Headers &, const std::string &,
  7466. const std::string &, ContentReceiver)>
  7467. request_func) {
  7468. Headers headers;
  7469. headers.emplace("X-Error-Test", "true");
  7470. std::string received_body;
  7471. auto receiver_failed = false;
  7472. auto res =
  7473. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7474. [&](const char *data, size_t data_length) {
  7475. received_body.append(data, data_length);
  7476. receiver_failed = true;
  7477. return false;
  7478. });
  7479. ASSERT_FALSE(res);
  7480. EXPECT_TRUE(receiver_failed);
  7481. }
  7482. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7483. #ifdef CPPHTTPLIB_SSL_ENABLED
  7484. using ClientT = SSLClient;
  7485. #else
  7486. using ClientT = Client;
  7487. #endif
  7488. TestWithHeadersAndContentReceiverError<ClientT>(
  7489. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7490. const std::string &body, const std::string &content_type,
  7491. ContentReceiver receiver) {
  7492. return cli.Post(path, headers, body, content_type, receiver);
  7493. });
  7494. }
  7495. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7496. #ifdef CPPHTTPLIB_SSL_ENABLED
  7497. using ClientT = SSLClient;
  7498. #else
  7499. using ClientT = Client;
  7500. #endif
  7501. TestWithHeadersAndContentReceiverError<ClientT>(
  7502. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7503. const std::string &body, const std::string &content_type,
  7504. ContentReceiver receiver) {
  7505. return cli.Put(path, headers, body, content_type, receiver);
  7506. });
  7507. }
  7508. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7509. #ifdef CPPHTTPLIB_SSL_ENABLED
  7510. using ClientT = SSLClient;
  7511. #else
  7512. using ClientT = Client;
  7513. #endif
  7514. TestWithHeadersAndContentReceiverError<ClientT>(
  7515. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7516. const std::string &body, const std::string &content_type,
  7517. ContentReceiver receiver) {
  7518. return cli.Patch(path, headers, body, content_type, receiver);
  7519. });
  7520. }
  7521. TEST_F(ServerTest, PostQueryStringAndBody) {
  7522. auto res =
  7523. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. ASSERT_EQ(StatusCode::OK_200, res->status);
  7526. }
  7527. TEST_F(ServerTest, HTTP2Magic) {
  7528. Request req;
  7529. req.method = "PRI";
  7530. req.path = "*";
  7531. req.body = "SM";
  7532. auto res = std::make_shared<Response>();
  7533. auto error = Error::Success;
  7534. auto ret = cli_.send(req, *res, error);
  7535. ASSERT_TRUE(ret);
  7536. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7537. }
  7538. TEST_F(ServerTest, KeepAlive) {
  7539. auto res = cli_.Get("/hi");
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::OK_200, res->status);
  7542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7543. EXPECT_EQ("Hello World!", res->body);
  7544. res = cli_.Get("/hi");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. EXPECT_EQ(StatusCode::OK_200, res->status);
  7547. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7548. EXPECT_EQ("Hello World!", res->body);
  7549. res = cli_.Get("/hi");
  7550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7551. EXPECT_EQ(StatusCode::OK_200, res->status);
  7552. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7553. EXPECT_EQ("Hello World!", res->body);
  7554. res = cli_.Get("/not-exist");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7557. res = cli_.Post("/empty", "", "text/plain");
  7558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7561. EXPECT_EQ("empty", res->body);
  7562. EXPECT_EQ("close", res->get_header_value("Connection"));
  7563. res = cli_.Post(
  7564. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7565. "text/plain");
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::OK_200, res->status);
  7568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7569. EXPECT_EQ("empty", res->body);
  7570. cli_.set_keep_alive(false);
  7571. res = cli_.Get("/last-request");
  7572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. EXPECT_EQ("close", res->get_header_value("Connection"));
  7575. }
  7576. TEST_F(ServerTest, TooManyRedirect) {
  7577. cli_.set_follow_location(true);
  7578. auto res = cli_.Get("/redirect/0");
  7579. ASSERT_TRUE(!res);
  7580. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7581. }
  7582. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7583. Request req;
  7584. req.method = "FOOBAR";
  7585. req.path = "/hi";
  7586. cli_.set_keep_alive(true);
  7587. auto res = cli_.send(req);
  7588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7589. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7590. EXPECT_EQ("close", res->get_header_value("Connection"));
  7591. EXPECT_FALSE(cli_.is_socket_open());
  7592. }
  7593. TEST_F(ServerTest, CustomRouteReadsBody) {
  7594. const std::string xml =
  7595. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7596. Request req;
  7597. req.method = "PROPFIND";
  7598. req.path = "/dav/dir";
  7599. req.set_header("Depth", "1");
  7600. req.body = xml;
  7601. auto res = cli_.send(req);
  7602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7603. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7604. EXPECT_EQ(xml, res->body);
  7605. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7606. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7607. }
  7608. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7609. Request req;
  7610. req.method = "PROPFIND";
  7611. req.path = "/dav/42";
  7612. auto res = cli_.send(req);
  7613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7614. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7615. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7616. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7617. }
  7618. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7619. Request req;
  7620. req.method = "PROPFIND";
  7621. req.path = "/dav-re/123";
  7622. auto res = cli_.send(req);
  7623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7624. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7625. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7626. }
  7627. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7628. Request req;
  7629. req.method = "MKCOL";
  7630. req.path = "/dav-mkcol";
  7631. auto res = cli_.send(req);
  7632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7633. EXPECT_EQ(StatusCode::Created_201, res->status);
  7634. }
  7635. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7636. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7637. Request req;
  7638. req.method = "REPORT";
  7639. req.path = "/dav-report";
  7640. req.body = xml;
  7641. auto res = cli_.send(req);
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7644. EXPECT_EQ(xml, res->body);
  7645. }
  7646. // A content reader route must fire even when the request carries no body,
  7647. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7648. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7649. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7650. Request req;
  7651. req.method = "REPORT";
  7652. req.path = "/dav-report";
  7653. auto res = cli_.send(req);
  7654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7655. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7656. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7657. }
  7658. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7659. Request req;
  7660. req.method = "PROPFIND";
  7661. req.path = "/not-dav";
  7662. auto res = cli_.send(req);
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7665. }
  7666. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7667. Request req;
  7668. req.method = "UNLOCK";
  7669. req.path = "/dav/dir";
  7670. cli_.set_keep_alive(true);
  7671. auto res = cli_.send(req);
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7674. EXPECT_EQ("close", res->get_header_value("Connection"));
  7675. EXPECT_FALSE(cli_.is_socket_open());
  7676. }
  7677. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7678. // The mount point serves this path, but only for GET and HEAD.
  7679. auto get_res = cli_.Get("/dir/index.html");
  7680. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7681. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7682. Request req;
  7683. req.method = "PROPFIND";
  7684. req.path = "/dir/index.html";
  7685. auto res = cli_.send(req);
  7686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7688. }
  7689. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7690. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7691. cli_.set_keep_alive(true);
  7692. for (auto i = 0; i < 2; i++) {
  7693. Request req;
  7694. req.method = "PROPFIND";
  7695. req.path = "/dav/dir";
  7696. req.body = xml;
  7697. auto res = cli_.send(req);
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7700. EXPECT_EQ(xml, res->body);
  7701. EXPECT_TRUE(cli_.is_socket_open());
  7702. }
  7703. // A built-in method must still be served on the same connection.
  7704. cli_.set_keep_alive(false);
  7705. auto res = cli_.Get("/hi");
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::OK_200, res->status);
  7708. EXPECT_EQ("close", res->get_header_value("Connection"));
  7709. }
  7710. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7711. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7712. Request req;
  7713. req.method = "PROPFIND";
  7714. req.path = "/dav/dir";
  7715. req.set_header("Expect", "100-continue");
  7716. req.body = xml;
  7717. auto res = cli_.send(req);
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7720. EXPECT_EQ(xml, res->body);
  7721. }
  7722. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7723. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7724. TEST_F(ServerTest, Gzip) {
  7725. Headers headers;
  7726. headers.emplace("Accept-Encoding", "gzip, deflate");
  7727. auto res = cli_.Get("/compress", headers);
  7728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7729. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7731. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7732. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7733. "7890123456789012345678901234567890",
  7734. res->body);
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. }
  7737. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7738. Headers headers;
  7739. headers.emplace("Accept-Encoding", "gzip, deflate");
  7740. auto res = cli_.Get("/compress-with-charset", headers);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7743. EXPECT_EQ("application/json; charset=utf-8",
  7744. res->get_header_value("Content-Type"));
  7745. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7746. "7890123456789012345678901234567890",
  7747. res->body);
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7751. Headers headers;
  7752. headers.emplace("Accept-Encoding", "");
  7753. auto res = cli_.Get("/compress", headers);
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7756. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7757. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7758. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7759. "7890123456789012345678901234567890",
  7760. res->body);
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. }
  7763. TEST_F(ServerTest, GzipWithContentReceiver) {
  7764. Headers headers;
  7765. headers.emplace("Accept-Encoding", "gzip, deflate");
  7766. std::string body;
  7767. auto res = cli_.Get("/compress", headers,
  7768. [&](const char *data, uint64_t data_length) {
  7769. EXPECT_EQ(100U, data_length);
  7770. body.append(data, data_length);
  7771. return true;
  7772. });
  7773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7774. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7775. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7776. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7777. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7778. "7890123456789012345678901234567890",
  7779. body);
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. }
  7782. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7783. Headers headers;
  7784. headers.emplace("Accept-Encoding", "gzip, deflate");
  7785. cli_.set_decompress(false);
  7786. auto res = cli_.Get("/compress", headers);
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7789. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7790. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7791. EXPECT_EQ(33U, res->body.size());
  7792. EXPECT_EQ(StatusCode::OK_200, res->status);
  7793. }
  7794. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7795. Headers headers;
  7796. headers.emplace("Accept-Encoding", "");
  7797. std::string body;
  7798. auto res = cli_.Get("/compress", headers,
  7799. [&](const char *data, uint64_t data_length) {
  7800. EXPECT_EQ(100U, data_length);
  7801. body.append(data, data_length);
  7802. return true;
  7803. });
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7807. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7808. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7809. "7890123456789012345678901234567890",
  7810. body);
  7811. EXPECT_EQ(StatusCode::OK_200, res->status);
  7812. }
  7813. TEST_F(ServerTest, NoGzip) {
  7814. Headers headers;
  7815. headers.emplace("Accept-Encoding", "gzip, deflate");
  7816. auto res = cli_.Get("/nocompress", headers);
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7819. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7820. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7821. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7822. "7890123456789012345678901234567890",
  7823. res->body);
  7824. EXPECT_EQ(StatusCode::OK_200, res->status);
  7825. }
  7826. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7827. Headers headers;
  7828. headers.emplace("Accept-Encoding", "gzip, deflate");
  7829. std::string body;
  7830. auto res = cli_.Get("/nocompress", headers,
  7831. [&](const char *data, uint64_t data_length) {
  7832. EXPECT_EQ(100U, data_length);
  7833. body.append(data, data_length);
  7834. return true;
  7835. });
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7838. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7839. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7840. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7841. "7890123456789012345678901234567890",
  7842. body);
  7843. EXPECT_EQ(StatusCode::OK_200, res->status);
  7844. }
  7845. TEST_F(ServerTest, MultipartFormDataGzip) {
  7846. UploadFormDataItems items = {
  7847. {"key1", "test", "", ""},
  7848. {"key2", "--abcdefg123", "", ""},
  7849. };
  7850. cli_.set_compress(true);
  7851. auto res = cli_.Post("/compress-multipart", items);
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. }
  7855. #endif
  7856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7857. // Static file compression is opt-in, so these run their own server rather than
  7858. // flipping it on for the shared ServerTest fixture, which would silently
  7859. // rewrite what every other static file test is asserting.
  7860. class StaticFileCompressionTest : public ::testing::Test {
  7861. protected:
  7862. void TearDown() override {
  7863. if (t_.joinable()) {
  7864. svr_.stop();
  7865. t_.join();
  7866. }
  7867. }
  7868. int start(const std::function<void(Server &)> &configure = nullptr) {
  7869. // Serves the same tree as a directory of build-time compressed assets
  7870. // would be served: the mount point names the coding the files are already
  7871. // stored in. Registered before "/" so it is the one that matches.
  7872. svr_.set_mount_point("/pre-encoded", "./www",
  7873. {{"Content-Encoding", "gzip"}});
  7874. svr_.set_mount_point("/", "./www");
  7875. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7876. res.set_file_content("./www/dir/index.html", "text/html");
  7877. });
  7878. svr_.Get("/pre-encoded-file-content",
  7879. [](const Request & /*req*/, Response &res) {
  7880. res.set_header("Content-Encoding", "gzip");
  7881. res.set_file_content("./www/dir/index.html", "text/html");
  7882. });
  7883. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7884. res.set_content_provider(
  7885. 6, "text/plain",
  7886. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7887. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7888. return true;
  7889. });
  7890. });
  7891. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7892. res.set_content_provider(
  7893. 1000, "text/plain",
  7894. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7895. if (offset < 100) {
  7896. std::string data(100, 'A');
  7897. sink.write(data.data(), data.size());
  7898. return true;
  7899. }
  7900. std::this_thread::sleep_for(std::chrono::seconds(2));
  7901. std::string data(900, 'B');
  7902. sink.write(data.data(), data.size());
  7903. return true;
  7904. });
  7905. });
  7906. if (configure) { configure(svr_); }
  7907. auto port = svr_.bind_to_any_port(HOST);
  7908. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7909. svr_.wait_until_ready();
  7910. return port;
  7911. }
  7912. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7913. // Every file under ./www except 1MB.txt is smaller than the default
  7914. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7915. // it out of the way.
  7916. static void enable_without_floor(Server &svr) {
  7917. svr.set_static_file_compression(true);
  7918. svr.set_static_file_compression_min_length(0);
  7919. }
  7920. Server svr_;
  7921. std::thread t_;
  7922. };
  7923. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7924. auto port = start();
  7925. Client cli(HOST, port);
  7926. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7930. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7931. EXPECT_EQ(1048576U, res->body.size());
  7932. }
  7933. TEST_F(StaticFileCompressionTest, MountPoint) {
  7934. auto port = start(enable);
  7935. Client cli(HOST, port);
  7936. cli.set_decompress(false);
  7937. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7941. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7942. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7943. // The response stays self-delimiting: a length, not a chunked body.
  7944. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7945. EXPECT_EQ(std::to_string(res->body.size()),
  7946. res->get_header_value("Content-Length"));
  7947. EXPECT_LT(res->body.size(), 1048576U);
  7948. EXPECT_FALSE(res->body.empty());
  7949. }
  7950. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7951. auto port = start(enable);
  7952. Client cli(HOST, port);
  7953. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7957. EXPECT_EQ(1048576U, res->body.size());
  7958. }
  7959. TEST_F(StaticFileCompressionTest, FileContent) {
  7960. auto port = start(enable_without_floor);
  7961. Client cli(HOST, port);
  7962. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7966. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7967. EXPECT_EQ(104U, res->body.size());
  7968. }
  7969. // A handler that serves an already-encoded file names the coding itself. The
  7970. // file-backed path decided its coding from Accept-Encoding and the content
  7971. // type alone, so it compressed the stored bytes a second time and appended a
  7972. // second Content-Encoding field line.
  7973. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7974. auto port = start(enable_without_floor);
  7975. Client cli(HOST, port);
  7976. cli.set_decompress(false);
  7977. auto res = cli.Get("/pre-encoded-file-content",
  7978. Headers{{"Accept-Encoding", "gzip"}});
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7982. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7983. // Vary belongs to a coding the server chose, and it chose none here.
  7984. EXPECT_FALSE(res->has_header("Vary"));
  7985. // The file travels exactly as it is stored on disk.
  7986. EXPECT_EQ(104U, res->body.size());
  7987. }
  7988. // The 1MB file clears the default floor, so this one runs the configuration a
  7989. // deployment would actually have.
  7990. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7991. auto port = start(enable);
  7992. Client cli(HOST, port);
  7993. cli.set_decompress(false);
  7994. auto res =
  7995. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7999. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8000. EXPECT_FALSE(res->has_header("Vary"));
  8001. EXPECT_EQ(1048576U, res->body.size());
  8002. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8003. }
  8004. TEST_F(StaticFileCompressionTest, Head) {
  8005. auto port = start(enable);
  8006. Client cli(HOST, port);
  8007. cli.set_decompress(false);
  8008. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8009. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8010. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8012. EXPECT_EQ(StatusCode::OK_200, res->status);
  8013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8014. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8015. // HEAD still reports the size a GET would return.
  8016. EXPECT_EQ(get->get_header_value("Content-Length"),
  8017. res->get_header_value("Content-Length"));
  8018. EXPECT_TRUE(res->body.empty());
  8019. }
  8020. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8021. auto port = start(enable);
  8022. Client cli(HOST, port);
  8023. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8024. {"Accept-Encoding", "gzip"}});
  8025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8027. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8028. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8029. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8030. EXPECT_EQ("cd", res->body);
  8031. }
  8032. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8033. auto port = start(enable);
  8034. Client cli(HOST, port);
  8035. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8037. EXPECT_EQ(StatusCode::OK_200, res->status);
  8038. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8039. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8040. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8041. }
  8042. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8043. auto port = start(enable);
  8044. Client cli(HOST, port);
  8045. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8047. EXPECT_EQ(StatusCode::OK_200, res->status);
  8048. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8049. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8050. EXPECT_TRUE(res->body.empty());
  8051. }
  8052. TEST_F(StaticFileCompressionTest, MinLength) {
  8053. auto port = start(enable);
  8054. Client cli(HOST, port);
  8055. // 104 bytes, well under the default floor. Compressing it would add the
  8056. // gzip header and trailer to a body that already fits in one packet.
  8057. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8059. EXPECT_EQ(StatusCode::OK_200, res->status);
  8060. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8061. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8062. }
  8063. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8064. auto port = start([](Server &svr) {
  8065. svr.set_static_file_compression(true);
  8066. svr.set_static_file_compression_min_length(1);
  8067. });
  8068. Client cli(HOST, port);
  8069. cli.set_decompress(false);
  8070. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8072. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8073. // A 9-byte file comes back larger than it went in, because gzip's header and
  8074. // trailer outweigh anything deflate can save. That is the end of the range
  8075. // the floor exists to keep out.
  8076. EXPECT_GT(res->body.size(), 9U);
  8077. }
  8078. TEST_F(StaticFileCompressionTest, MaxLength) {
  8079. auto port = start([](Server &svr) {
  8080. svr.set_static_file_compression(true);
  8081. svr.set_static_file_compression_min_length(0);
  8082. svr.set_static_file_compression_max_length(1024);
  8083. });
  8084. Client cli(HOST, port);
  8085. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8086. // defines `small` as a macro on Windows.
  8087. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8088. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8089. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8090. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8091. // Under it: compressed.
  8092. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8093. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8094. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8095. }
  8096. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8097. auto port = start(enable_without_floor);
  8098. Client cli(HOST, port);
  8099. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8100. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8101. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8102. auto identity_etag = identity->get_header_value("ETag");
  8103. ASSERT_FALSE(identity_etag.empty());
  8104. auto gzipped =
  8105. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8106. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8107. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8108. auto gzip_etag = gzipped->get_header_value("ETag");
  8109. ASSERT_FALSE(gzip_etag.empty());
  8110. // Two representations, two validators.
  8111. EXPECT_NE(identity_etag, gzip_etag);
  8112. // Each one revalidates against the request that would produce it...
  8113. auto fresh =
  8114. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8115. {"If-None-Match", gzip_etag}});
  8116. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8117. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8118. auto fresh_identity =
  8119. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8120. {"If-None-Match", identity_etag}});
  8121. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8122. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8123. // ...and not against the other representation.
  8124. auto crossed =
  8125. cli.Get("/dir/index.html",
  8126. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8127. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8128. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8129. }
  8130. // The opt-in covers responses the server reads off disk itself. A caller's own
  8131. // known-length provider keeps its Content-Length and, more importantly, keeps
  8132. // delivering incrementally: routing it through a compressor would hold every
  8133. // write back until zlib's window filled.
  8134. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8135. auto port = start(enable);
  8136. Client cli(HOST, port);
  8137. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8139. EXPECT_EQ(StatusCode::OK_200, res->status);
  8140. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8141. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8142. EXPECT_EQ("aaabbb", res->body);
  8143. }
  8144. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8145. auto port = start(enable);
  8146. Client cli(HOST, port);
  8147. cli.set_read_timeout(1, 0);
  8148. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8149. Headers{{"Accept-Encoding", "gzip"}});
  8150. ASSERT_TRUE(handle.is_valid());
  8151. // The provider writes 100 bytes and then stalls for longer than the read
  8152. // timeout. Those first bytes have to arrive anyway: run the response through
  8153. // a compressor and zlib holds them until its window fills, so the read would
  8154. // come back empty instead.
  8155. char buf[256];
  8156. auto n = handle.read(buf, sizeof(buf));
  8157. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8158. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8159. }
  8160. #endif
  8161. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8162. TEST_F(ServerTest, Brotli) {
  8163. Headers headers;
  8164. headers.emplace("Accept-Encoding", "br");
  8165. auto res = cli_.Get("/compress", headers);
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8168. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8169. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8170. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8171. "7890123456789012345678901234567890",
  8172. res->body);
  8173. EXPECT_EQ(StatusCode::OK_200, res->status);
  8174. }
  8175. #endif
  8176. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8177. TEST_F(ServerTest, Zstd) {
  8178. Headers headers;
  8179. headers.emplace("Accept-Encoding", "zstd");
  8180. auto res = cli_.Get("/compress", headers);
  8181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8182. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8183. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8184. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8185. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8186. "7890123456789012345678901234567890",
  8187. res->body);
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. }
  8190. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8191. Headers headers;
  8192. headers.emplace("Accept-Encoding", "");
  8193. auto res = cli_.Get("/compress", headers);
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8197. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8198. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8199. "7890123456789012345678901234567890",
  8200. res->body);
  8201. EXPECT_EQ(StatusCode::OK_200, res->status);
  8202. }
  8203. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8204. Headers headers;
  8205. headers.emplace("Accept-Encoding", "zstd");
  8206. std::string body;
  8207. auto res = cli_.Get("/compress", headers,
  8208. [&](const char *data, uint64_t data_length) {
  8209. EXPECT_EQ(100U, data_length);
  8210. body.append(data, data_length);
  8211. return true;
  8212. });
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8215. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8216. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8217. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8218. "7890123456789012345678901234567890",
  8219. body);
  8220. EXPECT_EQ(StatusCode::OK_200, res->status);
  8221. }
  8222. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8223. Headers headers;
  8224. headers.emplace("Accept-Encoding", "zstd");
  8225. cli_.set_decompress(false);
  8226. auto res = cli_.Get("/compress", headers);
  8227. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8228. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8229. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8230. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8234. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8235. EXPECT_EQ(StatusCode::OK_200, res->status);
  8236. ASSERT_EQ(26U, res->body.size());
  8237. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8238. 0);
  8239. }
  8240. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8241. Headers headers;
  8242. headers.emplace("Accept-Encoding", "");
  8243. std::string body;
  8244. auto res = cli_.Get("/compress", headers,
  8245. [&](const char *data, uint64_t data_length) {
  8246. EXPECT_EQ(100U, data_length);
  8247. body.append(data, data_length);
  8248. return true;
  8249. });
  8250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8251. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8252. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8253. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8254. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8255. "7890123456789012345678901234567890",
  8256. body);
  8257. EXPECT_EQ(StatusCode::OK_200, res->status);
  8258. }
  8259. TEST_F(ServerTest, NoZstd) {
  8260. Headers headers;
  8261. headers.emplace("Accept-Encoding", "zstd");
  8262. auto res = cli_.Get("/nocompress", headers);
  8263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8264. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8265. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8266. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8267. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8268. "7890123456789012345678901234567890",
  8269. res->body);
  8270. EXPECT_EQ(StatusCode::OK_200, res->status);
  8271. }
  8272. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8273. Headers headers;
  8274. headers.emplace("Accept-Encoding", "zstd");
  8275. std::string body;
  8276. auto res = cli_.Get("/nocompress", headers,
  8277. [&](const char *data, uint64_t data_length) {
  8278. EXPECT_EQ(100U, data_length);
  8279. body.append(data, data_length);
  8280. return true;
  8281. });
  8282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8283. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8284. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8285. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8286. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8287. "7890123456789012345678901234567890",
  8288. body);
  8289. EXPECT_EQ(StatusCode::OK_200, res->status);
  8290. }
  8291. // TODO: How to enable zstd ??
  8292. TEST_F(ServerTest, MultipartFormDataZstd) {
  8293. UploadFormDataItems items = {
  8294. {"key1", "test", "", ""},
  8295. {"key2", "--abcdefg123", "", ""},
  8296. };
  8297. Headers headers;
  8298. headers.emplace("Accept-Encoding", "zstd");
  8299. cli_.set_compress(true);
  8300. auto res = cli_.Post("/compress-multipart", headers, items);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. }
  8304. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8305. Headers headers;
  8306. headers.emplace("Accept-Encoding", "zstd");
  8307. cli_.set_compress(true);
  8308. auto res = cli_.Put(
  8309. "/put", headers, 3,
  8310. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8311. sink.os << "PUT";
  8312. return true;
  8313. },
  8314. "text/plain");
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::OK_200, res->status);
  8317. EXPECT_EQ("PUT", res->body);
  8318. }
  8319. // Pre-compression logging tests
  8320. TEST_F(ServerTest, PreCompressionLogging) {
  8321. // Test data for compression (matches the actual /compress endpoint content)
  8322. const std::string test_content =
  8323. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8324. "3456789012345678901234567890";
  8325. // Variables to capture logging data
  8326. std::string pre_compression_body;
  8327. std::string pre_compression_content_type;
  8328. std::string pre_compression_content_encoding;
  8329. std::string post_compression_body;
  8330. std::string post_compression_content_type;
  8331. std::string post_compression_content_encoding;
  8332. // Set up pre-compression logger
  8333. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8334. const Response &res) {
  8335. pre_compression_body = res.body;
  8336. pre_compression_content_type = res.get_header_value("Content-Type");
  8337. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8338. });
  8339. // Set up post-compression logger
  8340. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8341. post_compression_body = res.body;
  8342. post_compression_content_type = res.get_header_value("Content-Type");
  8343. post_compression_content_encoding =
  8344. res.get_header_value("Content-Encoding");
  8345. });
  8346. // Test with gzip compression
  8347. Headers headers;
  8348. headers.emplace("Accept-Encoding", "gzip");
  8349. auto res = cli_.Get("/compress", headers);
  8350. // Verify response was compressed
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8354. // Verify pre-compression logger captured uncompressed content
  8355. EXPECT_EQ(test_content, pre_compression_body);
  8356. EXPECT_EQ("text/plain", pre_compression_content_type);
  8357. EXPECT_TRUE(pre_compression_content_encoding
  8358. .empty()); // No encoding header before compression
  8359. // Verify post-compression logger captured compressed content
  8360. EXPECT_NE(test_content,
  8361. post_compression_body); // Should be different after compression
  8362. EXPECT_EQ("text/plain", post_compression_content_type);
  8363. EXPECT_EQ("gzip", post_compression_content_encoding);
  8364. // Verify compressed content is smaller
  8365. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8366. }
  8367. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8368. const std::string test_content =
  8369. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8370. "3456789012345678901234567890";
  8371. std::string pre_compression_body;
  8372. std::string post_compression_body;
  8373. svr_.set_pre_compression_logger(
  8374. [&](const Request & /*req*/, const Response &res) {
  8375. pre_compression_body = res.body;
  8376. });
  8377. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8378. post_compression_body = res.body;
  8379. });
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "br");
  8382. auto res = cli_.Get("/compress", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ(StatusCode::OK_200, res->status);
  8385. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8386. // Verify pre-compression content is uncompressed
  8387. EXPECT_EQ(test_content, pre_compression_body);
  8388. // Verify post-compression content is compressed
  8389. EXPECT_NE(test_content, post_compression_body);
  8390. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8391. }
  8392. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8393. const std::string test_content =
  8394. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8395. "3456789012345678901234567890";
  8396. std::string pre_compression_body;
  8397. std::string post_compression_body;
  8398. svr_.set_pre_compression_logger(
  8399. [&](const Request & /*req*/, const Response &res) {
  8400. pre_compression_body = res.body;
  8401. });
  8402. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8403. post_compression_body = res.body;
  8404. });
  8405. // Request without compression (use /nocompress endpoint)
  8406. Headers headers;
  8407. auto res = cli_.Get("/nocompress", headers);
  8408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8411. // Pre-compression logger should not be called when no compression is applied
  8412. EXPECT_TRUE(
  8413. pre_compression_body.empty()); // Pre-compression logger not called
  8414. EXPECT_EQ(
  8415. test_content,
  8416. post_compression_body); // Post-compression logger captures final content
  8417. }
  8418. TEST_F(ServerTest, LoggerSeesContentLength) {
  8419. size_t logged_content_length = 0;
  8420. std::string logged_content_length_header;
  8421. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8422. logged_content_length = res.content_length_;
  8423. logged_content_length_header = res.get_header_value("Content-Length");
  8424. });
  8425. auto res = cli_.Get("/nocompress");
  8426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8427. EXPECT_EQ(StatusCode::OK_200, res->status);
  8428. EXPECT_EQ(res->body.size(), logged_content_length);
  8429. EXPECT_EQ(std::to_string(logged_content_length),
  8430. logged_content_length_header);
  8431. }
  8432. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8433. const std::string test_content =
  8434. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8435. "3456789012345678901234567890";
  8436. std::string pre_compression_body;
  8437. bool pre_logger_called = false;
  8438. // Set only pre-compression logger
  8439. svr_.set_pre_compression_logger(
  8440. [&](const Request & /*req*/, const Response &res) {
  8441. pre_compression_body = res.body;
  8442. pre_logger_called = true;
  8443. });
  8444. Headers headers;
  8445. headers.emplace("Accept-Encoding", "gzip");
  8446. auto res = cli_.Get("/compress", headers);
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8450. // Verify pre-compression logger was called
  8451. EXPECT_TRUE(pre_logger_called);
  8452. EXPECT_EQ(test_content, pre_compression_body);
  8453. }
  8454. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8455. {
  8456. // Test with Expect: 100-continue header - success case
  8457. // Server returns 100 Continue, client sends body, server returns 200 OK
  8458. Request req;
  8459. req.method = "POST";
  8460. req.path = "/post-large";
  8461. req.set_header("Expect", "100-continue");
  8462. req.body = LARGE_DATA;
  8463. Response res;
  8464. auto error = Error::Success;
  8465. cli_.set_keep_alive(true);
  8466. auto ret = cli_.send(req, res, error);
  8467. EXPECT_TRUE(ret);
  8468. EXPECT_EQ(StatusCode::OK_200, res.status);
  8469. EXPECT_EQ(LARGE_DATA, res.body);
  8470. }
  8471. {
  8472. // Test with Expect: 100-continue header - error case
  8473. // Client should not send the body when server returns an error
  8474. Request req;
  8475. req.method = "POST";
  8476. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8477. req.set_header("Expect", "100-continue");
  8478. req.body = LARGE_DATA;
  8479. Response res;
  8480. auto error = Error::Success;
  8481. auto start = std::chrono::high_resolution_clock::now();
  8482. cli_.set_keep_alive(true);
  8483. auto ret = cli_.send(req, res, error);
  8484. auto end = std::chrono::high_resolution_clock::now();
  8485. auto elapsed =
  8486. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8487. .count();
  8488. // With Expect: 100-continue, request completes successfully but with error
  8489. EXPECT_TRUE(ret);
  8490. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8491. EXPECT_EQ("close", res.get_header_value("Connection"));
  8492. EXPECT_FALSE(cli_.is_socket_open());
  8493. EXPECT_LE(elapsed, 2000);
  8494. }
  8495. {
  8496. // Send an extra GET request to ensure error recovery without hanging
  8497. Request req;
  8498. req.method = "GET";
  8499. req.path = "/hi";
  8500. auto start = std::chrono::high_resolution_clock::now();
  8501. auto res = cli_.send(req);
  8502. auto end = std::chrono::high_resolution_clock::now();
  8503. auto elapsed =
  8504. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8505. .count();
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::OK_200, res->status);
  8508. EXPECT_EQ("Hello World!", res->body);
  8509. EXPECT_LE(elapsed, 500);
  8510. }
  8511. }
  8512. TEST(ZstdDecompressor, ChunkedDecompression) {
  8513. std::string data;
  8514. for (size_t i = 0; i < 32 * 1024; ++i) {
  8515. data.push_back(static_cast<char>('a' + i % 26));
  8516. }
  8517. std::string compressed_data;
  8518. {
  8519. httplib::detail::zstd_compressor compressor;
  8520. bool result = compressor.compress(
  8521. data.data(), data.size(),
  8522. /*last=*/true,
  8523. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8524. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8525. compressed_data_size);
  8526. return true;
  8527. });
  8528. ASSERT_TRUE(result);
  8529. }
  8530. std::string decompressed_data;
  8531. {
  8532. httplib::detail::zstd_decompressor decompressor;
  8533. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8534. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8535. size_t chunk_size = 130;
  8536. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8537. chunk_begin += chunk_size) {
  8538. size_t current_chunk_size =
  8539. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8540. bool result = decompressor.decompress(
  8541. compressed_data.data() + chunk_begin, current_chunk_size,
  8542. [&](const char *decompressed_data_chunk,
  8543. size_t decompressed_data_chunk_size) {
  8544. decompressed_data.insert(decompressed_data.size(),
  8545. decompressed_data_chunk,
  8546. decompressed_data_chunk_size);
  8547. return true;
  8548. });
  8549. ASSERT_TRUE(result);
  8550. }
  8551. }
  8552. ASSERT_EQ(data, decompressed_data);
  8553. }
  8554. TEST(ZstdDecompressor, Decompress) {
  8555. std::string original_text = "Compressed with ZSTD";
  8556. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8557. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8558. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8559. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8560. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8561. std::string decompressed_data;
  8562. {
  8563. httplib::detail::zstd_decompressor decompressor;
  8564. bool result = decompressor.decompress(
  8565. compressed_data.data(), compressed_data.size(),
  8566. [&](const char *decompressed_data_chunk,
  8567. size_t decompressed_data_chunk_size) {
  8568. decompressed_data.insert(decompressed_data.size(),
  8569. decompressed_data_chunk,
  8570. decompressed_data_chunk_size);
  8571. return true;
  8572. });
  8573. ASSERT_TRUE(result);
  8574. }
  8575. ASSERT_EQ(original_text, decompressed_data);
  8576. }
  8577. #endif
  8578. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8579. // separate chunks so that the server sees each part in its own read(). Used to
  8580. // place a read boundary at a specific offset of a request body.
  8581. static bool send_request_in_parts(time_t read_timeout_sec,
  8582. const std::vector<std::string> &parts,
  8583. std::string *resp = nullptr,
  8584. int port = PORT) {
  8585. auto error = Error::Success;
  8586. auto client_sock = detail::create_client_socket(
  8587. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8588. /*connection_timeout_sec=*/5, 0,
  8589. /*read_timeout_sec=*/5, 0,
  8590. /*write_timeout_sec=*/5, 0, std::string(), error);
  8591. if (client_sock == INVALID_SOCKET) { return false; }
  8592. auto ret = detail::process_client_socket(
  8593. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8594. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8595. for (size_t i = 0; i < parts.size(); i++) {
  8596. const auto &part = parts[i];
  8597. if (part.size() !=
  8598. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8599. return false;
  8600. }
  8601. if (i + 1 < parts.size()) {
  8602. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8603. }
  8604. }
  8605. char buf[512];
  8606. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8607. while (line_reader.getline()) {
  8608. if (resp) { *resp += line_reader.ptr(); }
  8609. }
  8610. return true;
  8611. });
  8612. detail::close_socket(client_sock);
  8613. return ret;
  8614. }
  8615. // Sends a raw request to a server listening at HOST:PORT.
  8616. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8617. std::string *resp = nullptr, int port = PORT) {
  8618. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8619. }
  8620. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8621. Server svr;
  8622. std::string header_value;
  8623. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8624. header_value = req.get_header_value("foo");
  8625. res.set_content("ok", "text/plain");
  8626. });
  8627. thread t = thread([&] { svr.listen(HOST, PORT); });
  8628. auto se = detail::scope_exit([&] {
  8629. svr.stop();
  8630. t.join();
  8631. ASSERT_FALSE(svr.is_running());
  8632. });
  8633. svr.wait_until_ready();
  8634. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8635. // like characters are not treated the same - use vertical tab and escape.
  8636. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8637. "foo: \t \v bar \x1B\t \r\n"
  8638. "Connection: close\r\n"
  8639. "\r\n";
  8640. std::string res;
  8641. ASSERT_TRUE(send_request(5, req, &res));
  8642. EXPECT_EQ(header_value, "");
  8643. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8644. }
  8645. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8646. Server svr;
  8647. std::string received;
  8648. svr.Get("/order", [&](const Request &req, Response &res) {
  8649. received = entries_to_string(req.headers);
  8650. res.set_content("ok", "text/plain");
  8651. });
  8652. auto port = svr.bind_to_any_port(HOST);
  8653. thread t = thread([&] { svr.listen_after_bind(); });
  8654. auto se = detail::scope_exit([&] {
  8655. svr.stop();
  8656. t.join();
  8657. ASSERT_FALSE(svr.is_running());
  8658. });
  8659. svr.wait_until_ready();
  8660. const std::string req = "GET /order HTTP/1.1\r\n"
  8661. "X-First: 1\r\n"
  8662. "X-Dup: a\r\n"
  8663. "X-Second: 2\r\n"
  8664. "X-Dup: b\r\n"
  8665. "Connection: close\r\n"
  8666. "\r\n";
  8667. std::string res;
  8668. ASSERT_TRUE(send_request(5, req, &res, port));
  8669. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8670. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8671. }
  8672. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8673. Server svr;
  8674. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8675. res.set_header("Set-Cookie", "first=1");
  8676. res.set_header("X-Between", "y");
  8677. res.set_header("Set-Cookie", "second=2");
  8678. res.set_content("ok", "text/plain");
  8679. });
  8680. auto port = svr.bind_to_any_port(HOST);
  8681. thread t = thread([&] { svr.listen_after_bind(); });
  8682. auto se = detail::scope_exit([&] {
  8683. svr.stop();
  8684. t.join();
  8685. ASSERT_FALSE(svr.is_running());
  8686. });
  8687. svr.wait_until_ready();
  8688. Client cli(HOST, port);
  8689. auto res = cli.Get("/cookies");
  8690. ASSERT_TRUE(res);
  8691. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8692. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8693. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8694. }
  8695. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8696. Server svr;
  8697. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8698. auto i = new int(0);
  8699. res.set_header("Trailer", "X-Safe, X-Reflected");
  8700. res.set_chunked_content_provider(
  8701. "text/plain",
  8702. [i](size_t /*offset*/, DataSink &sink) {
  8703. if (*i == 0) {
  8704. sink.os << "body";
  8705. } else {
  8706. Headers trailer;
  8707. // A valid trailer that must survive.
  8708. trailer.emplace("X-Safe", "safe");
  8709. // Attacker-controlled value carrying CR/LF (response splitting).
  8710. trailer.emplace("X-Reflected",
  8711. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8712. // Attacker-controlled name carrying CR/LF.
  8713. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8714. sink.done_with_trailer(trailer);
  8715. }
  8716. (*i)++;
  8717. return true;
  8718. },
  8719. [i](bool /*success*/) { delete i; });
  8720. });
  8721. thread t = thread([&] { svr.listen(HOST, PORT); });
  8722. auto se = detail::scope_exit([&] {
  8723. svr.stop();
  8724. t.join();
  8725. ASSERT_FALSE(svr.is_running());
  8726. });
  8727. svr.wait_until_ready();
  8728. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8729. "Host: " + HOST +
  8730. "\r\n"
  8731. "Connection: close\r\n"
  8732. "\r\n";
  8733. std::string res;
  8734. ASSERT_TRUE(send_request(5, req, &res));
  8735. // The injected fields must not appear anywhere in the raw response.
  8736. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8737. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8738. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8739. // Invalid trailers are dropped entirely, matching set_header().
  8740. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8741. // The valid trailer still passes through.
  8742. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8743. }
  8744. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8745. Server svr;
  8746. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8747. // res.headers is a public field an application can populate directly,
  8748. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8749. // A valid header that must survive.
  8750. res.headers.emplace("X-Safe", "safe");
  8751. // Attacker-controlled value carrying CR/LF (response splitting).
  8752. res.headers.emplace("X-Reflected",
  8753. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8754. // Attacker-controlled name carrying CR/LF.
  8755. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8756. res.set_content("body", "text/plain");
  8757. });
  8758. thread t = thread([&] { svr.listen(HOST, PORT); });
  8759. auto se = detail::scope_exit([&] {
  8760. svr.stop();
  8761. t.join();
  8762. ASSERT_FALSE(svr.is_running());
  8763. });
  8764. svr.wait_until_ready();
  8765. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8766. "Host: " + HOST +
  8767. "\r\n"
  8768. "Connection: close\r\n"
  8769. "\r\n";
  8770. std::string res;
  8771. ASSERT_TRUE(send_request(5, req, &res));
  8772. // The injected fields must not appear anywhere in the raw response.
  8773. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8774. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8775. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8776. // Invalid headers are dropped entirely, matching set_header().
  8777. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8778. // The valid header still passes through.
  8779. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8780. }
  8781. // Forward declaration: in split builds split.py strips `inline` and moves the
  8782. // definition into httplib.cc, so detail::write_request_line is not visible from
  8783. // the public httplib.h. Re-declaring it here lets the tests link against the
  8784. // symbol in both header-only and split builds.
  8785. namespace httplib {
  8786. namespace detail {
  8787. ssize_t write_request_line(Stream &strm, const std::string &method,
  8788. const std::string &path);
  8789. } // namespace detail
  8790. } // namespace httplib
  8791. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8792. // A well-formed target is written verbatim.
  8793. {
  8794. detail::BufferStream strm;
  8795. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8796. EXPECT_GT(n, 0);
  8797. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8798. }
  8799. // A target carrying CR/LF, SP or other control octets must be rejected
  8800. // before anything reaches the wire, otherwise it splits the request line and
  8801. // injects a header or a whole request.
  8802. const std::string evil_targets[] = {
  8803. "/a\r\nInjected: pwned",
  8804. "/a\rInjected",
  8805. "/a\nInjected",
  8806. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8807. "/a b",
  8808. "/a\tb",
  8809. "/a\x7f",
  8810. };
  8811. for (const auto &evil : evil_targets) {
  8812. detail::BufferStream strm;
  8813. auto n = detail::write_request_line(strm, "GET", evil);
  8814. EXPECT_LT(n, 0);
  8815. EXPECT_TRUE(strm.get_buffer().empty());
  8816. }
  8817. }
  8818. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8819. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8820. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8821. // target reaches write_request. The client must fail cleanly with
  8822. // Error::Write instead of putting a request-line-less, header-injecting
  8823. // request on the wire.
  8824. Server svr;
  8825. svr.Get("/a", [](const Request &, Response &res) {
  8826. res.set_content("ok", "text/plain");
  8827. });
  8828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8829. auto se = detail::scope_exit([&] {
  8830. svr.stop();
  8831. thread.join();
  8832. ASSERT_FALSE(svr.is_running());
  8833. });
  8834. svr.wait_until_ready();
  8835. {
  8836. Client cli(HOST, PORT);
  8837. cli.set_path_encode(false);
  8838. // The request is rejected before anything is written, so the connection
  8839. // stays silent and the subsequent response read would otherwise block for
  8840. // the full default read timeout. Shorten it -- the assertion is on the
  8841. // error, not the timeout.
  8842. cli.set_read_timeout(1, 0);
  8843. auto res = cli.Get("/a\r\nInjected: pwned");
  8844. EXPECT_FALSE(res);
  8845. EXPECT_EQ(Error::Write, res.error());
  8846. }
  8847. }
  8848. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8849. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8850. // including extension methods.
  8851. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8852. for (const auto &method : good_methods) {
  8853. detail::BufferStream strm;
  8854. auto n = detail::write_request_line(strm, method, "/");
  8855. EXPECT_GT(n, 0);
  8856. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8857. }
  8858. // A method carrying CR/LF would split the request line and smuggle a whole
  8859. // request ahead of the real one. A space or an empty method corrupts the
  8860. // request line. All must be rejected before anything reaches the wire.
  8861. const std::string evil_methods[] = {
  8862. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8863. "GET\r\nInjected: pwned",
  8864. "GET\r",
  8865. "GET\n",
  8866. "GE T",
  8867. "",
  8868. };
  8869. for (const auto &evil : evil_methods) {
  8870. detail::BufferStream strm;
  8871. auto n = detail::write_request_line(strm, evil, "/");
  8872. EXPECT_LT(n, 0);
  8873. EXPECT_TRUE(strm.get_buffer().empty());
  8874. }
  8875. }
  8876. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8877. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8878. // through Client::send must fail with Error::Write and no request, neither
  8879. // the smuggled one nor the real one, may reach the server.
  8880. Server svr;
  8881. std::atomic<int> request_count(0);
  8882. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8883. request_count++;
  8884. res.status = StatusCode::OK_200;
  8885. return Server::HandlerResponse::Handled;
  8886. });
  8887. auto port = svr.bind_to_any_port(HOST);
  8888. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8889. auto se = detail::scope_exit([&] {
  8890. svr.stop();
  8891. thread.join();
  8892. ASSERT_FALSE(svr.is_running());
  8893. });
  8894. svr.wait_until_ready();
  8895. {
  8896. Client cli(HOST, port);
  8897. const std::string evil_methods[] = {
  8898. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8899. "GE T",
  8900. "",
  8901. };
  8902. for (const auto &evil : evil_methods) {
  8903. Request req;
  8904. req.method = evil;
  8905. req.path = "/";
  8906. auto res = cli.send(req);
  8907. EXPECT_FALSE(res);
  8908. EXPECT_EQ(Error::Write, res.error());
  8909. }
  8910. auto handle =
  8911. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8912. EXPECT_FALSE(handle.is_valid());
  8913. EXPECT_EQ(Error::Write, handle.error);
  8914. // A valid request on the same client still goes through.
  8915. auto res = cli.Get("/");
  8916. ASSERT_TRUE(res);
  8917. EXPECT_EQ(StatusCode::OK_200, res->status);
  8918. }
  8919. EXPECT_EQ(1, request_count.load());
  8920. }
  8921. // Sends a raw request and verifies that there isn't a crash or exception.
  8922. static void test_raw_request(const std::string &req,
  8923. std::string *out = nullptr) {
  8924. Server svr;
  8925. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8926. res.set_content("ok", "text/plain");
  8927. });
  8928. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8929. res.set_content("ok", "text/plain");
  8930. });
  8931. svr.Get("/header_field_value_check",
  8932. [&](const Request & /*req*/, Response &res) {
  8933. res.set_content("ok", "text/plain");
  8934. });
  8935. svr.CustomRoute("PROPFIND", "/dav",
  8936. [&](const Request & /*req*/, Response &res) {
  8937. res.status = StatusCode::MultiStatus_207;
  8938. });
  8939. // Server read timeout must be longer than the client read timeout for the
  8940. // bug to reproduce, probably to force the server to process a request
  8941. // without a trailing blank line.
  8942. const time_t client_read_timeout_sec = 1;
  8943. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8944. bool listen_thread_ok = false;
  8945. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8946. auto se = detail::scope_exit([&] {
  8947. svr.stop();
  8948. t.join();
  8949. ASSERT_FALSE(svr.is_running());
  8950. EXPECT_TRUE(listen_thread_ok);
  8951. });
  8952. svr.wait_until_ready();
  8953. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8954. }
  8955. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8956. // A certain header line causes an exception if the header property is parsed
  8957. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8958. test_raw_request(
  8959. "GET /hi HTTP/1.1\r\n"
  8960. " : "
  8961. " "
  8962. " ");
  8963. }
  8964. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8965. // A certain header line causes an exception if the header property *name* is
  8966. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8967. // greedy matcher and requires backtracking when there are a lot of ":"
  8968. // characters.
  8969. // This occurs with libc++ but not libstdc++.
  8970. test_raw_request(
  8971. "GET /hi HTTP/1.1\r\n"
  8972. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8973. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8974. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8975. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8976. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8977. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8978. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8979. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8980. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8981. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8982. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8983. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8984. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8985. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8986. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8987. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8988. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8989. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8990. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8991. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8992. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8993. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8994. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8995. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8996. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8997. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8998. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8999. "&&&%%%");
  9000. }
  9001. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9002. // Make sure this doesn't crash the server.
  9003. // In a previous version of the header line regex, the "\r" rendered the line
  9004. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9005. // a new position where the leading white space ended and the field value
  9006. // began.
  9007. // The crash occurs with libc++ but not libstdc++.
  9008. test_raw_request("GET /hi HTTP/1.1\r\n"
  9009. "a:" +
  9010. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9011. "\r\n"
  9012. "\r\n");
  9013. }
  9014. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9015. std::string out;
  9016. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9017. "Content-Type: text/plain\r\n"
  9018. "Transfer-Encoding: chunked\r\n"
  9019. "\r\n"
  9020. "nothex\r\n",
  9021. &out);
  9022. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9023. }
  9024. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9025. std::string out;
  9026. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9027. "Content-Type: text/plain\r\n"
  9028. "Transfer-Encoding: chunked\r\n"
  9029. "\r\n"
  9030. "3\r\n"
  9031. "xyz\r\n"
  9032. "NaN\r\n",
  9033. &out);
  9034. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9035. }
  9036. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9037. std::string out;
  9038. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9039. "Content-Type: text/plain\r\n"
  9040. "Transfer-Encoding: chunked\r\n"
  9041. "\r\n"
  9042. // Length is too large for 64 bits.
  9043. "1ffffffffffffffff\r\n"
  9044. "xyz\r\n",
  9045. &out);
  9046. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9047. }
  9048. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9049. test_raw_request("GET /hi HTTP/1.1\r\n"
  9050. "Content-Type: text/plain\r\n\r");
  9051. }
  9052. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9053. std::string out;
  9054. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9056. }
  9057. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9058. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9059. std::string out;
  9060. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9061. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9062. }
  9063. }
  9064. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9065. std::string out;
  9066. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9067. "Connection: close\r\n\r\n",
  9068. &out);
  9069. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9070. }
  9071. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9072. Server svr;
  9073. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9074. EXPECT_TRUE(!req.remote_addr.empty());
  9075. });
  9076. thread t = thread([&] { svr.listen(HOST, PORT); });
  9077. auto se = detail::scope_exit([&] {
  9078. svr.stop();
  9079. t.join();
  9080. ASSERT_FALSE(svr.is_running());
  9081. });
  9082. svr.wait_until_ready();
  9083. // Send an invalid request line to trigger Bad Request
  9084. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9085. std::string out;
  9086. ASSERT_TRUE(send_request(5, bad_req, &out));
  9087. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9088. }
  9089. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9090. // answered right away rather than blocking on a read that waits for EOF.
  9091. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9092. std::string out;
  9093. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9094. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9095. }
  9096. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9097. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9098. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9099. for (const auto *method : methods) {
  9100. Server svr;
  9101. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9102. EXPECT_FALSE(svr.is_valid()) << method;
  9103. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9104. }
  9105. }
  9106. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9107. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9108. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9109. for (const auto *method : methods) {
  9110. Server svr;
  9111. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9112. EXPECT_FALSE(svr.is_valid()) << method;
  9113. }
  9114. }
  9115. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9116. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9117. "COPY", "MOVE", "LOCK",
  9118. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9119. Server svr;
  9120. for (const auto *method : methods) {
  9121. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9122. }
  9123. EXPECT_TRUE(svr.is_valid());
  9124. }
  9125. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9126. Server svr;
  9127. svr.CustomRoute("POST", "/x",
  9128. [](const Request &, Response &, const ContentReader &) {});
  9129. EXPECT_FALSE(svr.is_valid());
  9130. }
  9131. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9132. Server svr;
  9133. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9134. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9135. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9136. EXPECT_FALSE(svr.is_valid());
  9137. }
  9138. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9139. Server svr;
  9140. auto captured = Error::Success;
  9141. svr.set_error_logger(
  9142. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9143. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9144. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9145. }
  9146. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9147. std::string out;
  9148. std::string request(
  9149. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9150. test_raw_request(request, &out);
  9151. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9152. }
  9153. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9154. std::string out;
  9155. std::string request(
  9156. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9157. test_raw_request(request, &out);
  9158. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9159. }
  9160. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9161. std::string out;
  9162. std::string request(
  9163. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9164. test_raw_request(request, &out);
  9165. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9166. }
  9167. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9168. std::string out;
  9169. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9170. "Test: \r\n\r\n",
  9171. &out);
  9172. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9173. }
  9174. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9175. Server svr;
  9176. std::string x_custom;
  9177. std::string cookie;
  9178. std::string xff;
  9179. std::string x_unicode;
  9180. std::string x_iis;
  9181. svr.Get("/check", [&](const Request &req, Response &res) {
  9182. x_custom = req.get_header_value("X-Custom");
  9183. cookie = req.get_header_value("Cookie");
  9184. xff = req.get_header_value("X-Forwarded-For");
  9185. x_unicode = req.get_header_value("X-Unicode");
  9186. x_iis = req.get_header_value("X-IIS");
  9187. res.set_content("ok", "text/plain");
  9188. });
  9189. thread t = thread([&] { svr.listen(HOST, PORT); });
  9190. auto se = detail::scope_exit([&] {
  9191. svr.stop();
  9192. t.join();
  9193. ASSERT_FALSE(svr.is_running());
  9194. });
  9195. svr.wait_until_ready();
  9196. const std::string req = "GET /check HTTP/1.1\r\n"
  9197. "Host: localhost\r\n"
  9198. "X-Custom: a%0D%0AInjected: b\r\n"
  9199. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9200. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9201. "X-Unicode: %E3%81%82\r\n"
  9202. "X-IIS: %u00E9\r\n"
  9203. "Connection: close\r\n"
  9204. "\r\n";
  9205. std::string res;
  9206. ASSERT_TRUE(send_request(5, req, &res));
  9207. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9208. // Every value must be returned verbatim (wire form), with no decoding.
  9209. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9210. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9211. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9212. EXPECT_EQ("%E3%81%82", x_unicode);
  9213. EXPECT_EQ("%u00E9", x_iis);
  9214. }
  9215. // Applications that previously relied on automatic percent-decoding can
  9216. // reproduce the old behavior by explicitly calling decode_path_component()
  9217. // or, for RFC 3986 conformance, decode_uri_component().
  9218. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9219. Server svr;
  9220. std::string decoded;
  9221. svr.Get("/check", [&](const Request &req, Response &res) {
  9222. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9223. res.set_content("ok", "text/plain");
  9224. });
  9225. thread t = thread([&] { svr.listen(HOST, PORT); });
  9226. auto se = detail::scope_exit([&] {
  9227. svr.stop();
  9228. t.join();
  9229. ASSERT_FALSE(svr.is_running());
  9230. });
  9231. svr.wait_until_ready();
  9232. const std::string req = "GET /check HTTP/1.1\r\n"
  9233. "Host: localhost\r\n"
  9234. "X-Custom: hello%20world\r\n"
  9235. "Connection: close\r\n"
  9236. "\r\n";
  9237. std::string res;
  9238. ASSERT_TRUE(send_request(5, req, &res));
  9239. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9240. EXPECT_EQ("hello world", decoded);
  9241. }
  9242. // Regression test for #2033. Browsers send Referer values that include
  9243. // percent-encoded characters such as %0A inside the URL. Decoding the
  9244. // header value would either trip the post-decode CR/LF/NUL guard (the
  9245. // original bug, returning 400) or, after that guard was relaxed, silently
  9246. // store a literal LF — both unacceptable. The wire form must round-trip.
  9247. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9248. Server svr;
  9249. std::string referer;
  9250. svr.Get("/check", [&](const Request &req, Response &res) {
  9251. referer = req.get_header_value("Referer");
  9252. res.set_content("ok", "text/plain");
  9253. });
  9254. thread t = thread([&] { svr.listen(HOST, PORT); });
  9255. auto se = detail::scope_exit([&] {
  9256. svr.stop();
  9257. t.join();
  9258. ASSERT_FALSE(svr.is_running());
  9259. });
  9260. svr.wait_until_ready();
  9261. const std::string req = "GET /check HTTP/1.1\r\n"
  9262. "Host: localhost\r\n"
  9263. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9264. "Connection: close\r\n"
  9265. "\r\n";
  9266. std::string res;
  9267. ASSERT_TRUE(send_request(5, req, &res));
  9268. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9269. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9270. }
  9271. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9272. Server svr;
  9273. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9274. res.set_header("Cache-Control", "no-cache");
  9275. res.set_chunked_content_provider(
  9276. "text/event-stream", [](size_t offset, DataSink &sink) {
  9277. std::string s = "data:";
  9278. s += std::to_string(offset);
  9279. s += "\n\n";
  9280. auto ret = sink.write(s.data(), s.size());
  9281. EXPECT_TRUE(ret);
  9282. std::this_thread::sleep_for(std::chrono::seconds(1));
  9283. return true;
  9284. });
  9285. });
  9286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9287. svr.wait_until_ready();
  9288. Client client(HOST, PORT);
  9289. const Headers headers = {{"Accept", "text/event-stream"}};
  9290. auto get_thread = std::thread([&client, &headers]() {
  9291. auto res = client.Get(
  9292. "/events", headers,
  9293. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9294. });
  9295. auto se = detail::scope_exit([&] {
  9296. svr.stop();
  9297. get_thread.join();
  9298. listen_thread.join();
  9299. ASSERT_FALSE(svr.is_running());
  9300. });
  9301. // Give GET time to get a few messages.
  9302. std::this_thread::sleep_for(std::chrono::seconds(2));
  9303. }
  9304. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9305. httplib::Server svr;
  9306. svr.Post("/hi",
  9307. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9308. res.status = StatusCode::OK_200;
  9309. });
  9310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9311. svr.wait_until_ready();
  9312. Client cli(HOST, PORT);
  9313. auto res = cli.Post("/hi", "data", "text/plain");
  9314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9315. EXPECT_EQ(StatusCode::OK_200, res->status);
  9316. svr.stop();
  9317. thread.join();
  9318. ASSERT_FALSE(svr.is_running());
  9319. res = cli.Post("/hi", "data", "text/plain");
  9320. ASSERT_FALSE(res);
  9321. }
  9322. TEST(ServerStopTest, ListenFailure) {
  9323. Server svr;
  9324. auto t = thread([&]() {
  9325. auto ret = svr.listen("????", PORT);
  9326. EXPECT_FALSE(ret);
  9327. });
  9328. svr.wait_until_ready();
  9329. svr.stop();
  9330. t.join();
  9331. }
  9332. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9333. TEST(ServerStopTest, Decommision) {
  9334. Server svr;
  9335. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9336. for (int i = 0; i < 4; i++) {
  9337. auto is_even = !(i % 2);
  9338. std::thread t{[&] {
  9339. try {
  9340. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9341. if (is_even) {
  9342. throw std::runtime_error("Some thing that happens to go wrong.");
  9343. }
  9344. svr.listen(HOST, PORT);
  9345. } catch (...) { svr.decommission(); }
  9346. }};
  9347. svr.wait_until_ready();
  9348. // Server is up
  9349. {
  9350. Client cli(HOST, PORT);
  9351. auto res = cli.Get("/hi");
  9352. if (is_even) {
  9353. EXPECT_FALSE(res);
  9354. } else {
  9355. EXPECT_TRUE(res);
  9356. EXPECT_EQ("hi...", res->body);
  9357. }
  9358. }
  9359. svr.stop();
  9360. t.join();
  9361. // Server is down...
  9362. {
  9363. Client cli(HOST, PORT);
  9364. auto res = cli.Get("/hi");
  9365. EXPECT_FALSE(res);
  9366. }
  9367. }
  9368. }
  9369. #endif
  9370. // Helper function for string body upload progress tests
  9371. template <typename SetupHandler, typename ClientCall>
  9372. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9373. ClientCall &&client_call,
  9374. const string &body) {
  9375. Server svr;
  9376. setup_handler(svr);
  9377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9378. auto se = detail::scope_exit([&] {
  9379. svr.stop();
  9380. t.join();
  9381. });
  9382. svr.wait_until_ready();
  9383. Client cli(HOST, PORT);
  9384. vector<uint64_t> progress_values;
  9385. bool progress_called = false;
  9386. auto res =
  9387. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9388. progress_values.push_back(current);
  9389. progress_called = true;
  9390. return true;
  9391. });
  9392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9393. EXPECT_EQ(200, res->status);
  9394. EXPECT_TRUE(progress_called);
  9395. }
  9396. TEST(UploadProgressTest, PostStringBodyBasic) {
  9397. TestStringBodyUploadProgress(
  9398. [](Server &svr) {
  9399. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9400. res.set_content("received", "text/plain");
  9401. });
  9402. },
  9403. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9404. return cli.Post("/test", body, "text/plain", progress_callback);
  9405. },
  9406. "test data for upload progress");
  9407. }
  9408. TEST(UploadProgressTest, PutStringBodyBasic) {
  9409. TestStringBodyUploadProgress(
  9410. [](Server &svr) {
  9411. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9412. res.set_content("put received", "text/plain");
  9413. });
  9414. },
  9415. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9416. return cli.Put("/test", body, "text/plain", progress_callback);
  9417. },
  9418. "put test data for upload progress");
  9419. }
  9420. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9421. TestStringBodyUploadProgress(
  9422. [](Server &svr) {
  9423. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9424. res.set_content("patch received", "text/plain");
  9425. });
  9426. },
  9427. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9428. return cli.Patch("/test", body, "text/plain", progress_callback);
  9429. },
  9430. "patch test data for upload progress");
  9431. }
  9432. // Helper function for content provider upload progress tests
  9433. template <typename SetupHandler, typename ClientCall>
  9434. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9435. ClientCall &&client_call) {
  9436. Server svr;
  9437. setup_handler(svr);
  9438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9439. auto se = detail::scope_exit([&] {
  9440. svr.stop();
  9441. t.join();
  9442. });
  9443. svr.wait_until_ready();
  9444. Client cli(HOST, PORT);
  9445. vector<uint64_t> progress_values;
  9446. auto res =
  9447. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9448. progress_values.push_back(current);
  9449. return true;
  9450. });
  9451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9452. EXPECT_EQ(200, res->status);
  9453. EXPECT_FALSE(progress_values.empty());
  9454. }
  9455. TEST(UploadProgressTest, PostContentProviderProgress) {
  9456. TestContentProviderUploadProgress(
  9457. [](Server &svr) {
  9458. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9459. res.set_content("provider received", "text/plain");
  9460. });
  9461. },
  9462. [](Client &cli, UploadProgress progress_callback) {
  9463. return cli.Post(
  9464. "/test", 10,
  9465. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9466. sink.os << "test data";
  9467. return true;
  9468. },
  9469. "text/plain", progress_callback);
  9470. });
  9471. }
  9472. // Helper function for multipart upload progress tests
  9473. template <typename SetupHandler, typename ClientCall>
  9474. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9475. ClientCall &&client_call,
  9476. const string &endpoint) {
  9477. Server svr;
  9478. setup_handler(svr);
  9479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9480. auto se = detail::scope_exit([&] {
  9481. svr.stop();
  9482. t.join();
  9483. });
  9484. svr.wait_until_ready();
  9485. Client cli(HOST, PORT);
  9486. vector<uint64_t> progress_values;
  9487. UploadFormDataItems items = {
  9488. {"field1", "value1", "", ""},
  9489. {"field2", "longer value for progress tracking test", "", ""},
  9490. {"file1", "file content data for upload progress", "test.txt",
  9491. "text/plain"}};
  9492. auto res = client_call(cli, endpoint, items,
  9493. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9494. progress_values.push_back(current);
  9495. return true;
  9496. });
  9497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9498. EXPECT_EQ(200, res->status);
  9499. EXPECT_FALSE(progress_values.empty());
  9500. }
  9501. TEST(UploadProgressTest, PostMultipartProgress) {
  9502. TestMultipartUploadProgress(
  9503. [](Server &svr) {
  9504. svr.Post("/multipart", [](const Request &req, Response &res) {
  9505. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9506. res.set_content("multipart received", "text/plain");
  9507. });
  9508. },
  9509. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9510. UploadProgress progress_callback) {
  9511. return cli.Post(endpoint, items, progress_callback);
  9512. },
  9513. "/multipart");
  9514. }
  9515. // Helper function for basic download progress tests
  9516. template <typename SetupHandler, typename ClientCall>
  9517. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9518. ClientCall &&client_call, const string &endpoint,
  9519. size_t expected_content_size) {
  9520. Server svr;
  9521. setup_handler(svr);
  9522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9523. auto se = detail::scope_exit([&] {
  9524. svr.stop();
  9525. t.join();
  9526. });
  9527. svr.wait_until_ready();
  9528. Client cli(HOST, PORT);
  9529. vector<uint64_t> progress_values;
  9530. auto res = client_call(cli, endpoint,
  9531. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9532. progress_values.push_back(current);
  9533. return true;
  9534. });
  9535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9536. EXPECT_EQ(200, res->status);
  9537. EXPECT_FALSE(progress_values.empty());
  9538. EXPECT_EQ(expected_content_size, res->body.size());
  9539. }
  9540. TEST(DownloadProgressTest, GetBasic) {
  9541. TestBasicDownloadProgress(
  9542. [](Server &svr) {
  9543. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9544. string content(1000, 'D');
  9545. res.set_content(content, "text/plain");
  9546. });
  9547. },
  9548. [](Client &cli, const string &endpoint,
  9549. DownloadProgress progress_callback) {
  9550. return cli.Get(endpoint, progress_callback);
  9551. },
  9552. "/download", 1000u);
  9553. }
  9554. // Helper function for content receiver download progress tests
  9555. template <typename SetupHandler, typename ClientCall>
  9556. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9557. ClientCall &&client_call,
  9558. const string &endpoint,
  9559. size_t expected_content_size) {
  9560. Server svr;
  9561. setup_handler(svr);
  9562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9563. auto se = detail::scope_exit([&] {
  9564. svr.stop();
  9565. t.join();
  9566. });
  9567. svr.wait_until_ready();
  9568. Client cli(HOST, PORT);
  9569. vector<uint64_t> progress_values;
  9570. string received_body;
  9571. auto res = client_call(
  9572. cli, endpoint,
  9573. [&](const char *data, size_t data_length) -> bool {
  9574. received_body.append(data, data_length);
  9575. return true;
  9576. },
  9577. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9578. progress_values.push_back(current);
  9579. return true;
  9580. });
  9581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9582. EXPECT_EQ(200, res->status);
  9583. EXPECT_FALSE(progress_values.empty());
  9584. EXPECT_EQ(expected_content_size, received_body.size());
  9585. EXPECT_TRUE(res->body.empty());
  9586. }
  9587. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9588. TestContentReceiverDownloadProgress(
  9589. [](Server &svr) {
  9590. svr.Get("/download-receiver",
  9591. [](const Request & /*req*/, Response &res) {
  9592. string content(2000, 'R');
  9593. res.set_content(content, "text/plain");
  9594. });
  9595. },
  9596. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9597. DownloadProgress progress_callback) {
  9598. return cli.Get(endpoint, content_receiver, progress_callback);
  9599. },
  9600. "/download-receiver", 2000u);
  9601. }
  9602. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9603. // A provider reaching a pass with nothing to hand over - an empty buffer
  9604. // popped off a queue, say - must not be taken to mean the body is finished.
  9605. // It used to end the loop with the terminating chunk unwritten while the
  9606. // server still considered the response complete, so the peer waited for an
  9607. // end that never arrived.
  9608. Server svr;
  9609. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9610. auto step = std::make_shared<int>(0);
  9611. res.set_chunked_content_provider("text/plain",
  9612. [step](size_t /*offset*/, DataSink &sink) {
  9613. switch ((*step)++) {
  9614. case 0: sink.write("", 0); break;
  9615. case 1: sink.write("hello", 5); break;
  9616. default: sink.done(); break;
  9617. }
  9618. return true;
  9619. });
  9620. });
  9621. auto port = svr.bind_to_any_port(HOST);
  9622. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9623. auto listen_se = detail::scope_exit([&] {
  9624. svr.stop();
  9625. listen_thread.join();
  9626. ASSERT_FALSE(svr.is_running());
  9627. });
  9628. svr.wait_until_ready();
  9629. Client cli(HOST, port);
  9630. // Without the fix the body is never terminated, so bound the wait rather
  9631. // than letting the test hang on the default read timeout.
  9632. cli.set_read_timeout(5, 0);
  9633. auto res = cli.Get("/stream");
  9634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9635. EXPECT_EQ(StatusCode::OK_200, res->status);
  9636. EXPECT_EQ("hello", res->body);
  9637. }
  9638. TEST(StreamingTest, NoContentLengthStreaming) {
  9639. Server svr;
  9640. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9641. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9642. if (offset < 6) {
  9643. sink.os << (offset < 3 ? "a" : "b");
  9644. } else {
  9645. sink.done();
  9646. }
  9647. return true;
  9648. });
  9649. });
  9650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9651. auto listen_se = detail::scope_exit([&] {
  9652. svr.stop();
  9653. listen_thread.join();
  9654. ASSERT_FALSE(svr.is_running());
  9655. });
  9656. svr.wait_until_ready();
  9657. Client client(HOST, PORT);
  9658. auto get_thread = std::thread([&client]() {
  9659. std::string s;
  9660. auto res =
  9661. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9662. s += std::string(data, len);
  9663. return true;
  9664. });
  9665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9666. EXPECT_EQ(StatusCode::OK_200, res->status);
  9667. EXPECT_EQ("aaabbb", s);
  9668. });
  9669. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9670. // Give GET time to get a few messages.
  9671. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9672. }
  9673. TEST(MountTest, Unmount) {
  9674. Server svr;
  9675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9676. auto se = detail::scope_exit([&] {
  9677. svr.stop();
  9678. listen_thread.join();
  9679. ASSERT_FALSE(svr.is_running());
  9680. });
  9681. svr.wait_until_ready();
  9682. Client cli("localhost", PORT);
  9683. svr.set_mount_point("/mount2", "./www2");
  9684. auto res = cli.Get("/");
  9685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9687. res = cli.Get("/mount2/dir/test.html");
  9688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9689. EXPECT_EQ(StatusCode::OK_200, res->status);
  9690. svr.set_mount_point("/", "./www");
  9691. res = cli.Get("/dir/");
  9692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9693. EXPECT_EQ(StatusCode::OK_200, res->status);
  9694. svr.remove_mount_point("/");
  9695. res = cli.Get("/dir/");
  9696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9698. svr.remove_mount_point("/mount2");
  9699. res = cli.Get("/mount2/dir/test.html");
  9700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9702. }
  9703. TEST(MountTest, PathSegmentBoundary) {
  9704. Server svr;
  9705. svr.set_mount_point("/mount2", "./www2");
  9706. svr.set_mount_point("/", "./www");
  9707. auto port = svr.bind_to_any_port(HOST);
  9708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9709. auto se = detail::scope_exit([&] {
  9710. svr.stop();
  9711. listen_thread.join();
  9712. ASSERT_FALSE(svr.is_running());
  9713. });
  9714. svr.wait_until_ready();
  9715. Client cli(HOST, port);
  9716. auto res = cli.Get("/mount2/dir/test.html");
  9717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9718. EXPECT_EQ(StatusCode::OK_200, res->status);
  9719. // "/mount2" must not match part-way through a path segment.
  9720. res = cli.Get("/mount2dir/test.html");
  9721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9723. // A mount point ending in '/' keeps matching every path below it.
  9724. res = cli.Get("/dir/test.html");
  9725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9726. EXPECT_EQ(StatusCode::OK_200, res->status);
  9727. }
  9728. TEST(MountTest, Redicect) {
  9729. Server svr;
  9730. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9731. auto se = detail::scope_exit([&] {
  9732. svr.stop();
  9733. listen_thread.join();
  9734. ASSERT_FALSE(svr.is_running());
  9735. });
  9736. svr.set_mount_point("/", "./www");
  9737. svr.wait_until_ready();
  9738. Client cli("localhost", PORT);
  9739. auto res = cli.Get("/dir/");
  9740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9741. EXPECT_EQ(StatusCode::OK_200, res->status);
  9742. res = cli.Get("/dir");
  9743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9744. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9745. res = cli.Get("/file");
  9746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9747. EXPECT_EQ(StatusCode::OK_200, res->status);
  9748. res = cli.Get("/file/");
  9749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9751. cli.set_follow_location(true);
  9752. res = cli.Get("/dir");
  9753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9754. EXPECT_EQ(StatusCode::OK_200, res->status);
  9755. }
  9756. TEST(MountTest, MultibytesPathName) {
  9757. Server svr;
  9758. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9759. auto se = detail::scope_exit([&] {
  9760. svr.stop();
  9761. listen_thread.join();
  9762. ASSERT_FALSE(svr.is_running());
  9763. });
  9764. svr.set_mount_point("/", "./www");
  9765. svr.wait_until_ready();
  9766. Client cli("localhost", PORT);
  9767. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9769. EXPECT_EQ(StatusCode::OK_200, res->status);
  9770. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9771. }
  9772. #ifdef _WIN32
  9773. // Issue #2435: mmap::open() must succeed even when another handle holds
  9774. // the file open for writing (e.g. an active log file).
  9775. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9776. const char *path = "mmap_concurrent_writer_test.txt";
  9777. const char *content = "hello";
  9778. {
  9779. std::ofstream f(path, std::ios::binary);
  9780. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9781. }
  9782. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9783. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9784. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9785. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9786. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9787. detail::mmap m(path);
  9788. ASSERT_TRUE(m.is_open());
  9789. EXPECT_EQ(strlen(content), m.size());
  9790. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9791. }
  9792. #endif
  9793. #ifndef _WIN32
  9794. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9795. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9796. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9797. TEST(MmapTest, FailedMappingIsNotOpen) {
  9798. const char *path = "./mmap_failed_mapping_test_dir";
  9799. ASSERT_EQ(0, ::mkdir(path, 0755));
  9800. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9801. detail::mmap m(path);
  9802. EXPECT_FALSE(m.is_open());
  9803. EXPECT_EQ(0U, m.size());
  9804. EXPECT_NE(static_cast<const void *>(m.data()),
  9805. static_cast<const void *>(MAP_FAILED));
  9806. }
  9807. #endif
  9808. TEST(KeepAliveTest, ReadTimeout) {
  9809. Server svr;
  9810. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9811. std::this_thread::sleep_for(std::chrono::seconds(2));
  9812. res.set_content("a", "text/plain");
  9813. });
  9814. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9815. res.set_content("b", "text/plain");
  9816. });
  9817. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9818. auto se = detail::scope_exit([&] {
  9819. svr.stop();
  9820. listen_thread.join();
  9821. ASSERT_FALSE(svr.is_running());
  9822. });
  9823. svr.wait_until_ready();
  9824. Client cli("localhost", PORT);
  9825. cli.set_keep_alive(true);
  9826. cli.set_read_timeout(std::chrono::seconds(1));
  9827. auto resa = cli.Get("/a");
  9828. ASSERT_FALSE(resa);
  9829. EXPECT_EQ(Error::Read, resa.error());
  9830. auto resb = cli.Get("/b");
  9831. ASSERT_TRUE(resb);
  9832. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9833. EXPECT_EQ("b", resb->body);
  9834. }
  9835. TEST(KeepAliveTest, MaxCount) {
  9836. size_t keep_alive_max_count = 3;
  9837. Server svr;
  9838. svr.set_keep_alive_max_count(keep_alive_max_count);
  9839. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9840. res.set_content("Hello World!", "text/plain");
  9841. });
  9842. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9843. auto se = detail::scope_exit([&] {
  9844. svr.stop();
  9845. listen_thread.join();
  9846. ASSERT_FALSE(svr.is_running());
  9847. });
  9848. svr.wait_until_ready();
  9849. Client cli(HOST, PORT);
  9850. cli.set_keep_alive(true);
  9851. for (size_t i = 0; i < 5; i++) {
  9852. auto result = cli.Get("/hi");
  9853. ASSERT_TRUE(result);
  9854. EXPECT_EQ(StatusCode::OK_200, result->status);
  9855. if (i == keep_alive_max_count - 1) {
  9856. EXPECT_EQ("close", result->get_header_value("Connection"));
  9857. } else {
  9858. EXPECT_FALSE(result->has_header("Connection"));
  9859. }
  9860. }
  9861. }
  9862. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9863. // can pull the next one into the server's buffer. The server must serve it
  9864. // without waiting for the socket to become readable again. The keep-alive
  9865. // timeout outlasts the client's read timeout, so a request left waiting for it
  9866. // shows up as a missing response.
  9867. static void serve_pipelining_routes(Server &svr,
  9868. const std::function<void(int)> &client) {
  9869. svr.set_keep_alive_timeout(5);
  9870. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9871. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9872. });
  9873. svr.Post("/echo", [](const Request &req, Response &res) {
  9874. res.set_content("echo " + req.body, "text/plain");
  9875. });
  9876. auto port = svr.bind_to_any_port(HOST);
  9877. thread t = thread([&] { svr.listen_after_bind(); });
  9878. auto se = detail::scope_exit([&] {
  9879. svr.stop();
  9880. t.join();
  9881. });
  9882. svr.wait_until_ready();
  9883. client(port);
  9884. }
  9885. static std::string
  9886. send_pipelined_requests(const std::vector<std::string> &parts) {
  9887. Server svr;
  9888. std::string res;
  9889. serve_pipelining_routes(svr, [&](int port) {
  9890. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9891. });
  9892. return res;
  9893. }
  9894. static void expect_in_order(const std::string &res,
  9895. const std::vector<std::string> &bodies) {
  9896. size_t pos = 0;
  9897. for (const auto &body : bodies) {
  9898. pos = res.find(body, pos);
  9899. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9900. pos += body.size();
  9901. }
  9902. }
  9903. TEST(KeepAliveTest, PipelinedRequests) {
  9904. auto res = send_pipelined_requests(
  9905. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9906. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9907. "Content-Length: 4\r\n\r\nbody"
  9908. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9909. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9910. }
  9911. // The second request starts in the server's buffer and ends on the socket.
  9912. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9913. auto res =
  9914. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9915. "GET /hi/2 HTTP/1.1\r\nHo",
  9916. "st: localhost\r\nConnection: close\r\n\r\n"});
  9917. expect_in_order(res, {"hi 1", "hi 2"});
  9918. }
  9919. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9920. // CRLF after a body does not turn into a 400 for the next request.
  9921. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9922. auto res = send_pipelined_requests(
  9923. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9924. "Content-Length: 4\r\n\r\nbody\r\n"
  9925. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9926. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9927. expect_in_order(res, {"echo body", "hi 2"});
  9928. }
  9929. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9930. // must not be served as the next request.
  9931. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9932. auto res = send_pipelined_requests(
  9933. {"INVALID REQUEST LINE\r\n\r\n"
  9934. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9935. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9936. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9937. }
  9938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9939. // Over TLS, the next request is held by the TLS library as already decrypted
  9940. // data rather than on the socket.
  9941. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9943. std::string res;
  9944. serve_pipelining_routes(svr, [&](int port) {
  9945. auto error = Error::Success;
  9946. auto sock = detail::create_client_socket(
  9947. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9948. /*connection_timeout_sec=*/5, 0,
  9949. /*read_timeout_sec=*/2, 0,
  9950. /*write_timeout_sec=*/5, 0, std::string(), error);
  9951. ASSERT_NE(INVALID_SOCKET, sock);
  9952. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9953. auto ctx = SSL_CTX_new(TLS_client_method());
  9954. auto ssl = SSL_new(ctx);
  9955. auto ssl_se = detail::scope_exit([&] {
  9956. SSL_free(ssl);
  9957. SSL_CTX_free(ctx);
  9958. });
  9959. SSL_set_fd(ssl, static_cast<int>(sock));
  9960. ASSERT_EQ(1, SSL_connect(ssl));
  9961. // One write, so all three requests arrive in one TLS record
  9962. const std::string req =
  9963. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9964. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9965. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9966. ASSERT_EQ(static_cast<int>(req.size()),
  9967. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9968. char buf[512];
  9969. int n;
  9970. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9971. res.append(buf, static_cast<size_t>(n));
  9972. }
  9973. });
  9974. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9975. }
  9976. #endif
  9977. TEST(KeepAliveTest, Issue1041) {
  9978. Server svr;
  9979. svr.set_keep_alive_timeout(3);
  9980. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9981. res.set_content("Hello World!", "text/plain");
  9982. });
  9983. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9984. auto se = detail::scope_exit([&] {
  9985. svr.stop();
  9986. listen_thread.join();
  9987. ASSERT_FALSE(svr.is_running());
  9988. });
  9989. svr.wait_until_ready();
  9990. Client cli(HOST, PORT);
  9991. cli.set_keep_alive(true);
  9992. auto result = cli.Get("/hi");
  9993. ASSERT_TRUE(result);
  9994. EXPECT_EQ(StatusCode::OK_200, result->status);
  9995. std::this_thread::sleep_for(std::chrono::seconds(5));
  9996. result = cli.Get("/hi");
  9997. ASSERT_TRUE(result);
  9998. EXPECT_EQ(StatusCode::OK_200, result->status);
  9999. }
  10000. TEST(KeepAliveTest, Issue1959) {
  10001. Server svr;
  10002. svr.set_keep_alive_timeout(5);
  10003. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10004. res.set_content("a", "text/plain");
  10005. });
  10006. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10007. auto se = detail::scope_exit([&] {
  10008. if (!svr.is_running()) return;
  10009. svr.stop();
  10010. listen_thread.join();
  10011. ASSERT_FALSE(svr.is_running());
  10012. });
  10013. svr.wait_until_ready();
  10014. Client cli("localhost", PORT);
  10015. cli.set_keep_alive(true);
  10016. using namespace std::chrono;
  10017. auto start = steady_clock::now();
  10018. cli.Get("/a");
  10019. svr.stop();
  10020. listen_thread.join();
  10021. auto end = steady_clock::now();
  10022. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10023. EXPECT_LT(elapsed, 5000);
  10024. }
  10025. #ifdef CPPHTTPLIB_SSL_ENABLED
  10026. TEST(KeepAliveTest, SSLClientReconnection) {
  10027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10028. ASSERT_TRUE(svr.is_valid());
  10029. svr.set_keep_alive_timeout(1);
  10030. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10031. res.set_content("Hello World!", "text/plain");
  10032. });
  10033. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10034. auto se = detail::scope_exit([&] {
  10035. svr.stop();
  10036. listen_thread.join();
  10037. ASSERT_FALSE(svr.is_running());
  10038. });
  10039. svr.wait_until_ready();
  10040. SSLClient cli(HOST, PORT);
  10041. cli.enable_server_certificate_verification(false);
  10042. cli.set_keep_alive(true);
  10043. auto result = cli.Get("/hi");
  10044. ASSERT_TRUE(result);
  10045. EXPECT_EQ(StatusCode::OK_200, result->status);
  10046. result = cli.Get("/hi");
  10047. ASSERT_TRUE(result);
  10048. EXPECT_EQ(StatusCode::OK_200, result->status);
  10049. std::this_thread::sleep_for(std::chrono::seconds(2));
  10050. // Recoonect
  10051. result = cli.Get("/hi");
  10052. ASSERT_TRUE(result);
  10053. EXPECT_EQ(StatusCode::OK_200, result->status);
  10054. result = cli.Get("/hi");
  10055. ASSERT_TRUE(result);
  10056. EXPECT_EQ(StatusCode::OK_200, result->status);
  10057. }
  10058. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10060. ASSERT_TRUE(svr.is_valid());
  10061. svr.set_keep_alive_timeout(1);
  10062. std::string content = "reconnect";
  10063. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10064. res.set_content("Hello World!", "text/plain");
  10065. });
  10066. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10067. auto se = detail::scope_exit([&] {
  10068. svr.stop();
  10069. listen_thread.join();
  10070. ASSERT_FALSE(svr.is_running());
  10071. });
  10072. svr.wait_until_ready();
  10073. SSLClient cli(HOST, PORT);
  10074. cli.enable_server_certificate_verification(false);
  10075. cli.set_keep_alive(true);
  10076. auto result = cli.Post(
  10077. "/hi", content.size(),
  10078. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10079. sink.write(content.c_str(), content.size());
  10080. return true;
  10081. },
  10082. "text/plain");
  10083. ASSERT_TRUE(result);
  10084. EXPECT_EQ(200, result->status);
  10085. std::this_thread::sleep_for(std::chrono::seconds(2));
  10086. // Recoonect
  10087. result = cli.Post(
  10088. "/hi", content.size(),
  10089. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10090. sink.write(content.c_str(), content.size());
  10091. return true;
  10092. },
  10093. "text/plain");
  10094. ASSERT_TRUE(result);
  10095. EXPECT_EQ(200, result->status);
  10096. result = cli.Post(
  10097. "/hi", content.size(),
  10098. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10099. sink.write(content.c_str(), content.size());
  10100. return true;
  10101. },
  10102. "text/plain");
  10103. ASSERT_TRUE(result);
  10104. EXPECT_EQ(200, result->status);
  10105. }
  10106. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10107. using namespace httplib::tls;
  10108. {
  10109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10110. ASSERT_TRUE(svr.is_valid());
  10111. svr.Get("/sni", [&](const Request &req, Response &res) {
  10112. std::string expected = req.sni();
  10113. EXPECT_EQ(expected, req.get_param_value("expected"));
  10114. res.set_content("ok", "text/plain");
  10115. });
  10116. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10117. auto se = detail::scope_exit([&] {
  10118. svr.stop();
  10119. listen_thread.join();
  10120. ASSERT_FALSE(svr.is_running());
  10121. });
  10122. svr.wait_until_ready();
  10123. {
  10124. SSLClient cli("localhost", PORT);
  10125. cli.enable_server_certificate_verification(false);
  10126. auto res = cli.Get("/sni?expected=localhost");
  10127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10128. }
  10129. {
  10130. SSLClient cli("::1", PORT);
  10131. cli.enable_server_certificate_verification(false);
  10132. auto res = cli.Get("/sni?expected=");
  10133. // NOTE: This may fail if the server is listening on IPv4 only
  10134. // (e.g., when localhost resolves to 127.0.0.1 only)
  10135. if (res) {
  10136. EXPECT_EQ(StatusCode::OK_200, res->status);
  10137. } else {
  10138. EXPECT_EQ(Error::Connection, res.error());
  10139. }
  10140. }
  10141. }
  10142. }
  10143. #endif
  10144. TEST(ClientProblemDetectionTest, ContentProvider) {
  10145. Server svr;
  10146. size_t content_length = 1024 * 1024;
  10147. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10148. res.set_content_provider(
  10149. content_length, "text/plain",
  10150. [&](size_t offset, size_t length, DataSink &sink) {
  10151. auto out_len = std::min(length, static_cast<size_t>(1024));
  10152. std::string out(out_len, '@');
  10153. sink.write(out.data(), out_len);
  10154. return offset < 4096;
  10155. },
  10156. [](bool success) { ASSERT_FALSE(success); });
  10157. });
  10158. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10159. res.set_content_provider(
  10160. 0, "text/plain",
  10161. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10162. EXPECT_TRUE(false);
  10163. return true;
  10164. },
  10165. [](bool success) { ASSERT_FALSE(success); });
  10166. });
  10167. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10168. auto se = detail::scope_exit([&] {
  10169. svr.stop();
  10170. listen_thread.join();
  10171. ASSERT_FALSE(svr.is_running());
  10172. });
  10173. svr.wait_until_ready();
  10174. Client cli("localhost", PORT);
  10175. {
  10176. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10177. size_t /*data_length*/) { return false; });
  10178. ASSERT_FALSE(res);
  10179. }
  10180. {
  10181. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10182. size_t /*data_length*/) { return false; });
  10183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10184. }
  10185. }
  10186. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10187. // A provider that reports success without writing anything and without
  10188. // calling done() used to be handed the same offset and length again on every
  10189. // pass, so it spun for as long as the peer stayed connected.
  10190. Server svr;
  10191. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10192. res.set_content("ok", "text/plain");
  10193. });
  10194. auto port = svr.bind_to_any_port(HOST);
  10195. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. listen_thread.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. });
  10201. svr.wait_until_ready();
  10202. std::atomic<int> call_count{0};
  10203. Client cli(HOST, port);
  10204. auto res = cli.Post(
  10205. "/", 1024,
  10206. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10207. // Give up after enough passes to show the spin, so that losing the
  10208. // check below fails this test instead of hanging it.
  10209. return ++call_count < 100;
  10210. },
  10211. "text/plain");
  10212. ASSERT_FALSE(res);
  10213. EXPECT_EQ(Error::Write, res.error());
  10214. EXPECT_EQ(1, call_count.load());
  10215. }
  10216. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10217. // A writer only has to assign `write`. The other three used to be left as
  10218. // empty std::functions, so a provider calling one threw
  10219. // std::bad_function_call out of the thread running it and took the whole
  10220. // process down.
  10221. DataSink sink;
  10222. std::string written;
  10223. sink.write = [&](const char *data, size_t data_len) {
  10224. written.append(data, data_len);
  10225. return true;
  10226. };
  10227. EXPECT_TRUE(sink.is_writable());
  10228. sink.done();
  10229. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10230. EXPECT_TRUE(written.empty());
  10231. }
  10232. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10233. // A sink that cannot carry trailers still has to finish.
  10234. DataSink sink;
  10235. auto done_count = 0;
  10236. sink.done = [&]() { done_count++; };
  10237. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10238. EXPECT_EQ(1, done_count);
  10239. }
  10240. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10241. Server svr;
  10242. const std::string body(4096, 'x');
  10243. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10244. res.set_content_provider(body.size(), "text/plain",
  10245. [&](size_t offset, size_t length, DataSink &sink) {
  10246. sink.write(body.data() + offset, length);
  10247. sink.done();
  10248. return true;
  10249. });
  10250. });
  10251. auto port = svr.bind_to_any_port(HOST);
  10252. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. listen_thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. Client cli(HOST, port);
  10260. auto res = cli.Get("/");
  10261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10262. EXPECT_EQ(StatusCode::OK_200, res->status);
  10263. EXPECT_EQ(body, res->body);
  10264. }
  10265. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10266. Server svr;
  10267. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10268. res.set_content_provider(
  10269. 1024, "text/plain",
  10270. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10271. sink.write("hello", 5);
  10272. sink.done(); // short of the 1024 bytes the response promised
  10273. return true;
  10274. });
  10275. });
  10276. auto port = svr.bind_to_any_port(HOST);
  10277. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10278. auto se = detail::scope_exit([&] {
  10279. svr.stop();
  10280. listen_thread.join();
  10281. ASSERT_FALSE(svr.is_running());
  10282. });
  10283. svr.wait_until_ready();
  10284. Client cli(HOST, port);
  10285. cli.set_read_timeout(5, 0);
  10286. // The response is short of its Content-Length, so the client cannot read a
  10287. // complete body. What matters is that this returns at all: a no-op done()
  10288. // would leave the writer looping over a provider that never makes progress.
  10289. auto res = cli.Get("/");
  10290. EXPECT_FALSE(res);
  10291. }
  10292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10293. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10294. // The compressed path builds the whole body before connecting, so this
  10295. // fails client-side and never reaches a server.
  10296. Client cli(HOST, PORT);
  10297. cli.set_compress(true);
  10298. auto res = cli.Post(
  10299. "/", 1024,
  10300. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10301. sink.write("hello", 5);
  10302. sink.done(); // short of the 1024 bytes the request announced
  10303. return true;
  10304. },
  10305. "text/plain");
  10306. ASSERT_FALSE(res);
  10307. EXPECT_EQ(Error::Write, res.error());
  10308. }
  10309. #endif
  10310. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10311. Server svr;
  10312. svr.set_error_handler([](Request const &, Response &res) -> void {
  10313. res.set_chunked_content_provider(
  10314. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10315. sink.os << "hello";
  10316. sink.os << "world";
  10317. sink.done();
  10318. return true;
  10319. });
  10320. });
  10321. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10322. auto se = detail::scope_exit([&] {
  10323. svr.stop();
  10324. listen_thread.join();
  10325. ASSERT_FALSE(svr.is_running());
  10326. });
  10327. svr.wait_until_ready();
  10328. Client cli("localhost", PORT);
  10329. auto res = cli.Get("/");
  10330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10331. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10332. EXPECT_EQ("helloworld", res->body);
  10333. }
  10334. // A body set after a content provider must replace it, not be sent through it.
  10335. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10336. Server svr;
  10337. svr.set_mount_point("/", "./www");
  10338. svr.set_file_request_handler([](const Request &req, Response &res) {
  10339. if (req.path == "/dir/test.html") {
  10340. res.status = StatusCode::Forbidden_403;
  10341. res.set_content(std::string(5000, 'D'), "text/plain");
  10342. } else if (req.path == "/file") {
  10343. res.status = StatusCode::Forbidden_403;
  10344. res.body = "Denied";
  10345. }
  10346. });
  10347. auto port = svr.bind_to_any_port(HOST);
  10348. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10349. auto se = detail::scope_exit([&] {
  10350. svr.stop();
  10351. t.join();
  10352. ASSERT_FALSE(svr.is_running());
  10353. });
  10354. svr.wait_until_ready();
  10355. Client cli(HOST, port);
  10356. {
  10357. auto res = cli.Get("/dir/test.html");
  10358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10359. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10360. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10361. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10362. }
  10363. {
  10364. auto res = cli.Get("/file");
  10365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10366. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10367. EXPECT_EQ("Denied", res->body);
  10368. }
  10369. {
  10370. auto res = cli.Get("/dir/index.html");
  10371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10372. EXPECT_EQ(StatusCode::OK_200, res->status);
  10373. EXPECT_EQ(0U, res->body.find("<html>"));
  10374. }
  10375. }
  10376. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10377. Server svr;
  10378. std::vector<bool> released;
  10379. std::mutex released_mutex;
  10380. auto releaser = [&](bool success) {
  10381. std::lock_guard<std::mutex> guard(released_mutex);
  10382. released.push_back(success);
  10383. };
  10384. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10385. return sink.write(&"hello"[offset], length);
  10386. };
  10387. svr.Get("/sized", [&](const Request &, Response &res) {
  10388. res.status = StatusCode::NotFound_404;
  10389. res.set_content_provider(5, "text/plain", provider, releaser);
  10390. });
  10391. svr.Get("/chunked", [&](const Request &, Response &res) {
  10392. res.status = StatusCode::ServiceUnavailable_503;
  10393. res.set_chunked_content_provider(
  10394. "text/plain",
  10395. [](size_t, DataSink &sink) {
  10396. sink.os << "chunk";
  10397. sink.done();
  10398. return true;
  10399. },
  10400. releaser);
  10401. });
  10402. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10403. res.set_content_provider(5, "text/plain", provider, releaser);
  10404. throw std::runtime_error("after the provider");
  10405. });
  10406. svr.set_error_handler([](const Request &req, Response &res) {
  10407. // Leave the exception handler's content to it.
  10408. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10409. res.set_content(std::string(1000, 'E'), "text/html");
  10410. return Server::HandlerResponse::Handled;
  10411. });
  10412. svr.set_exception_handler(
  10413. [](const Request &, Response &res, std::exception_ptr) {
  10414. res.status = StatusCode::InternalServerError_500;
  10415. res.set_content(std::string(1000, 'X'), "text/html");
  10416. });
  10417. auto port = svr.bind_to_any_port(HOST);
  10418. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. t.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. Client cli(HOST, port);
  10426. {
  10427. auto res = cli.Get("/sized");
  10428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10429. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10430. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10431. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10432. }
  10433. {
  10434. auto res = cli.Get("/chunked");
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10437. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10438. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10439. }
  10440. {
  10441. auto res = cli.Get("/throw");
  10442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10443. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10444. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10445. }
  10446. std::lock_guard<std::mutex> guard(released_mutex);
  10447. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10448. }
  10449. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10450. Server svr;
  10451. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10452. return sink.write(&"abc"[offset], length);
  10453. };
  10454. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10455. res.set_file_content("./www/dir/test.html");
  10456. res.set_content("body", "text/plain");
  10457. });
  10458. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10459. res.set_content(std::string(100, 'B'), "text/plain");
  10460. res.set_file_content("./www/dir/test.html");
  10461. });
  10462. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10463. res.set_content(std::string(100, 'B'), "text/plain");
  10464. res.set_content_provider(3, "text/plain", abc);
  10465. });
  10466. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10467. res.set_content_provider(3, "text/plain", abc);
  10468. res.set_content(std::string(100, 'B'), "text/plain");
  10469. });
  10470. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10471. res.set_content_provider(3, "text/plain", abc);
  10472. res.body = "direct";
  10473. });
  10474. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10475. res.set_file_content("./www/dir/test.html");
  10476. res.body = "direct";
  10477. });
  10478. auto port = svr.bind_to_any_port(HOST);
  10479. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10480. auto se = detail::scope_exit([&] {
  10481. svr.stop();
  10482. t.join();
  10483. ASSERT_FALSE(svr.is_running());
  10484. });
  10485. svr.wait_until_ready();
  10486. Client cli(HOST, port);
  10487. auto expect_body = [&](const char *path, const std::string &body) {
  10488. // Uncompressed, so Content-Length can be compared with the body.
  10489. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10490. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10491. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10492. EXPECT_EQ(body, res->body) << path;
  10493. EXPECT_EQ(std::to_string(body.size()),
  10494. res->get_header_value("Content-Length"))
  10495. << path;
  10496. };
  10497. expect_body("/file-then-body", "body");
  10498. expect_body("/body-then-file", "test.html");
  10499. expect_body("/body-then-provider", "abc");
  10500. expect_body("/provider-then-body", std::string(100, 'B'));
  10501. expect_body("/provider-then-direct-body", "direct");
  10502. expect_body("/file-then-direct-body", "direct");
  10503. // Ranges are checked against the body, not the dropped provider.
  10504. {
  10505. auto res = cli.Get("/provider-then-direct-body",
  10506. Headers{{make_range_header({{1, 2}})}});
  10507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10509. EXPECT_EQ("ir", res->body);
  10510. }
  10511. {
  10512. auto res = cli.Get("/file-then-direct-body",
  10513. Headers{{make_range_header({{7, 8}})}});
  10514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10515. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10516. }
  10517. }
  10518. // Forward declaration (see the base64_encode note).
  10519. namespace httplib {
  10520. namespace detail {
  10521. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10522. const std::string &content_type,
  10523. EncodingType encoding);
  10524. } // namespace detail
  10525. } // namespace httplib
  10526. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10527. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10528. ASSERT_TRUE(mm->is_open());
  10529. Response res;
  10530. detail::set_file_content_provider(res, mm, "text/html",
  10531. detail::EncodingType::None);
  10532. std::string out;
  10533. DataSink sink;
  10534. sink.write = [&](const char *d, size_t l) {
  10535. out.append(d, l);
  10536. return true;
  10537. };
  10538. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10539. EXPECT_EQ("test.html", out);
  10540. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10541. EXPECT_EQ("test.html", out);
  10542. }
  10543. TEST(LongPollingTest, ClientCloseDetection) {
  10544. Server svr;
  10545. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10546. res.set_chunked_content_provider(
  10547. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10548. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10549. sink.os << "hello";
  10550. auto count = 10;
  10551. while (count > 0 && sink.is_writable()) {
  10552. this_thread::sleep_for(chrono::milliseconds(10));
  10553. count--;
  10554. }
  10555. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10556. return true;
  10557. });
  10558. });
  10559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10560. auto se = detail::scope_exit([&] {
  10561. svr.stop();
  10562. listen_thread.join();
  10563. ASSERT_FALSE(svr.is_running());
  10564. });
  10565. svr.wait_until_ready();
  10566. Client cli("localhost", PORT);
  10567. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10568. EXPECT_EQ("hello", string(data, data_length));
  10569. return false; // close the socket immediately.
  10570. });
  10571. ASSERT_FALSE(res);
  10572. }
  10573. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10574. Server svr;
  10575. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10576. res.set_chunked_content_provider(
  10577. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10578. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10579. sink.os << "hello";
  10580. EXPECT_TRUE(sink.os.good());
  10581. // Wait for the client to close the connection
  10582. auto count = 10;
  10583. while (count > 0 && sink.is_writable()) {
  10584. this_thread::sleep_for(chrono::milliseconds(10));
  10585. count--;
  10586. }
  10587. // After client disconnect, write repeatedly until the socket
  10588. // write actually fails (small writes may be absorbed by the
  10589. // kernel buffer)
  10590. std::string chunk(1024, 'x');
  10591. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10592. sink.os << chunk;
  10593. }
  10594. EXPECT_TRUE(sink.os.fail());
  10595. return true;
  10596. });
  10597. });
  10598. auto port = svr.bind_to_any_port("localhost");
  10599. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10600. auto se = detail::scope_exit([&] {
  10601. svr.stop();
  10602. listen_thread.join();
  10603. ASSERT_FALSE(svr.is_running());
  10604. });
  10605. svr.wait_until_ready();
  10606. Client cli("localhost", port);
  10607. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10608. EXPECT_EQ("hello", string(data, data_length));
  10609. return false; // close the socket immediately.
  10610. });
  10611. ASSERT_FALSE(res);
  10612. }
  10613. TEST(GetWithParametersTest, GetWithParameters) {
  10614. Server svr;
  10615. svr.Get("/", [&](const Request &req, Response &) {
  10616. EXPECT_EQ("world", req.get_param_value("hello"));
  10617. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10618. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10619. });
  10620. svr.Get("/params", [&](const Request &req, Response &) {
  10621. EXPECT_EQ("world", req.get_param_value("hello"));
  10622. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10623. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10624. });
  10625. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10626. EXPECT_EQ("resource-id", req.matches[1]);
  10627. EXPECT_EQ("foo", req.get_param_value("param1"));
  10628. EXPECT_EQ("bar", req.get_param_value("param2"));
  10629. });
  10630. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10631. EXPECT_EQ("user-id", req.path_params.at("id"));
  10632. EXPECT_EQ("foo", req.get_param_value("param1"));
  10633. EXPECT_EQ("bar", req.get_param_value("param2"));
  10634. });
  10635. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10636. auto se = detail::scope_exit([&] {
  10637. svr.stop();
  10638. listen_thread.join();
  10639. ASSERT_FALSE(svr.is_running());
  10640. });
  10641. svr.wait_until_ready();
  10642. {
  10643. Client cli(HOST, PORT);
  10644. Params params;
  10645. params.emplace("hello", "world");
  10646. params.emplace("hello2", "world2");
  10647. params.emplace("hello3", "world3");
  10648. auto res = cli.Get("/", params, Headers{});
  10649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10650. EXPECT_EQ(StatusCode::OK_200, res->status);
  10651. }
  10652. {
  10653. Client cli(HOST, PORT);
  10654. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10656. EXPECT_EQ(StatusCode::OK_200, res->status);
  10657. }
  10658. {
  10659. Client cli(HOST, PORT);
  10660. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10662. EXPECT_EQ(StatusCode::OK_200, res->status);
  10663. }
  10664. {
  10665. Client cli(HOST, PORT);
  10666. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10668. EXPECT_EQ(StatusCode::OK_200, res->status);
  10669. }
  10670. }
  10671. TEST(GetWithParametersTest, GetWithParameters2) {
  10672. Server svr;
  10673. svr.Get("/", [&](const Request &req, Response &res) {
  10674. auto text = req.get_param_value("hello");
  10675. res.set_content(text, "text/plain");
  10676. });
  10677. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. listen_thread.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. });
  10683. svr.wait_until_ready();
  10684. Client cli("localhost", PORT);
  10685. Params params;
  10686. params.emplace("hello", "world");
  10687. std::string body;
  10688. auto res = cli.Get("/", params, Headers{},
  10689. [&](const char *data, size_t data_length) {
  10690. body.append(data, data_length);
  10691. return true;
  10692. });
  10693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10694. EXPECT_EQ(StatusCode::OK_200, res->status);
  10695. EXPECT_EQ("world", body);
  10696. }
  10697. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10698. Server svr;
  10699. svr.Get("/search", [&](const Request &req, Response &res) {
  10700. auto q = req.get_param_value("q");
  10701. res.set_content(q, "text/plain");
  10702. });
  10703. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. listen_thread.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. Client cli("localhost", PORT);
  10711. // Verify that Get(path, params) works without requiring Headers argument
  10712. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10714. EXPECT_EQ(StatusCode::OK_200, res->status);
  10715. EXPECT_EQ("cpp-httplib", res->body);
  10716. }
  10717. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10718. auto host = "httpbingo.org";
  10719. auto path = std::string{"/range/32"};
  10720. #ifdef CPPHTTPLIB_SSL_ENABLED
  10721. SSLClient cli(host);
  10722. #else
  10723. Client cli(host);
  10724. #endif
  10725. cli.set_default_headers({make_range_header({{1, 10}})});
  10726. cli.set_connection_timeout(5);
  10727. {
  10728. auto res = cli.Get(path);
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. EXPECT_EQ("bcdefghijk", res->body);
  10731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10732. }
  10733. {
  10734. auto res = cli.Get(path);
  10735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10736. EXPECT_EQ("bcdefghijk", res->body);
  10737. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10738. }
  10739. }
  10740. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10741. Server svr;
  10742. svr.set_default_headers({{"Hello", "World"}});
  10743. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10744. res.set_content("ok", "text/plain");
  10745. });
  10746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. listen_thread.join();
  10750. ASSERT_FALSE(svr.is_running());
  10751. });
  10752. svr.wait_until_ready();
  10753. Client cli("localhost", PORT);
  10754. auto res = cli.Get("/");
  10755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10756. EXPECT_EQ(StatusCode::OK_200, res->status);
  10757. EXPECT_EQ("ok", res->body);
  10758. EXPECT_EQ("World", res->get_header_value("Hello"));
  10759. }
  10760. #ifdef CPPHTTPLIB_SSL_ENABLED
  10761. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10763. ASSERT_TRUE(svr.is_valid());
  10764. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10765. std::this_thread::sleep_for(std::chrono::seconds(2));
  10766. res.set_content("a", "text/plain");
  10767. });
  10768. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10769. res.set_content("b", "text/plain");
  10770. });
  10771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10772. auto se = detail::scope_exit([&] {
  10773. svr.stop();
  10774. listen_thread.join();
  10775. ASSERT_FALSE(svr.is_running());
  10776. });
  10777. svr.wait_until_ready();
  10778. SSLClient cli("localhost", PORT);
  10779. cli.enable_server_certificate_verification(false);
  10780. cli.set_keep_alive(true);
  10781. cli.set_read_timeout(std::chrono::seconds(1));
  10782. auto resa = cli.Get("/a");
  10783. ASSERT_TRUE(!resa);
  10784. EXPECT_EQ(Error::Read, resa.error());
  10785. auto resb = cli.Get("/b");
  10786. ASSERT_TRUE(resb);
  10787. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10788. EXPECT_EQ("b", resb->body);
  10789. }
  10790. // Closing an idle keep-alive connection sends close_notify and returns. The
  10791. // server must not wait for the client's close_notify: an idle client never
  10792. // sends one, so the worker would be held until the read timeout expires, and
  10793. // stop() would wait for it.
  10794. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10796. ASSERT_TRUE(svr.is_valid());
  10797. svr.set_keep_alive_timeout(1);
  10798. svr.set_read_timeout(10, 0);
  10799. svr.Get("/", [](const Request &, Response &res) {
  10800. res.set_content("ok", "text/plain");
  10801. });
  10802. auto port = svr.bind_to_any_port(HOST);
  10803. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10804. auto se = detail::scope_exit([&] {
  10805. if (listen_thread.joinable()) {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. }
  10809. });
  10810. svr.wait_until_ready();
  10811. SSLClient cli(HOST, port);
  10812. cli.enable_server_certificate_verification(false);
  10813. cli.set_keep_alive(true);
  10814. auto res = cli.Get("/");
  10815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10816. EXPECT_EQ(StatusCode::OK_200, res->status);
  10817. // Stay idle past the keep-alive timeout so the server closes the connection.
  10818. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10819. auto start = std::chrono::steady_clock::now();
  10820. svr.stop();
  10821. listen_thread.join();
  10822. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10823. std::chrono::steady_clock::now() - start)
  10824. .count();
  10825. EXPECT_LT(elapsed, 3000);
  10826. }
  10827. #endif
  10828. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10829. protected:
  10830. ServerTestWithAI_PASSIVE()
  10831. : cli_(HOST, PORT)
  10832. #ifdef CPPHTTPLIB_SSL_ENABLED
  10833. ,
  10834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10835. #endif
  10836. {
  10837. #ifdef CPPHTTPLIB_SSL_ENABLED
  10838. cli_.enable_server_certificate_verification(false);
  10839. #endif
  10840. }
  10841. virtual void SetUp() {
  10842. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10843. res.set_content("Hello World!", "text/plain");
  10844. });
  10845. t_ = thread(
  10846. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10847. svr_.wait_until_ready();
  10848. }
  10849. virtual void TearDown() {
  10850. svr_.stop();
  10851. t_.join();
  10852. }
  10853. #ifdef CPPHTTPLIB_SSL_ENABLED
  10854. SSLClient cli_;
  10855. SSLServer svr_;
  10856. #else
  10857. Client cli_;
  10858. Server svr_;
  10859. #endif
  10860. thread t_;
  10861. };
  10862. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10863. auto res = cli_.Get("/hi");
  10864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10865. EXPECT_EQ(StatusCode::OK_200, res->status);
  10866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10867. EXPECT_EQ("Hello World!", res->body);
  10868. }
  10869. class ServerUpDownTest : public ::testing::Test {
  10870. protected:
  10871. ServerUpDownTest() : cli_(HOST, PORT) {}
  10872. virtual void SetUp() {
  10873. t_ = thread([&]() {
  10874. svr_.bind_to_any_port(HOST);
  10875. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10876. ASSERT_TRUE(svr_.listen_after_bind());
  10877. });
  10878. svr_.wait_until_ready();
  10879. }
  10880. virtual void TearDown() {
  10881. svr_.stop();
  10882. t_.join();
  10883. }
  10884. Client cli_;
  10885. Server svr_;
  10886. thread t_;
  10887. };
  10888. TEST_F(ServerUpDownTest, QuickStartStop) {
  10889. // Should not crash, especially when run with
  10890. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10891. }
  10892. class PayloadMaxLengthTest : public ::testing::Test {
  10893. protected:
  10894. PayloadMaxLengthTest()
  10895. : cli_(HOST, PORT)
  10896. #ifdef CPPHTTPLIB_SSL_ENABLED
  10897. ,
  10898. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10899. #endif
  10900. {
  10901. #ifdef CPPHTTPLIB_SSL_ENABLED
  10902. cli_.enable_server_certificate_verification(false);
  10903. #endif
  10904. }
  10905. virtual void SetUp() {
  10906. svr_.set_payload_max_length(8);
  10907. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10908. res.set_content("test", "text/plain");
  10909. });
  10910. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10911. svr_.wait_until_ready();
  10912. }
  10913. virtual void TearDown() {
  10914. svr_.stop();
  10915. t_.join();
  10916. }
  10917. #ifdef CPPHTTPLIB_SSL_ENABLED
  10918. SSLClient cli_;
  10919. SSLServer svr_;
  10920. #else
  10921. Client cli_;
  10922. Server svr_;
  10923. #endif
  10924. thread t_;
  10925. };
  10926. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10927. auto res = cli_.Post("/test", "123456789", "text/plain");
  10928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10929. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10930. res = cli_.Post("/test", "12345678", "text/plain");
  10931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10932. EXPECT_EQ(StatusCode::OK_200, res->status);
  10933. }
  10934. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10935. // Test chunked encoding with payload exceeding the 8-byte limit
  10936. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10937. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10939. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10940. }
  10941. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10942. // Test chunked encoding with payload within the 8-byte limit
  10943. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10944. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10946. EXPECT_EQ(StatusCode::OK_200, res->status);
  10947. }
  10948. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10949. // Test using send_request to send chunked data exceeding payload limit
  10950. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10951. "Host: " +
  10952. std::string(HOST) + ":" + std::to_string(PORT) +
  10953. "\r\n"
  10954. "Transfer-Encoding: chunked\r\n"
  10955. "Connection: close\r\n"
  10956. "\r\n"
  10957. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10958. "0123456789\r\n"
  10959. "0\r\n" // End chunk
  10960. "\r\n";
  10961. std::string response;
  10962. bool result = send_request(1, chunked_request, &response);
  10963. if (!result) {
  10964. // If send_request fails, it might be because the server closed the
  10965. // connection due to payload limit enforcement, which is acceptable
  10966. SUCCEED()
  10967. << "Server rejected oversized chunked request (connection closed)";
  10968. } else {
  10969. // If we got a response, check if it's an error response or connection was
  10970. // closed early Short response length indicates connection was closed due to
  10971. // payload limit
  10972. if (response.length() <= 10) {
  10973. SUCCEED() << "Server closed connection for oversized chunked request";
  10974. } else {
  10975. // Check for error status codes
  10976. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10977. response.find("Payload Too Large") != std::string::npos ||
  10978. response.find("400") != std::string::npos);
  10979. }
  10980. }
  10981. }
  10982. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10983. // Test request without Content-Length header exceeding payload limit
  10984. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10985. "Host: " +
  10986. std::string(HOST) + ":" +
  10987. std::to_string(PORT) +
  10988. "\r\n"
  10989. "Connection: close\r\n"
  10990. "\r\n";
  10991. // Add payload exceeding the 8-byte limit
  10992. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10993. request_without_content_length += large_payload;
  10994. std::string response;
  10995. bool result = send_request(1, request_without_content_length, &response);
  10996. if (!result) {
  10997. // If send_request fails, server likely closed connection due to payload
  10998. // limit
  10999. SUCCEED() << "Server rejected oversized request without Content-Length "
  11000. "(connection closed)";
  11001. } else {
  11002. // Check if server responded with error or closed connection early
  11003. if (response.length() <= 10) {
  11004. SUCCEED() << "Server closed connection for oversized request without "
  11005. "Content-Length";
  11006. } else {
  11007. // Check for error status codes
  11008. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11009. response.find("Payload Too Large") != std::string::npos ||
  11010. response.find("400") != std::string::npos);
  11011. }
  11012. }
  11013. }
  11014. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11015. // Test request without Content-Length header within payload limit
  11016. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11017. "Host: " +
  11018. std::string(HOST) + ":" +
  11019. std::to_string(PORT) +
  11020. "\r\n"
  11021. "Connection: close\r\n"
  11022. "\r\n";
  11023. // Add payload within the 8-byte limit
  11024. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11025. request_without_content_length += small_payload;
  11026. std::string response;
  11027. bool result = send_request(1, request_without_content_length, &response);
  11028. // For requests without Content-Length, the server may have different behavior
  11029. // The key is that it should not reject due to payload limit for small
  11030. // payloads
  11031. if (result) {
  11032. // Check for any HTTP response (success or error, but not connection closed)
  11033. if (response.length() > 10) {
  11034. SUCCEED()
  11035. << "Server processed request without Content-Length within limit";
  11036. } else {
  11037. // Short response might indicate connection closed, which is acceptable
  11038. SUCCEED() << "Server closed connection for request without "
  11039. "Content-Length (acceptable behavior)";
  11040. }
  11041. } else {
  11042. // Connection failure might be due to protocol requirements
  11043. SUCCEED() << "Connection issue with request without Content-Length "
  11044. "(environment-specific)";
  11045. }
  11046. }
  11047. class LargePayloadMaxLengthTest : public ::testing::Test {
  11048. protected:
  11049. LargePayloadMaxLengthTest()
  11050. : cli_(HOST, PORT)
  11051. #ifdef CPPHTTPLIB_SSL_ENABLED
  11052. ,
  11053. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11054. #endif
  11055. {
  11056. #ifdef CPPHTTPLIB_SSL_ENABLED
  11057. cli_.enable_server_certificate_verification(false);
  11058. #endif
  11059. }
  11060. virtual void SetUp() {
  11061. // Set 10MB payload limit
  11062. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11063. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11064. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11065. res.set_content("Large payload test", "text/plain");
  11066. });
  11067. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11068. svr_.wait_until_ready();
  11069. }
  11070. virtual void TearDown() {
  11071. svr_.stop();
  11072. t_.join();
  11073. }
  11074. #ifdef CPPHTTPLIB_SSL_ENABLED
  11075. SSLClient cli_;
  11076. SSLServer svr_;
  11077. #else
  11078. Client cli_;
  11079. Server svr_;
  11080. #endif
  11081. thread t_;
  11082. };
  11083. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11084. // Test chunked encoding with payload within 10MB limit
  11085. std::string medium_payload(5 * 1024 * 1024,
  11086. 'A'); // 5MB payload, within 10MB limit
  11087. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11089. EXPECT_EQ(StatusCode::OK_200, res->status);
  11090. }
  11091. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11092. // Test chunked encoding with payload exceeding 10MB limit
  11093. std::string large_payload(12 * 1024 * 1024,
  11094. 'B'); // 12MB payload, exceeds 10MB limit
  11095. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11096. // Server may either return 413 or close the connection
  11097. if (res) {
  11098. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11099. } else {
  11100. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11101. }
  11102. }
  11103. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11104. // Test request without Content-Length header within 10MB limit
  11105. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11106. "Host: " +
  11107. std::string(HOST) + ":" +
  11108. std::to_string(PORT) +
  11109. "\r\n"
  11110. "Connection: close\r\n"
  11111. "\r\n";
  11112. // Add 1MB payload (within 10MB limit)
  11113. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11114. request_without_content_length += medium_payload;
  11115. std::string response;
  11116. bool result = send_request(5, request_without_content_length, &response);
  11117. if (result) {
  11118. // Should get a proper HTTP response for payloads within limit
  11119. if (response.length() > 10) {
  11120. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11121. "10MB limit";
  11122. } else {
  11123. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11124. "Content-Length)";
  11125. }
  11126. } else {
  11127. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11128. }
  11129. }
  11130. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11131. // Test request without Content-Length header exceeding 10MB limit
  11132. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11133. "Host: " +
  11134. std::string(HOST) + ":" +
  11135. std::to_string(PORT) +
  11136. "\r\n"
  11137. "Connection: close\r\n"
  11138. "\r\n";
  11139. // Add 12MB payload (exceeds 10MB limit)
  11140. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11141. request_without_content_length += large_payload;
  11142. std::string response;
  11143. bool result = send_request(10, request_without_content_length, &response);
  11144. if (!result) {
  11145. // Server should close connection due to payload limit
  11146. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11147. "(connection closed)";
  11148. } else {
  11149. // Check for error response
  11150. if (response.length() <= 10) {
  11151. SUCCEED()
  11152. << "Server closed connection for 12MB request exceeding 10MB limit";
  11153. } else {
  11154. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11155. response.find("Payload Too Large") != std::string::npos ||
  11156. response.find("400") != std::string::npos);
  11157. }
  11158. }
  11159. }
  11160. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11161. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11162. // path.
  11163. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11164. Server svr;
  11165. const size_t LIMIT = 64 * 1024; // 64KB
  11166. svr.set_payload_max_length(LIMIT);
  11167. size_t total = 0;
  11168. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11169. const ContentReader &content_reader) {
  11170. content_reader([&](const char * /*data*/, size_t len) {
  11171. total += len;
  11172. return true;
  11173. });
  11174. res.status = 200;
  11175. res.set_content("stream_ok", "text/plain");
  11176. });
  11177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11178. auto se = detail::scope_exit([&] {
  11179. svr.stop();
  11180. thread.join();
  11181. ASSERT_FALSE(svr.is_running());
  11182. });
  11183. svr.wait_until_ready();
  11184. // Prepare 256KB raw data and gzip-compress it
  11185. std::string raw(256 * 1024, 'A');
  11186. std::string gz;
  11187. {
  11188. z_stream zs{};
  11189. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11190. Z_DEFAULT_STRATEGY);
  11191. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11192. zs.avail_in = static_cast<uInt>(raw.size());
  11193. char outbuf[4096];
  11194. int ret;
  11195. do {
  11196. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11197. zs.avail_out = sizeof(outbuf);
  11198. ret = deflate(&zs, Z_FINISH);
  11199. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11200. } while (ret != Z_STREAM_END);
  11201. deflateEnd(&zs);
  11202. }
  11203. Client cli(HOST, PORT);
  11204. cli.set_connection_timeout(std::chrono::seconds(5));
  11205. Headers headers = {{"Content-Encoding", "gzip"}};
  11206. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11207. "application/octet-stream");
  11208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11209. // Server must reject oversized decompressed payloads with 413.
  11210. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11211. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11212. EXPECT_LE(total, LIMIT);
  11213. }
  11214. #ifndef CPPHTTPLIB_SSL_ENABLED
  11215. // For a request with neither Content-Length nor Transfer-Encoding, the
  11216. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11217. // compressed wire bytes straight to the ContentReader without ever routing
  11218. // them through the decompressor, so payload_max_length_ only bounded the
  11219. // compressed size on the wire, not the decompressed size.
  11220. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11221. Server svr;
  11222. const size_t LIMIT = 64 * 1024; // 64KB
  11223. svr.set_payload_max_length(LIMIT);
  11224. size_t total = 0;
  11225. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11226. const ContentReader &content_reader) {
  11227. content_reader([&](const char * /*data*/, size_t len) {
  11228. total += len;
  11229. return true;
  11230. });
  11231. res.status = 200;
  11232. res.set_content("stream_ok", "text/plain");
  11233. });
  11234. auto port = svr.bind_to_any_port(HOST);
  11235. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11236. auto se = detail::scope_exit([&] {
  11237. svr.stop();
  11238. thread.join();
  11239. ASSERT_FALSE(svr.is_running());
  11240. });
  11241. svr.wait_until_ready();
  11242. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11243. // StreamingGzipDecompression test above.
  11244. std::string raw(256 * 1024, 'A');
  11245. std::string gz;
  11246. {
  11247. httplib::detail::gzip_compressor compressor;
  11248. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11249. [&](const char *chunk, size_t len) {
  11250. gz.append(chunk, len);
  11251. return true;
  11252. });
  11253. ASSERT_TRUE(result);
  11254. }
  11255. // Send the gzip body over raw TCP with neither Content-Length nor
  11256. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11257. // kicks in.
  11258. std::string req = "POST /stream HTTP/1.1\r\n"
  11259. "Host: " +
  11260. std::string(HOST) + ":" + std::to_string(port) +
  11261. "\r\n"
  11262. "Content-Encoding: gzip\r\n"
  11263. "Connection: close\r\n"
  11264. "\r\n" +
  11265. gz;
  11266. std::string response;
  11267. ASSERT_TRUE(send_request(5, req, &response, port));
  11268. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11269. EXPECT_LE(total, LIMIT);
  11270. }
  11271. #endif
  11272. #endif
  11273. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11274. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11275. // the payload must be passed through untouched instead of being rejected.
  11276. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11277. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11278. Server svr;
  11279. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11280. res.set_content(body, "image/jpeg");
  11281. res.set_header("Content-Encoding", "UTF-8");
  11282. });
  11283. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11284. res.set_content(body, "image/jpeg");
  11285. res.set_header("Content-Encoding", "identity");
  11286. });
  11287. svr.Post("/echo", [](const Request &req, Response &res) {
  11288. res.set_content(req.body, "image/jpeg");
  11289. });
  11290. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11291. auto se = detail::scope_exit([&] {
  11292. svr.stop();
  11293. t.join();
  11294. ASSERT_FALSE(svr.is_running());
  11295. });
  11296. svr.wait_until_ready();
  11297. Client cli(HOST, PORT);
  11298. {
  11299. auto res = cli.Get("/image");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. EXPECT_EQ(StatusCode::OK_200, res->status);
  11302. EXPECT_EQ(body, res->body);
  11303. }
  11304. {
  11305. auto res = cli.Get("/identity");
  11306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11307. EXPECT_EQ(StatusCode::OK_200, res->status);
  11308. EXPECT_EQ(body, res->body);
  11309. }
  11310. {
  11311. // The same applies to a request body reaching the server.
  11312. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11313. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11315. EXPECT_EQ(StatusCode::OK_200, res->status);
  11316. EXPECT_EQ(body, res->body);
  11317. }
  11318. }
  11319. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11320. // gzip-encoded response even when the build has no zlib support.
  11321. static const char GZIPPED_HELLO_WORLD[] = {
  11322. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11323. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11324. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11325. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11326. // A content coding is a whole token, not something the field value merely
  11327. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11328. // as "fibre" look like Brotli, and turned a multi-coding value like
  11329. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11330. // it was never meant to see.
  11331. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11332. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11333. Server svr;
  11334. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11335. res.set_content(body, "image/jpeg");
  11336. res.set_header("Content-Encoding", "fibre");
  11337. });
  11338. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11339. res.set_content(body, "image/jpeg");
  11340. res.set_header("Content-Encoding", "gzip, br");
  11341. });
  11342. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11343. res.set_content(body, "image/jpeg");
  11344. res.set_header("Content-Encoding", "x-zstd-ish");
  11345. });
  11346. auto port = svr.bind_to_any_port(HOST);
  11347. thread t = thread([&]() { svr.listen_after_bind(); });
  11348. auto se = detail::scope_exit([&] {
  11349. svr.stop();
  11350. t.join();
  11351. ASSERT_FALSE(svr.is_running());
  11352. });
  11353. svr.wait_until_ready();
  11354. Client cli(HOST, port);
  11355. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11356. auto res = cli.Get(path);
  11357. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11358. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11359. // Not a coding we recognize, so the payload comes back untouched
  11360. EXPECT_EQ(body, res->body) << path;
  11361. }
  11362. }
  11363. // A content coding cpp-httplib recognizes but was not built with must be
  11364. // reported as such. Handing the still-compressed payload back to the caller
  11365. // would silently corrupt it.
  11366. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11367. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11368. Server svr;
  11369. // "image/jpeg" keeps the server from applying a content coding of its own,
  11370. // so the hand-crafted Content-Encoding below survives.
  11371. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11372. res.set_content(gzipped, "image/jpeg");
  11373. res.set_header("Content-Encoding", "gzip");
  11374. });
  11375. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11376. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11377. res.set_content(gzipped, "image/jpeg");
  11378. res.set_header("Content-Encoding", "GZIP");
  11379. });
  11380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11381. auto se = detail::scope_exit([&] {
  11382. svr.stop();
  11383. t.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.wait_until_ready();
  11387. Client cli(HOST, PORT);
  11388. {
  11389. auto res = cli.Get("/gzipped");
  11390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11392. EXPECT_EQ("Hello World!", res->body);
  11393. #else
  11394. ASSERT_FALSE(res);
  11395. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11396. #endif
  11397. }
  11398. {
  11399. // open_stream() must behave the same way.
  11400. auto handle = cli.open_stream("GET", "/gzipped");
  11401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11402. ASSERT_TRUE(handle.is_valid());
  11403. std::string received;
  11404. char buf[256];
  11405. ssize_t n;
  11406. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11407. received.append(buf, static_cast<size_t>(n));
  11408. }
  11409. EXPECT_EQ("Hello World!", received);
  11410. #else
  11411. EXPECT_FALSE(handle.is_valid());
  11412. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11413. #endif
  11414. }
  11415. {
  11416. // A differently-cased coding must not be mistaken for an unknown one, or
  11417. // the body would be handed back still compressed.
  11418. auto res = cli.Get("/gzipped-uppercase");
  11419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11421. EXPECT_EQ("Hello World!", res->body);
  11422. #else
  11423. ASSERT_FALSE(res);
  11424. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11425. #endif
  11426. }
  11427. }
  11428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11429. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11430. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11431. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11432. // body a second time and appending a second Content-Encoding field line, so
  11433. // clients that decode one coding per listed value handed back raw gzip bytes.
  11434. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11435. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11436. Server svr;
  11437. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11438. // keeps the server from applying a coding of its own.
  11439. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11440. res.set_content(gzipped, "text/plain");
  11441. res.set_header("Content-Encoding", "gzip");
  11442. });
  11443. auto port = svr.bind_to_any_port(HOST);
  11444. thread t = thread([&]() { svr.listen_after_bind(); });
  11445. auto se = detail::scope_exit([&] {
  11446. svr.stop();
  11447. t.join();
  11448. ASSERT_FALSE(svr.is_running());
  11449. });
  11450. svr.wait_until_ready();
  11451. Client cli(HOST, port);
  11452. Headers headers = {{"Accept-Encoding", "gzip"}};
  11453. auto res = cli.Get("/pre-gzipped", headers);
  11454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11455. EXPECT_EQ(StatusCode::OK_200, res->status);
  11456. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11457. EXPECT_EQ("Hello World!", res->body);
  11458. }
  11459. // A chunked provider settles its coding where the headers are written and
  11460. // reuses it at write time. Both ends of that have to hold: a handler's own
  11461. // Content-Encoding suppresses the coding, and a response without one is still
  11462. // compressed as it always was.
  11463. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11464. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11465. const std::string plain = "Hello World! Hello World! Hello World!";
  11466. Server svr;
  11467. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11468. res.set_header("Content-Encoding", "gzip");
  11469. res.set_chunked_content_provider(
  11470. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11471. sink.write(gzipped.data(), gzipped.size());
  11472. sink.done();
  11473. return true;
  11474. });
  11475. });
  11476. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11477. res.set_chunked_content_provider(
  11478. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11479. sink.write(plain.data(), plain.size());
  11480. sink.done();
  11481. return true;
  11482. });
  11483. });
  11484. auto port = svr.bind_to_any_port(HOST);
  11485. thread t = thread([&]() { svr.listen_after_bind(); });
  11486. auto se = detail::scope_exit([&] {
  11487. svr.stop();
  11488. t.join();
  11489. ASSERT_FALSE(svr.is_running());
  11490. });
  11491. svr.wait_until_ready();
  11492. Client cli(HOST, port);
  11493. Headers headers = {{"Accept-Encoding", "gzip"}};
  11494. {
  11495. auto res = cli.Get("/pre-gzipped", headers);
  11496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11497. EXPECT_EQ(StatusCode::OK_200, res->status);
  11498. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11499. EXPECT_EQ("Hello World!", res->body);
  11500. }
  11501. {
  11502. auto res = cli.Get("/negotiated", headers);
  11503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11504. EXPECT_EQ(StatusCode::OK_200, res->status);
  11505. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11506. EXPECT_EQ(plain, res->body);
  11507. }
  11508. }
  11509. #endif
  11510. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11511. // the same message as the comma-joined one, so both have to be read the same
  11512. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11513. // single gzip coding, and a body the sender says was encoded twice was handed
  11514. // back after one pass, still compressed but presented as decoded.
  11515. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11516. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11517. Server svr;
  11518. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11519. res.set_content(body, "image/jpeg");
  11520. res.headers.emplace("Content-Encoding", "gzip");
  11521. res.headers.emplace("Content-Encoding", "gzip");
  11522. });
  11523. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11524. res.set_content(body, "image/jpeg");
  11525. res.set_header("Content-Encoding", "gzip, gzip");
  11526. });
  11527. auto port = svr.bind_to_any_port(HOST);
  11528. thread t = thread([&]() { svr.listen_after_bind(); });
  11529. auto se = detail::scope_exit([&] {
  11530. svr.stop();
  11531. t.join();
  11532. ASSERT_FALSE(svr.is_running());
  11533. });
  11534. svr.wait_until_ready();
  11535. Client cli(HOST, port);
  11536. // Two codings is not something cpp-httplib decodes, so both representations
  11537. // take the pass-through path rather than one of them being gunzipped once.
  11538. for (const char *path : {"/split", "/joined"}) {
  11539. auto res = cli.Get(path);
  11540. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11541. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11542. EXPECT_EQ(body, res->body) << path;
  11543. }
  11544. }
  11545. // Regression test for DoS vulnerability: a malicious server sending a response
  11546. // without Content-Length header must not cause unbounded memory consumption on
  11547. // the client side. The client should stop reading after a reasonable limit,
  11548. // similar to the server-side set_payload_max_length protection.
  11549. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11550. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11551. #ifndef _WIN32
  11552. signal(SIGPIPE, SIG_IGN);
  11553. #endif
  11554. auto server_thread = std::thread([] {
  11555. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11556. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11557. default_socket_options(srv);
  11558. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11559. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11560. sockaddr_in addr{};
  11561. addr.sin_family = AF_INET;
  11562. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11563. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11564. int opt = 1;
  11565. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11566. #ifdef _WIN32
  11567. reinterpret_cast<const char *>(&opt),
  11568. #else
  11569. &opt,
  11570. #endif
  11571. sizeof(opt));
  11572. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11573. ::listen(srv, 1);
  11574. sockaddr_in cli_addr{};
  11575. socklen_t cli_len = sizeof(cli_addr);
  11576. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11577. if (cli != INVALID_SOCKET) {
  11578. char buf[4096];
  11579. ::recv(cli, buf, sizeof(buf), 0);
  11580. // Malicious response: no Content-Length, no chunked encoding
  11581. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11582. "Connection: close\r\n"
  11583. "\r\n";
  11584. ::send(cli,
  11585. #ifdef _WIN32
  11586. static_cast<const char *>(response_header.c_str()),
  11587. static_cast<int>(response_header.size()),
  11588. #else
  11589. response_header.c_str(), response_header.size(),
  11590. #endif
  11591. 0);
  11592. // Send 10MB of data
  11593. std::string chunk(64 * 1024, 'A');
  11594. size_t total_sent = 0;
  11595. while (total_sent < MALICIOUS_DATA_SIZE) {
  11596. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11597. auto sent = ::send(cli,
  11598. #ifdef _WIN32
  11599. static_cast<const char *>(chunk.c_str()),
  11600. static_cast<int>(to_send),
  11601. #else
  11602. chunk.c_str(), to_send,
  11603. #endif
  11604. 0);
  11605. if (sent <= 0) break;
  11606. total_sent += static_cast<size_t>(sent);
  11607. }
  11608. detail::close_socket(cli);
  11609. }
  11610. detail::close_socket(srv);
  11611. });
  11612. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11613. size_t total_read = 0;
  11614. {
  11615. Client cli("127.0.0.1", PORT + 2);
  11616. cli.set_read_timeout(5, 0);
  11617. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11618. auto stream = cli.open_stream("GET", "/malicious");
  11619. ASSERT_TRUE(stream.is_valid());
  11620. char buffer[64 * 1024];
  11621. ssize_t n;
  11622. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11623. total_read += static_cast<size_t>(n);
  11624. }
  11625. } // StreamHandle and Client destroyed here, closing the socket
  11626. server_thread.join();
  11627. // With set_payload_max_length, the client must stop reading before consuming
  11628. // all 10MB. The read loop should be cut off at or near the configured limit.
  11629. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11630. << "Client read " << total_read << " bytes, exceeding the configured "
  11631. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11632. }
  11633. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11634. // the entire response body without truncation.
  11635. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11636. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11637. #ifndef _WIN32
  11638. signal(SIGPIPE, SIG_IGN);
  11639. #endif
  11640. auto server_thread = std::thread([] {
  11641. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11642. default_socket_options(srv);
  11643. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11644. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11645. sockaddr_in addr{};
  11646. addr.sin_family = AF_INET;
  11647. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11648. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11649. int opt = 1;
  11650. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11651. #ifdef _WIN32
  11652. reinterpret_cast<const char *>(&opt),
  11653. #else
  11654. &opt,
  11655. #endif
  11656. sizeof(opt));
  11657. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11658. ::listen(srv, 1);
  11659. sockaddr_in cli_addr{};
  11660. socklen_t cli_len = sizeof(cli_addr);
  11661. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11662. if (cli != INVALID_SOCKET) {
  11663. char buf[4096];
  11664. ::recv(cli, buf, sizeof(buf), 0);
  11665. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11666. "Connection: close\r\n"
  11667. "\r\n";
  11668. ::send(cli,
  11669. #ifdef _WIN32
  11670. static_cast<const char *>(response_header.c_str()),
  11671. static_cast<int>(response_header.size()),
  11672. #else
  11673. response_header.c_str(), response_header.size(),
  11674. #endif
  11675. 0);
  11676. std::string chunk(64 * 1024, 'A');
  11677. size_t total_sent = 0;
  11678. while (total_sent < DATA_SIZE) {
  11679. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11680. auto sent = ::send(cli,
  11681. #ifdef _WIN32
  11682. static_cast<const char *>(chunk.c_str()),
  11683. static_cast<int>(to_send),
  11684. #else
  11685. chunk.c_str(), to_send,
  11686. #endif
  11687. 0);
  11688. if (sent <= 0) break;
  11689. total_sent += static_cast<size_t>(sent);
  11690. }
  11691. #ifdef _WIN32
  11692. ::shutdown(cli, SD_SEND);
  11693. #else
  11694. ::shutdown(cli, SHUT_WR);
  11695. #endif
  11696. // Drain until the client closes its end, ensuring all data is delivered
  11697. char drain[1024];
  11698. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11699. detail::close_socket(cli);
  11700. }
  11701. detail::close_socket(srv);
  11702. });
  11703. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11704. size_t total_read = 0;
  11705. {
  11706. Client cli("127.0.0.1", PORT + 2);
  11707. cli.set_read_timeout(5, 0);
  11708. cli.set_payload_max_length(0); // 0 means no limit
  11709. auto stream = cli.open_stream("GET", "/data");
  11710. ASSERT_TRUE(stream.is_valid());
  11711. char buffer[64 * 1024];
  11712. ssize_t n;
  11713. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11714. total_read += static_cast<size_t>(n);
  11715. }
  11716. }
  11717. server_thread.join();
  11718. EXPECT_EQ(total_read, DATA_SIZE)
  11719. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11720. << " bytes without truncation, but only read " << total_read << " bytes.";
  11721. }
  11722. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11723. // enormous Content-Length must not cause the client to pre-allocate a huge
  11724. // response body buffer. The reservation is capped at payload_max_length_, and
  11725. // the read itself fails when the body exceeds the limit.
  11726. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11727. #ifndef _WIN32
  11728. signal(SIGPIPE, SIG_IGN);
  11729. #endif
  11730. auto server_thread = std::thread([] {
  11731. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11732. default_socket_options(srv);
  11733. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11734. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11735. sockaddr_in addr{};
  11736. addr.sin_family = AF_INET;
  11737. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11738. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11739. int opt = 1;
  11740. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11741. #ifdef _WIN32
  11742. reinterpret_cast<const char *>(&opt),
  11743. #else
  11744. &opt,
  11745. #endif
  11746. sizeof(opt));
  11747. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11748. ::listen(srv, 1);
  11749. sockaddr_in cli_addr{};
  11750. socklen_t cli_len = sizeof(cli_addr);
  11751. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11752. if (cli != INVALID_SOCKET) {
  11753. char buf[4096];
  11754. ::recv(cli, buf, sizeof(buf), 0);
  11755. // Malicious response: claim a 20GB body but send only a tiny payload.
  11756. std::string response = "HTTP/1.1 200 OK\r\n"
  11757. "Content-Length: 20000000000\r\n"
  11758. "\r\n"
  11759. "abc";
  11760. ::send(cli,
  11761. #ifdef _WIN32
  11762. static_cast<const char *>(response.c_str()),
  11763. static_cast<int>(response.size()),
  11764. #else
  11765. response.c_str(), response.size(),
  11766. #endif
  11767. 0);
  11768. detail::close_socket(cli);
  11769. }
  11770. detail::close_socket(srv);
  11771. });
  11772. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11773. {
  11774. Client cli("127.0.0.1", PORT + 2);
  11775. cli.set_read_timeout(5, 0);
  11776. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11777. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11778. // (server claims more bytes than payload_max_length permits), but it must
  11779. // not exhaust memory before getting there.
  11780. auto res = cli.Get("/malicious");
  11781. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11782. }
  11783. server_thread.join();
  11784. }
  11785. // Verify that content_receiver bypasses the default payload_max_length,
  11786. // allowing streaming downloads larger than 100MB without requiring an explicit
  11787. // set_payload_max_length call.
  11788. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11789. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11790. #ifndef _WIN32
  11791. signal(SIGPIPE, SIG_IGN);
  11792. #endif
  11793. auto server_thread = std::thread([] {
  11794. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11795. default_socket_options(srv);
  11796. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11797. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11798. sockaddr_in addr{};
  11799. addr.sin_family = AF_INET;
  11800. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11801. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11802. int opt = 1;
  11803. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11804. #ifdef _WIN32
  11805. reinterpret_cast<const char *>(&opt),
  11806. #else
  11807. &opt,
  11808. #endif
  11809. sizeof(opt));
  11810. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11811. ::listen(srv, 1);
  11812. sockaddr_in cli_addr{};
  11813. socklen_t cli_len = sizeof(cli_addr);
  11814. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11815. if (cli != INVALID_SOCKET) {
  11816. char buf[4096];
  11817. ::recv(cli, buf, sizeof(buf), 0);
  11818. // Response with Content-Length larger than default 100MB limit
  11819. auto content_length = std::to_string(DATA_SIZE);
  11820. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11821. "Content-Length: " +
  11822. content_length +
  11823. "\r\n"
  11824. "Connection: close\r\n"
  11825. "\r\n";
  11826. ::send(cli,
  11827. #ifdef _WIN32
  11828. static_cast<const char *>(response_header.c_str()),
  11829. static_cast<int>(response_header.size()),
  11830. #else
  11831. response_header.c_str(), response_header.size(),
  11832. #endif
  11833. 0);
  11834. std::string chunk(64 * 1024, 'A');
  11835. size_t total_sent = 0;
  11836. while (total_sent < DATA_SIZE) {
  11837. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11838. auto sent = ::send(cli,
  11839. #ifdef _WIN32
  11840. static_cast<const char *>(chunk.c_str()),
  11841. static_cast<int>(to_send),
  11842. #else
  11843. chunk.c_str(), to_send,
  11844. #endif
  11845. 0);
  11846. if (sent <= 0) break;
  11847. total_sent += static_cast<size_t>(sent);
  11848. }
  11849. detail::close_socket(cli);
  11850. }
  11851. detail::close_socket(srv);
  11852. });
  11853. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11854. size_t total_received = 0;
  11855. {
  11856. Client cli("127.0.0.1", PORT + 2);
  11857. cli.set_read_timeout(10, 0);
  11858. // Do NOT call set_payload_max_length — use the default 100MB limit
  11859. auto res =
  11860. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11861. total_received += data_length;
  11862. return true;
  11863. });
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ(StatusCode::OK_200, res->status);
  11866. }
  11867. server_thread.join();
  11868. EXPECT_EQ(total_received, DATA_SIZE)
  11869. << "With content_receiver, the client should read all " << DATA_SIZE
  11870. << " bytes despite the default 100MB payload_max_length, but only read "
  11871. << total_received << " bytes.";
  11872. }
  11873. // Verify that an explicit set_payload_max_length smaller than the response is
  11874. // enforced even when a content_receiver is used.
  11875. TEST(ClientVulnerabilityTest,
  11876. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11877. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11878. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11879. #ifndef _WIN32
  11880. signal(SIGPIPE, SIG_IGN);
  11881. #endif
  11882. auto server_thread = std::thread([] {
  11883. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11884. default_socket_options(srv);
  11885. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11887. sockaddr_in addr{};
  11888. addr.sin_family = AF_INET;
  11889. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11890. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11891. int opt = 1;
  11892. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11893. #ifdef _WIN32
  11894. reinterpret_cast<const char *>(&opt),
  11895. #else
  11896. &opt,
  11897. #endif
  11898. sizeof(opt));
  11899. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11900. ::listen(srv, 1);
  11901. sockaddr_in cli_addr{};
  11902. socklen_t cli_len = sizeof(cli_addr);
  11903. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11904. if (cli != INVALID_SOCKET) {
  11905. char buf[4096];
  11906. ::recv(cli, buf, sizeof(buf), 0);
  11907. auto content_length = std::to_string(DATA_SIZE);
  11908. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11909. "Content-Length: " +
  11910. content_length +
  11911. "\r\n"
  11912. "Connection: close\r\n"
  11913. "\r\n";
  11914. ::send(cli,
  11915. #ifdef _WIN32
  11916. static_cast<const char *>(response_header.c_str()),
  11917. static_cast<int>(response_header.size()),
  11918. #else
  11919. response_header.c_str(), response_header.size(),
  11920. #endif
  11921. 0);
  11922. std::string chunk(64 * 1024, 'A');
  11923. size_t total_sent = 0;
  11924. while (total_sent < DATA_SIZE) {
  11925. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11926. auto sent = ::send(cli,
  11927. #ifdef _WIN32
  11928. static_cast<const char *>(chunk.c_str()),
  11929. static_cast<int>(to_send),
  11930. #else
  11931. chunk.c_str(), to_send,
  11932. #endif
  11933. 0);
  11934. if (sent <= 0) break;
  11935. total_sent += static_cast<size_t>(sent);
  11936. }
  11937. detail::close_socket(cli);
  11938. }
  11939. detail::close_socket(srv);
  11940. });
  11941. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11942. size_t total_received = 0;
  11943. {
  11944. Client cli("127.0.0.1", PORT + 2);
  11945. cli.set_read_timeout(10, 0);
  11946. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11947. auto res =
  11948. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11949. total_received += data_length;
  11950. return true;
  11951. });
  11952. // Should fail because 200MB exceeds the explicit 150MB limit
  11953. EXPECT_FALSE(res);
  11954. }
  11955. server_thread.join();
  11956. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11957. << "Client with content_receiver should respect the explicit "
  11958. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11959. << total_received << " bytes.";
  11960. }
  11961. // Verify that an explicit set_payload_max_length larger than the response
  11962. // allows the content_receiver to read all data successfully.
  11963. TEST(ClientVulnerabilityTest,
  11964. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11965. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11966. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11967. #ifndef _WIN32
  11968. signal(SIGPIPE, SIG_IGN);
  11969. #endif
  11970. auto server_thread = std::thread([] {
  11971. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11972. default_socket_options(srv);
  11973. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11974. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11975. sockaddr_in addr{};
  11976. addr.sin_family = AF_INET;
  11977. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11978. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11979. int opt = 1;
  11980. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11981. #ifdef _WIN32
  11982. reinterpret_cast<const char *>(&opt),
  11983. #else
  11984. &opt,
  11985. #endif
  11986. sizeof(opt));
  11987. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11988. ::listen(srv, 1);
  11989. sockaddr_in cli_addr{};
  11990. socklen_t cli_len = sizeof(cli_addr);
  11991. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11992. if (cli != INVALID_SOCKET) {
  11993. char buf[4096];
  11994. ::recv(cli, buf, sizeof(buf), 0);
  11995. auto content_length = std::to_string(DATA_SIZE);
  11996. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11997. "Content-Length: " +
  11998. content_length +
  11999. "\r\n"
  12000. "Connection: close\r\n"
  12001. "\r\n";
  12002. ::send(cli,
  12003. #ifdef _WIN32
  12004. static_cast<const char *>(response_header.c_str()),
  12005. static_cast<int>(response_header.size()),
  12006. #else
  12007. response_header.c_str(), response_header.size(),
  12008. #endif
  12009. 0);
  12010. std::string chunk(64 * 1024, 'A');
  12011. size_t total_sent = 0;
  12012. while (total_sent < DATA_SIZE) {
  12013. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12014. auto sent = ::send(cli,
  12015. #ifdef _WIN32
  12016. static_cast<const char *>(chunk.c_str()),
  12017. static_cast<int>(to_send),
  12018. #else
  12019. chunk.c_str(), to_send,
  12020. #endif
  12021. 0);
  12022. if (sent <= 0) break;
  12023. total_sent += static_cast<size_t>(sent);
  12024. }
  12025. #ifdef _WIN32
  12026. ::shutdown(cli, SD_SEND);
  12027. #else
  12028. ::shutdown(cli, SHUT_WR);
  12029. #endif
  12030. char drain[1024];
  12031. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12032. detail::close_socket(cli);
  12033. }
  12034. detail::close_socket(srv);
  12035. });
  12036. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12037. size_t total_received = 0;
  12038. {
  12039. Client cli("127.0.0.1", PORT + 2);
  12040. cli.set_read_timeout(10, 0);
  12041. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12042. auto res =
  12043. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12044. total_received += data_length;
  12045. return true;
  12046. });
  12047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12048. EXPECT_EQ(StatusCode::OK_200, res->status);
  12049. }
  12050. server_thread.join();
  12051. EXPECT_EQ(total_received, DATA_SIZE)
  12052. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12053. << " bytes (larger than " << DATA_SIZE
  12054. << " bytes response), content_receiver should read all data, but only "
  12055. "read "
  12056. << total_received << " bytes.";
  12057. }
  12058. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12059. // Regression test for "zip bomb" attack on the client side: a malicious server
  12060. // sends a small gzip-compressed response that decompresses to a huge payload.
  12061. // The client must enforce payload_max_length on the decompressed size.
  12062. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12063. constexpr size_t DECOMPRESSED_SIZE =
  12064. 10 * 1024 * 1024; // 10MB after decompression
  12065. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12066. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12067. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12068. std::string compressed;
  12069. {
  12070. httplib::detail::gzip_compressor compressor;
  12071. bool ok =
  12072. compressor.compress(uncompressed.data(), uncompressed.size(),
  12073. /*last=*/true, [&](const char *buf, size_t len) {
  12074. compressed.append(buf, len);
  12075. return true;
  12076. });
  12077. ASSERT_TRUE(ok);
  12078. }
  12079. // Sanity: compressed data should be much smaller than the decompressed size
  12080. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12081. #ifndef _WIN32
  12082. signal(SIGPIPE, SIG_IGN);
  12083. #endif
  12084. // Set up the listening socket in the main thread so the server is guaranteed
  12085. // to be ready before the client connects (eliminates race condition).
  12086. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12087. default_socket_options(srv);
  12088. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12089. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12090. sockaddr_in addr{};
  12091. addr.sin_family = AF_INET;
  12092. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12093. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12094. int opt = 1;
  12095. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12096. #ifdef _WIN32
  12097. reinterpret_cast<const char *>(&opt),
  12098. #else
  12099. &opt,
  12100. #endif
  12101. sizeof(opt));
  12102. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12103. ASSERT_EQ(0, ::listen(srv, 1));
  12104. auto server_thread = std::thread([&compressed, srv] {
  12105. sockaddr_in cli_addr{};
  12106. socklen_t cli_len = sizeof(cli_addr);
  12107. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12108. if (cli != INVALID_SOCKET) {
  12109. // Read the full HTTP request (until \r\n\r\n)
  12110. char buf[4096];
  12111. size_t total = 0;
  12112. while (total < sizeof(buf)) {
  12113. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12114. if (n <= 0) break;
  12115. total += static_cast<size_t>(n);
  12116. // Check for end of headers
  12117. if (total >= 4) {
  12118. std::string req(buf, total);
  12119. if (req.find("\r\n\r\n") != std::string::npos) break;
  12120. }
  12121. }
  12122. // Malicious response: gzip-compressed body, no Content-Length
  12123. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12124. "Content-Encoding: gzip\r\n"
  12125. "Connection: close\r\n"
  12126. "\r\n";
  12127. ::send(cli,
  12128. #ifdef _WIN32
  12129. static_cast<const char *>(response_header.c_str()),
  12130. static_cast<int>(response_header.size()),
  12131. #else
  12132. response_header.c_str(), response_header.size(),
  12133. #endif
  12134. 0);
  12135. // Send the compressed payload (small on the wire, huge when decompressed)
  12136. size_t total_sent = 0;
  12137. while (total_sent < compressed.size()) {
  12138. auto to_send = std::min(compressed.size() - total_sent,
  12139. static_cast<size_t>(64 * 1024));
  12140. auto sent =
  12141. ::send(cli,
  12142. #ifdef _WIN32
  12143. static_cast<const char *>(compressed.c_str() + total_sent),
  12144. static_cast<int>(to_send),
  12145. #else
  12146. compressed.c_str() + total_sent, to_send,
  12147. #endif
  12148. 0);
  12149. if (sent <= 0) break;
  12150. total_sent += static_cast<size_t>(sent);
  12151. }
  12152. detail::close_socket(cli);
  12153. }
  12154. });
  12155. auto se = detail::scope_exit([&] {
  12156. detail::close_socket(srv);
  12157. server_thread.join();
  12158. });
  12159. size_t total_decompressed = 0;
  12160. {
  12161. Client cli("127.0.0.1", PORT + 3);
  12162. cli.set_read_timeout(5, 0);
  12163. cli.set_decompress(true);
  12164. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12165. auto stream = cli.open_stream("GET", "/zipbomb");
  12166. ASSERT_TRUE(stream.is_valid());
  12167. char buffer[64 * 1024];
  12168. ssize_t n;
  12169. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12170. total_decompressed += static_cast<size_t>(n);
  12171. }
  12172. }
  12173. // The decompressed size must be capped by payload_max_length. Without
  12174. // protection, the client would decompress the full 10MB from a tiny
  12175. // compressed payload, enabling a zip bomb DoS attack.
  12176. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12177. << "Client decompressed " << total_decompressed
  12178. << " bytes from a gzip response. The decompressed size should be "
  12179. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12180. }
  12181. #endif
  12182. TEST(HostAndPortPropertiesTest, NoSSL) {
  12183. httplib::Client cli("www.google.com", 1234);
  12184. ASSERT_EQ("www.google.com", cli.host());
  12185. ASSERT_EQ(1234, cli.port());
  12186. }
  12187. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12188. httplib::Client cli("www.google.com:1234");
  12189. ASSERT_EQ("www.google.com", cli.host());
  12190. ASSERT_EQ(1234, cli.port());
  12191. }
  12192. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12193. // Port number that overflows int — should not crash, client becomes invalid
  12194. httplib::Client cli("http://www.google.com:99999999999999999999");
  12195. ASSERT_FALSE(cli.is_valid());
  12196. }
  12197. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12198. // Port 99999 exceeds valid range (1-65535) — should not crash
  12199. httplib::Client cli("http://www.google.com:99999");
  12200. ASSERT_FALSE(cli.is_valid());
  12201. }
  12202. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12203. httplib::Client cli("http://www.google.com:80abc");
  12204. ASSERT_FALSE(cli.is_valid());
  12205. }
  12206. #ifdef CPPHTTPLIB_SSL_ENABLED
  12207. TEST(HostAndPortPropertiesTest, SSL) {
  12208. httplib::SSLClient cli("www.google.com");
  12209. ASSERT_EQ("www.google.com", cli.host());
  12210. ASSERT_EQ(443, cli.port());
  12211. }
  12212. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12213. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12214. std::string cert;
  12215. read_file(CA_CERT_FILE, cert);
  12216. httplib::SSLClient httplib_client("www.google.com");
  12217. // Load CA store first time
  12218. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12219. // Load CA store second time (update)
  12220. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12221. // Verify client is still valid and can make connections
  12222. httplib_client.enable_server_certificate_verification(true);
  12223. auto res = httplib_client.Get("/");
  12224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12225. // Google may return 200 or 301 depending on various factors
  12226. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12227. res->status == StatusCode::MovedPermanently_301);
  12228. }
  12229. TEST(SSLClientTest, ServerNameIndication_Online) {
  12230. auto host = "httpbingo.org";
  12231. auto path = std::string{"/get"};
  12232. SSLClient cli(host, 443);
  12233. auto res = cli.Get(path);
  12234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12235. ASSERT_EQ(StatusCode::OK_200, res->status);
  12236. }
  12237. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12238. // Use a site that will cause SSL verification failure due to self-signed cert
  12239. SSLClient cli("self-signed.badssl.com", 443);
  12240. cli.enable_server_certificate_verification(true);
  12241. auto res = cli.Get("/");
  12242. ASSERT_TRUE(!res);
  12243. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12244. // Verify backend error is captured for SSLServerVerification
  12245. // This occurs when certificate verification fails
  12246. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12247. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12248. EXPECT_NE(0UL, res.ssl_backend_error());
  12249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12250. // For OpenSSL, ssl_error is 0 for verification errors
  12251. EXPECT_EQ(0, res.ssl_error());
  12252. #if !defined(_WIN32) || \
  12253. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12254. // On non-Windows or when Windows Schannel is disabled, the error comes
  12255. // from OpenSSL's verification
  12256. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12257. res.ssl_backend_error());
  12258. #endif
  12259. #endif
  12260. }
  12261. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12262. // Use a site where hostname doesn't match the certificate
  12263. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12264. SSLClient cli("wrong.host.badssl.com", 443);
  12265. cli.enable_server_certificate_verification(true);
  12266. cli.enable_server_hostname_verification(true);
  12267. auto res = cli.Get("/");
  12268. ASSERT_TRUE(!res);
  12269. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12270. // Verify backend error is captured for hostname verification failure
  12271. EXPECT_NE(0UL, res.ssl_backend_error());
  12272. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12273. // For OpenSSL, ssl_error is 0 for verification errors
  12274. EXPECT_EQ(0, res.ssl_error());
  12275. #if !defined(_WIN32) || \
  12276. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12277. // On non-Windows or when Windows Schannel is disabled, the error comes
  12278. // from OpenSSL's hostname verification
  12279. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12280. res.ssl_backend_error());
  12281. #endif
  12282. #endif
  12283. }
  12284. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12285. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12286. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12287. SSLClient cli("www.google.com", 443);
  12288. cli.enable_server_certificate_verification(true);
  12289. auto res = cli.Get("/");
  12290. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12291. }
  12292. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12293. SSLClient cli("www.google.com", 443);
  12294. cli.enable_server_certificate_verification(true);
  12295. cli.enable_windows_certificate_verification(false);
  12296. auto res = cli.Get("/");
  12297. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12298. }
  12299. // The server sends an intermediate cross-signed by a root Windows trusts,
  12300. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12301. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12302. SSLClient cli("accounts.spotify.com", 443);
  12303. auto res = cli.Get("/");
  12304. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12305. << " ssl_backend_error=" << res.ssl_backend_error();
  12306. }
  12307. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12308. // policy status, which no backend reports for a self-signed certificate.
  12309. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12310. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12311. ASSERT_TRUE(svr.is_valid());
  12312. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12313. auto se = detail::scope_exit([&] {
  12314. svr.stop();
  12315. t.join();
  12316. ASSERT_FALSE(svr.is_running());
  12317. });
  12318. svr.wait_until_ready();
  12319. SSLClient cli("127.0.0.1", PORT);
  12320. cli.set_connection_timeout(30);
  12321. auto res = cli.Get("/");
  12322. ASSERT_FALSE(res);
  12323. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12324. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12325. }
  12326. #endif
  12327. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12328. Client cli("https://google.com");
  12329. auto res = cli.Get("/");
  12330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12331. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12332. }
  12333. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12334. SSLClient cli("google.com");
  12335. cli.set_ca_cert_path(CA_CERT_FILE);
  12336. auto res = cli.Get("/");
  12337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12338. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12339. }
  12340. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12341. SSLClient cli("google.com");
  12342. cli.enable_server_certificate_verification(true);
  12343. cli.set_ca_cert_path("hello");
  12344. auto res = cli.Get("/");
  12345. ASSERT_TRUE(!res);
  12346. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12347. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12348. // should be set
  12349. EXPECT_EQ(0, res.ssl_error());
  12350. // Verify backend error is captured for SSLLoadingCerts
  12351. // This error occurs when loading CA certificates fails
  12352. EXPECT_NE(0UL, res.ssl_backend_error());
  12353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12354. // OpenSSL specific error codes:
  12355. // > openssl errstr 0x80000002
  12356. // error:80000002:system library::No such file or directory
  12357. // > openssl errstr 0xA000126
  12358. // error:0A000126:SSL routines::unexpected eof while reading
  12359. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12360. res.ssl_backend_error() == 0xA000126);
  12361. #endif
  12362. }
  12363. TEST(SSLClientTest, ServerCertificateVerification4) {
  12364. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12365. ASSERT_TRUE(svr.is_valid());
  12366. svr.Get("/test", [&](const Request &, Response &res) {
  12367. res.set_content("test", "text/plain");
  12368. svr.stop();
  12369. ASSERT_TRUE(true);
  12370. });
  12371. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12372. auto se = detail::scope_exit([&] {
  12373. t.join();
  12374. ASSERT_FALSE(svr.is_running());
  12375. });
  12376. svr.wait_until_ready();
  12377. SSLClient cli("127.0.0.1", PORT);
  12378. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12379. cli.enable_server_certificate_verification(true);
  12380. cli.set_connection_timeout(30);
  12381. auto res = cli.Get("/test");
  12382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12383. ASSERT_EQ(StatusCode::OK_200, res->status);
  12384. }
  12385. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12386. std::string cert;
  12387. read_file(CA_CERT_FILE, cert);
  12388. SSLClient cli("google.com");
  12389. cli.load_ca_cert_store(cert.data(), cert.size());
  12390. const auto res = cli.Get("/");
  12391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12392. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12393. }
  12394. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12395. // clang-format off
  12396. static constexpr char cert[] =
  12397. "GlobalSign Root CA\n"
  12398. "==================\n"
  12399. "-----BEGIN CERTIFICATE-----\n"
  12400. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12401. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12402. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12403. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12404. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12405. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12406. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12407. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12408. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12409. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12410. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12411. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12412. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12413. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12414. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12415. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12416. "-----END CERTIFICATE-----\n";
  12417. // clang-format on
  12418. SSLClient cli("google.com");
  12419. cli.load_ca_cert_store(cert, sizeof(cert));
  12420. const auto res = cli.Get("/");
  12421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12422. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12423. }
  12424. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12425. SSLClient cli("www.youtube.com");
  12426. cli.set_ca_cert_path(CA_CERT_FILE);
  12427. cli.enable_server_certificate_verification(true);
  12428. cli.set_follow_location(true);
  12429. auto res = cli.Get("/");
  12430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12431. ASSERT_EQ(StatusCode::OK_200, res->status);
  12432. }
  12433. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12434. SSLClient cli("wWw.YouTube.Com");
  12435. cli.set_ca_cert_path(CA_CERT_FILE);
  12436. cli.enable_server_certificate_verification(true);
  12437. cli.enable_server_hostname_verification(true);
  12438. cli.set_follow_location(true);
  12439. auto res = cli.Get("/");
  12440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12441. ASSERT_EQ(StatusCode::OK_200, res->status);
  12442. }
  12443. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12444. SSLClient cli("gOoGlE.COm");
  12445. cli.enable_server_certificate_verification(true);
  12446. cli.enable_server_hostname_verification(true);
  12447. cli.set_follow_location(true);
  12448. auto res = cli.Get("/");
  12449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12450. ASSERT_EQ(StatusCode::OK_200, res->status);
  12451. }
  12452. TEST(SSLClientTest, Issue2004_Online) {
  12453. Client client("https://google.com");
  12454. client.set_follow_location(true);
  12455. auto res = client.Get("/");
  12456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12457. ASSERT_EQ(StatusCode::OK_200, res->status);
  12458. auto body = res->body;
  12459. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12460. }
  12461. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12462. // Create SSLClient with invalid cert/key to make is_valid() return false
  12463. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12464. "nonexistent_key.pem");
  12465. // is_valid() should be false due to cert loading failure
  12466. ASSERT_FALSE(cli.is_valid());
  12467. auto res = cli.Get("/");
  12468. ASSERT_FALSE(res);
  12469. EXPECT_EQ(Error::SSLConnection, res.error());
  12470. }
  12471. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12472. // Test for Issue #2251: SSL error not properly reported when client cert
  12473. // and key paths are swapped or mismatched
  12474. // This simulates the scenario where user accidentally swaps the cert and key
  12475. // files
  12476. // Using client cert file as private key and vice versa (completely wrong)
  12477. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12478. // Should fail validation due to cert/key mismatch
  12479. ASSERT_FALSE(cli.is_valid());
  12480. // Attempt to make a request should fail with proper error
  12481. auto res = cli.Get("/");
  12482. ASSERT_FALSE(res);
  12483. EXPECT_EQ(Error::SSLConnection, res.error());
  12484. // SSL error should be recorded in the Result object (this is the key fix for
  12485. // Issue #2251)
  12486. auto backend_error = res.ssl_backend_error();
  12487. EXPECT_NE(0u, backend_error);
  12488. }
  12489. // Tests cert/key mismatch detection at the TLS context level
  12490. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12491. // Test that using mismatched cert/key causes connection failure.
  12492. // We verify this at the SSLClient level rather than through internal
  12493. // TLS API functions.
  12494. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12495. cli.enable_server_certificate_verification(false);
  12496. cli.set_connection_timeout(2);
  12497. // The mismatch should cause a connection or handshake error
  12498. auto res = cli.Get("/test");
  12499. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12500. // Either way, the request should fail
  12501. EXPECT_FALSE(res);
  12502. }
  12503. #endif
  12504. #if 0
  12505. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12506. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12507. ASSERT_TRUE(cli != nullptr);
  12508. cli->set_address_family(AF_INET6);
  12509. cli->set_interface("en0");
  12510. auto res = cli->Get("/get");
  12511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12512. ASSERT_EQ(StatusCode::OK_200, res->status);
  12513. }
  12514. #endif
  12515. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12516. #ifdef CPPHTTPLIB_SSL_ENABLED
  12517. void ClientCertPresent(
  12518. const std::string &client_cert_file,
  12519. const std::string &client_private_key_file,
  12520. const std::string &client_encrypted_private_key_pass = std::string()) {
  12521. using namespace httplib::tls;
  12522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12523. CLIENT_CA_CERT_DIR);
  12524. ASSERT_TRUE(svr.is_valid());
  12525. svr.Get("/test", [&](const Request &req, Response &res) {
  12526. res.set_content("test", "text/plain");
  12527. auto cert = req.peer_cert();
  12528. ASSERT_TRUE(static_cast<bool>(cert));
  12529. std::string common_name = cert.subject_cn();
  12530. EXPECT_EQ("Common Name", common_name);
  12531. });
  12532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12533. auto se = detail::scope_exit([&] {
  12534. svr.stop();
  12535. t.join();
  12536. ASSERT_FALSE(svr.is_running());
  12537. });
  12538. svr.wait_until_ready();
  12539. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12540. client_encrypted_private_key_pass);
  12541. cli.enable_server_certificate_verification(false);
  12542. cli.set_connection_timeout(30);
  12543. auto res = cli.Get("/test");
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. ASSERT_EQ(StatusCode::OK_200, res->status);
  12546. }
  12547. TEST(SSLClientServerTest, ClientCertPresent) {
  12548. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12549. }
  12550. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12551. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12552. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12553. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12554. }
  12555. // PEM memory-based constructor tests (works with all TLS backends)
  12556. void PemMemoryClientCertPresent(
  12557. const std::string &client_cert_file,
  12558. const std::string &client_private_key_file,
  12559. const std::string &client_encrypted_private_key_pass = std::string()) {
  12560. // Read PEM files into memory
  12561. std::string server_cert_pem, server_key_pem;
  12562. std::string client_ca_pem;
  12563. std::string client_cert_pem, client_key_pem;
  12564. read_file(SERVER_CERT_FILE, server_cert_pem);
  12565. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12566. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12567. read_file(client_cert_file, client_cert_pem);
  12568. read_file(client_private_key_file, client_key_pem);
  12569. // Create server with PEM memory
  12570. SSLServer::PemMemory server_pem = {
  12571. server_cert_pem.c_str(),
  12572. server_cert_pem.size(),
  12573. server_key_pem.c_str(),
  12574. server_key_pem.size(),
  12575. client_ca_pem.c_str(),
  12576. client_ca_pem.size(),
  12577. nullptr // no password for server key
  12578. };
  12579. SSLServer svr(server_pem);
  12580. ASSERT_TRUE(svr.is_valid());
  12581. svr.Get("/test", [&](const Request &, Response &res) {
  12582. res.set_content("test", "text/plain");
  12583. });
  12584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12585. auto se = detail::scope_exit([&] {
  12586. svr.stop();
  12587. t.join();
  12588. ASSERT_FALSE(svr.is_running());
  12589. });
  12590. svr.wait_until_ready();
  12591. // Create client with PEM memory
  12592. const char *password = client_encrypted_private_key_pass.empty()
  12593. ? nullptr
  12594. : client_encrypted_private_key_pass.c_str();
  12595. SSLClient::PemMemory client_pem = {
  12596. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12597. client_key_pem.size(), password};
  12598. SSLClient cli(HOST, PORT, client_pem);
  12599. cli.enable_server_certificate_verification(false);
  12600. cli.set_connection_timeout(30);
  12601. auto res = cli.Get("/test");
  12602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12603. ASSERT_EQ(StatusCode::OK_200, res->status);
  12604. }
  12605. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12606. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12607. }
  12608. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12609. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12610. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12611. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12612. }
  12613. TEST(SSLClientServerTest, ClientCertMissing) {
  12614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12615. CLIENT_CA_CERT_DIR);
  12616. ASSERT_TRUE(svr.is_valid());
  12617. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12618. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12619. auto se = detail::scope_exit([&] {
  12620. svr.stop();
  12621. t.join();
  12622. ASSERT_FALSE(svr.is_running());
  12623. });
  12624. svr.wait_until_ready();
  12625. SSLClient cli(HOST, PORT);
  12626. cli.set_connection_timeout(30);
  12627. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12628. // the chain check on Windows, so the result does not depend on the order.
  12629. cli.enable_server_hostname_verification(false);
  12630. auto res = cli.Get("/test");
  12631. ASSERT_TRUE(!res);
  12632. // When client cert is missing and server requires it, connection fails
  12633. // Error type depends on backend implementation
  12634. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12635. res.error() == Error::SSLConnection);
  12636. // Verify backend error is captured
  12637. // Note: This test may have different error codes depending on the exact
  12638. // verification failure
  12639. EXPECT_NE(0UL, res.ssl_backend_error());
  12640. }
  12641. TEST(SSLClientServerTest, TrustDirOptional) {
  12642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12643. ASSERT_TRUE(svr.is_valid());
  12644. svr.Get("/test", [&](const Request &, Response &res) {
  12645. res.set_content("test", "text/plain");
  12646. });
  12647. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12648. auto se = detail::scope_exit([&] {
  12649. svr.stop();
  12650. t.join();
  12651. ASSERT_FALSE(svr.is_running());
  12652. });
  12653. svr.wait_until_ready();
  12654. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12655. cli.enable_server_certificate_verification(false);
  12656. cli.set_connection_timeout(30);
  12657. auto res = cli.Get("/test");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. ASSERT_EQ(StatusCode::OK_200, res->status);
  12660. }
  12661. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12662. class NoListenSSLServer : public SSLServer {
  12663. public:
  12664. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12665. const char *client_ca_cert_file_path,
  12666. const char *client_ca_cert_dir_path = nullptr)
  12667. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12668. client_ca_cert_dir_path),
  12669. stop_(false) {}
  12670. std::atomic_bool stop_;
  12671. private:
  12672. bool process_and_close_socket(socket_t /*sock*/) override {
  12673. // Don't create SSL context
  12674. while (!stop_.load()) {
  12675. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12676. }
  12677. return true;
  12678. }
  12679. };
  12680. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12681. CLIENT_CA_CERT_FILE);
  12682. ASSERT_TRUE(svr.is_valid());
  12683. svr.Get("/test", [&](const Request &, Response &res) {
  12684. res.set_content("test", "text/plain");
  12685. });
  12686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop_ = true;
  12689. svr.stop();
  12690. t.join();
  12691. ASSERT_FALSE(svr.is_running());
  12692. });
  12693. svr.wait_until_ready();
  12694. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12695. cli.enable_server_certificate_verification(false);
  12696. cli.set_connection_timeout(1);
  12697. auto res = cli.Get("/test");
  12698. ASSERT_TRUE(!res);
  12699. EXPECT_EQ(Error::SSLConnection, res.error());
  12700. // Timeout results in WantRead error code (maps to backend-specific value)
  12701. EXPECT_NE(0, res.ssl_error());
  12702. }
  12703. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12704. // Test SSLServer with client certificate verification using the standard
  12705. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12707. CLIENT_CA_CERT_DIR);
  12708. ASSERT_TRUE(svr.is_valid());
  12709. svr.Get("/test", [&](const Request &req, Response &res) {
  12710. res.set_content("test", "text/plain");
  12711. auto cert = req.peer_cert();
  12712. ASSERT_TRUE(static_cast<bool>(cert));
  12713. auto common_name = cert.subject_cn();
  12714. EXPECT_EQ("Common Name", common_name);
  12715. });
  12716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12717. auto se = detail::scope_exit([&] {
  12718. svr.stop();
  12719. t.join();
  12720. ASSERT_FALSE(svr.is_running());
  12721. });
  12722. svr.wait_until_ready();
  12723. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12724. cli.enable_server_certificate_verification(false);
  12725. cli.set_connection_timeout(30);
  12726. auto res = cli.Get("/test");
  12727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12728. ASSERT_EQ(StatusCode::OK_200, res->status);
  12729. }
  12730. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12731. // Verifies that wildcard matching and exact matching work consistently
  12732. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12733. using namespace httplib::tls;
  12734. // We need a running server to test against
  12735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12736. ASSERT_TRUE(svr.is_valid());
  12737. svr.Get("/test", [](const Request &, Response &res) {
  12738. res.set_content("ok", "text/plain");
  12739. });
  12740. thread t([&]() { svr.listen(HOST, PORT); });
  12741. auto se = detail::scope_exit([&] {
  12742. svr.stop();
  12743. t.join();
  12744. });
  12745. svr.wait_until_ready();
  12746. bool verify_callback_called = false;
  12747. bool verify_result_wrong = false;
  12748. SSLClient cli(HOST, PORT);
  12749. cli.enable_server_certificate_verification(true);
  12750. cli.set_ca_cert_path(CA_CERT_FILE);
  12751. cli.set_connection_timeout(5);
  12752. // Note: Test certificate has CN="Common Name", not "localhost"
  12753. bool verify_result_cn = false;
  12754. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12755. verify_callback_called = true;
  12756. if (!ctx.cert) return false;
  12757. // Test 1: "Common Name" should match (our test server cert CN)
  12758. verify_result_cn = ctx.check_hostname("Common Name");
  12759. // Test 2: wrong hostname should not match
  12760. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12761. return true; // Accept for the purpose of this test
  12762. });
  12763. auto res = cli.Get("/test");
  12764. // The request may succeed or fail depending on cert configuration
  12765. // but the callback should have been called
  12766. ASSERT_TRUE(verify_callback_called)
  12767. << "Verify callback should have been called";
  12768. // CN="Common Name" should match our test certificate
  12769. //
  12770. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12771. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12772. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12773. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12774. // <openssl/base.h>, which is included transitively when
  12775. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12776. #if defined(OPENSSL_IS_BORINGSSL)
  12777. EXPECT_FALSE(verify_result_cn)
  12778. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12779. #else
  12780. EXPECT_TRUE(verify_result_cn)
  12781. << "verify_hostname should match 'Common Name' (certificate CN)";
  12782. #endif
  12783. // Wrong hostname should not match
  12784. EXPECT_FALSE(verify_result_wrong)
  12785. << "verify_hostname should not match 'wronghost.example.com'";
  12786. }
  12787. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12788. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12789. // X509_check_ip behavior and must hold for every backend.
  12790. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12791. using namespace httplib::tls;
  12792. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12793. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12794. ASSERT_TRUE(svr.is_valid());
  12795. svr.Get("/test", [](const Request &, Response &res) {
  12796. res.set_content("ok", "text/plain");
  12797. });
  12798. thread t([&]() { svr.listen(HOST, PORT); });
  12799. auto se = detail::scope_exit([&] {
  12800. svr.stop();
  12801. t.join();
  12802. });
  12803. svr.wait_until_ready();
  12804. bool verify_callback_called = false;
  12805. bool ip_matched_via_cn = true;
  12806. SSLClient cli(HOST, PORT);
  12807. cli.enable_server_certificate_verification(true);
  12808. cli.set_ca_cert_path(CA_CERT_FILE);
  12809. cli.set_connection_timeout(5);
  12810. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12811. verify_callback_called = true;
  12812. if (!ctx.cert) return false;
  12813. // The IP appears only in the CN, so it must NOT be accepted.
  12814. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12815. return true; // Accept for the purpose of this test
  12816. });
  12817. cli.Get("/test");
  12818. ASSERT_TRUE(verify_callback_called)
  12819. << "Verify callback should have been called";
  12820. EXPECT_FALSE(ip_matched_via_cn)
  12821. << "An IP host must not be authenticated via the certificate CN";
  12822. }
  12823. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12824. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12825. using namespace httplib::tls;
  12826. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12827. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12828. ASSERT_TRUE(svr.is_valid());
  12829. svr.Get("/test", [](const Request &, Response &res) {
  12830. res.set_content("ok", "text/plain");
  12831. });
  12832. thread t([&]() { svr.listen(HOST, PORT); });
  12833. auto se = detail::scope_exit([&] {
  12834. svr.stop();
  12835. t.join();
  12836. });
  12837. svr.wait_until_ready();
  12838. bool verify_callback_called = false;
  12839. bool san_matched = false;
  12840. bool wrong_ipv6_matched = true;
  12841. bool cn_ipv6_matched = true;
  12842. SSLClient cli(HOST, PORT);
  12843. cli.enable_server_certificate_verification(true);
  12844. cli.set_ca_cert_path(CA_CERT_FILE);
  12845. cli.set_connection_timeout(5);
  12846. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12847. verify_callback_called = true;
  12848. if (!ctx.cert) return false;
  12849. // Matches the IPv6 iPAddress SAN.
  12850. san_matched = ctx.check_hostname("2001:db8::1");
  12851. // A different IPv6 address must not match.
  12852. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12853. // "::1" lives only in the CN, so it must not be accepted.
  12854. cn_ipv6_matched = ctx.check_hostname("::1");
  12855. return true; // Accept for the purpose of this test
  12856. });
  12857. cli.Get("/test");
  12858. ASSERT_TRUE(verify_callback_called)
  12859. << "Verify callback should have been called";
  12860. EXPECT_TRUE(san_matched)
  12861. << "verify_hostname should match an IPv6 iPAddress SAN";
  12862. EXPECT_FALSE(wrong_ipv6_matched)
  12863. << "verify_hostname should not match a non-matching IPv6 address";
  12864. EXPECT_FALSE(cn_ipv6_matched)
  12865. << "An IPv6 host must not be authenticated via the certificate CN";
  12866. }
  12867. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12868. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12869. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12870. using namespace httplib::tls;
  12871. // SANs: DNS:a.zz, IP:42.46.122.122
  12872. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12873. ASSERT_TRUE(svr.is_valid());
  12874. svr.Get("/test", [](const Request &, Response &res) {
  12875. res.set_content("ok", "text/plain");
  12876. });
  12877. auto port = svr.bind_to_any_port(HOST);
  12878. thread t([&]() { svr.listen_after_bind(); });
  12879. auto se = detail::scope_exit([&] {
  12880. svr.stop();
  12881. t.join();
  12882. });
  12883. svr.wait_until_ready();
  12884. bool verify_callback_called = false;
  12885. bool dns_san_matched = false;
  12886. bool ip_san_matched = false;
  12887. bool ip_matched_via_dns_san = true;
  12888. bool dns_matched_via_ip_san = true;
  12889. SSLClient cli(HOST, port);
  12890. cli.enable_server_certificate_verification(true);
  12891. cli.set_ca_cert_path(CA_CERT_FILE);
  12892. cli.set_connection_timeout(5);
  12893. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12894. verify_callback_called = true;
  12895. if (!ctx.cert) return false;
  12896. dns_san_matched = ctx.check_hostname("a.zz");
  12897. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12898. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12899. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12900. return true; // Accept for the purpose of this test
  12901. });
  12902. cli.Get("/test");
  12903. ASSERT_TRUE(verify_callback_called)
  12904. << "Verify callback should have been called";
  12905. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12906. EXPECT_TRUE(ip_san_matched)
  12907. << "verify_hostname should match an iPAddress SAN";
  12908. EXPECT_FALSE(ip_matched_via_dns_san)
  12909. << "An IP host must not be authenticated via a dNSName SAN";
  12910. EXPECT_FALSE(dns_matched_via_ip_san)
  12911. << "A DNS host must not be authenticated via an iPAddress SAN";
  12912. }
  12913. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12914. // "www.*.example.test" names one host and not every host under example.test.
  12915. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12916. using namespace httplib::tls;
  12917. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12918. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12919. ASSERT_TRUE(svr.is_valid());
  12920. svr.Get("/test", [](const Request &, Response &res) {
  12921. res.set_content("ok", "text/plain");
  12922. });
  12923. auto port = svr.bind_to_any_port(HOST);
  12924. thread t([&]() { svr.listen_after_bind(); });
  12925. auto se = detail::scope_exit([&] {
  12926. svr.stop();
  12927. t.join();
  12928. });
  12929. svr.wait_until_ready();
  12930. bool verify_callback_called = false;
  12931. bool leftmost_wildcard_matched = false;
  12932. bool wildcard_spanned_labels = true;
  12933. bool inner_wildcard_matched = true;
  12934. SSLClient cli(HOST, port);
  12935. cli.enable_server_certificate_verification(true);
  12936. cli.set_ca_cert_path(CA_CERT_FILE);
  12937. cli.set_connection_timeout(5);
  12938. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12939. verify_callback_called = true;
  12940. if (!ctx.cert) return false;
  12941. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12942. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12943. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12944. return true; // Accept for the purpose of this test
  12945. });
  12946. cli.Get("/test");
  12947. ASSERT_TRUE(verify_callback_called)
  12948. << "Verify callback should have been called";
  12949. EXPECT_TRUE(leftmost_wildcard_matched)
  12950. << "A leftmost wildcard should match a single label";
  12951. EXPECT_FALSE(wildcard_spanned_labels)
  12952. << "A wildcard label must not match more than one label";
  12953. EXPECT_FALSE(inner_wildcard_matched)
  12954. << "A wildcard outside the leftmost label must not be honoured";
  12955. }
  12956. // sans() must report each SAN entry under its own type.
  12957. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12958. using namespace httplib::tls;
  12959. // SANs: DNS:a.zz, IP:42.46.122.122
  12960. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12961. ASSERT_TRUE(svr.is_valid());
  12962. svr.Get("/test", [](const Request &, Response &res) {
  12963. res.set_content("ok", "text/plain");
  12964. });
  12965. auto port = svr.bind_to_any_port(HOST);
  12966. thread t([&]() { svr.listen_after_bind(); });
  12967. auto se = detail::scope_exit([&] {
  12968. svr.stop();
  12969. t.join();
  12970. });
  12971. svr.wait_until_ready();
  12972. bool verify_callback_called = false;
  12973. std::vector<SanEntry> sans;
  12974. SSLClient cli(HOST, port);
  12975. cli.enable_server_certificate_verification(true);
  12976. cli.set_ca_cert_path(CA_CERT_FILE);
  12977. cli.set_connection_timeout(5);
  12978. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12979. verify_callback_called = true;
  12980. if (!ctx.cert) return false;
  12981. sans = ctx.sans();
  12982. return true; // Accept for the purpose of this test
  12983. });
  12984. cli.Get("/test");
  12985. ASSERT_TRUE(verify_callback_called)
  12986. << "Verify callback should have been called";
  12987. auto has_san = [&](SanType type, const std::string &value) {
  12988. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12989. return san.type == type && san.value == value;
  12990. });
  12991. };
  12992. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12993. << "sans() should report the dNSName SAN";
  12994. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12995. << "sans() should report the iPAddress SAN";
  12996. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12997. << "sans() must not report the dNSName SAN as an address";
  12998. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12999. << "sans() must not report the iPAddress SAN as a DNS name";
  13000. }
  13001. #endif
  13002. // mbedTLS-specific callback constructor test
  13003. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13004. #ifdef CPPHTTPLIB_SSL_ENABLED
  13005. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13007. ASSERT_TRUE(svr.is_valid());
  13008. // Set up a handler to verify client certificate is present
  13009. bool client_cert_verified = false;
  13010. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13011. // Verify that client certificate was provided
  13012. client_cert_verified = true;
  13013. res.set_content("success", "text/plain");
  13014. });
  13015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13016. auto se = detail::scope_exit([&] {
  13017. svr.stop();
  13018. t.join();
  13019. ASSERT_FALSE(svr.is_running());
  13020. });
  13021. svr.wait_until_ready();
  13022. // Client with certificate
  13023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13024. cli.enable_server_certificate_verification(false);
  13025. cli.set_connection_timeout(30);
  13026. auto res = cli.Get("/test");
  13027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13028. ASSERT_EQ(StatusCode::OK_200, res->status);
  13029. ASSERT_TRUE(client_cert_verified);
  13030. EXPECT_EQ("success", res->body);
  13031. }
  13032. #endif
  13033. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13034. // backends
  13035. #ifdef CPPHTTPLIB_SSL_ENABLED
  13036. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13037. using namespace httplib::tls;
  13038. // Test that when client CA cert file is provided,
  13039. // the server properly requests and validates client certificates
  13040. // Create a server with client authentication
  13041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13042. ASSERT_TRUE(svr.is_valid());
  13043. bool handler_called = false;
  13044. svr.Get("/test", [&](const Request &req, Response &res) {
  13045. handler_called = true;
  13046. // Verify that a client certificate was provided
  13047. auto cert = req.peer_cert();
  13048. ASSERT_TRUE(static_cast<bool>(cert));
  13049. // Get the issuer name
  13050. std::string issuer_str = cert.issuer_name();
  13051. ASSERT_FALSE(issuer_str.empty());
  13052. // The client certificate should be issued by our test CA
  13053. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13054. res.set_content("authenticated", "text/plain");
  13055. });
  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. // Connect with a client certificate issued by the CA
  13064. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13065. cli.enable_server_certificate_verification(false);
  13066. cli.set_connection_timeout(30);
  13067. auto res = cli.Get("/test");
  13068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13069. ASSERT_EQ(StatusCode::OK_200, res->status);
  13070. ASSERT_TRUE(handler_called);
  13071. EXPECT_EQ("authenticated", res->body);
  13072. }
  13073. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13074. using namespace httplib::tls;
  13075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13076. ASSERT_TRUE(svr.is_valid());
  13077. svr.Get("/test", [](const Request &, Response &res) {
  13078. res.set_content("ok", "text/plain");
  13079. });
  13080. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13081. auto se = detail::scope_exit([&] {
  13082. svr.stop();
  13083. t.join();
  13084. });
  13085. svr.wait_until_ready();
  13086. SSLClient cli(HOST, PORT);
  13087. cli.enable_server_certificate_verification(false);
  13088. cli.set_connection_timeout(30);
  13089. bool cert_checked = false;
  13090. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13091. if (ctx.cert) {
  13092. auto sans = ctx.sans();
  13093. // Test certificate may or may not have SANs - just verify the API
  13094. // works If SANs exist, verify the types are valid
  13095. for (const auto &san : sans) {
  13096. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13097. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13098. san.type == SanType::OTHER);
  13099. EXPECT_FALSE(san.value.empty());
  13100. }
  13101. cert_checked = true;
  13102. }
  13103. return true;
  13104. });
  13105. auto res = cli.Get("/test");
  13106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13107. EXPECT_TRUE(cert_checked);
  13108. }
  13109. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13110. using namespace httplib::tls;
  13111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13112. ASSERT_TRUE(svr.is_valid());
  13113. svr.Get("/test", [](const Request &, Response &res) {
  13114. res.set_content("ok", "text/plain");
  13115. });
  13116. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13117. auto se = detail::scope_exit([&] {
  13118. svr.stop();
  13119. t.join();
  13120. });
  13121. svr.wait_until_ready();
  13122. SSLClient cli(HOST, PORT);
  13123. cli.enable_server_certificate_verification(false);
  13124. cli.set_connection_timeout(30);
  13125. bool validity_checked = false;
  13126. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13127. if (ctx.cert) {
  13128. time_t not_before = 0, not_after = 0;
  13129. bool result = ctx.validity(not_before, not_after);
  13130. EXPECT_TRUE(result);
  13131. // Verify that not_before < now < not_after for a valid cert
  13132. time_t now = time(nullptr);
  13133. EXPECT_LT(not_before, now);
  13134. EXPECT_GT(not_after, now);
  13135. validity_checked = true;
  13136. }
  13137. return true;
  13138. });
  13139. auto res = cli.Get("/test");
  13140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13141. EXPECT_TRUE(validity_checked);
  13142. }
  13143. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13144. using namespace httplib::tls;
  13145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13146. ASSERT_TRUE(svr.is_valid());
  13147. svr.Get("/test", [](const Request &, Response &res) {
  13148. res.set_content("ok", "text/plain");
  13149. });
  13150. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13151. auto se = detail::scope_exit([&] {
  13152. svr.stop();
  13153. t.join();
  13154. });
  13155. svr.wait_until_ready();
  13156. SSLClient cli(HOST, PORT);
  13157. cli.enable_server_certificate_verification(false);
  13158. cli.set_connection_timeout(30);
  13159. bool serial_checked = false;
  13160. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13161. if (ctx.cert) {
  13162. std::string serial = ctx.serial();
  13163. EXPECT_FALSE(serial.empty());
  13164. // Serial should be a hex string
  13165. for (char c : serial) {
  13166. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13167. (c >= 'a' && c <= 'f'));
  13168. }
  13169. serial_checked = true;
  13170. }
  13171. return true;
  13172. });
  13173. auto res = cli.Get("/test");
  13174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13175. EXPECT_TRUE(serial_checked);
  13176. }
  13177. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13178. // Test 1: Valid CA file - no error should be recorded
  13179. {
  13180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13181. CLIENT_CA_CERT_FILE);
  13182. ASSERT_TRUE(svr.is_valid());
  13183. // With valid setup, last_ssl_error should be 0
  13184. EXPECT_EQ(0, svr.ssl_last_error());
  13185. }
  13186. // Test 2: Invalid CA file content
  13187. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13188. {
  13189. // Create a temporary file with completely invalid content
  13190. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13191. {
  13192. std::ofstream ofs(temp_invalid_ca);
  13193. ofs << "This is not a certificate file at all\n";
  13194. ofs << "Just plain text content\n";
  13195. }
  13196. // Create server with invalid CA file
  13197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13198. // Clean up temporary file
  13199. std::remove(temp_invalid_ca);
  13200. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13201. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13202. // Note: SSL_CTX_load_verify_locations typically fails first,
  13203. // but our error handling code path is still exercised
  13204. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13205. }
  13206. }
  13207. TEST(VerifyCallbackTest, VerifyContextFields) {
  13208. using namespace httplib::tls;
  13209. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13210. ASSERT_TRUE(svr.is_valid());
  13211. svr.Get("/test", [](const Request &, Response &res) {
  13212. res.set_content("ok", "text/plain");
  13213. });
  13214. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13215. auto se = detail::scope_exit([&] {
  13216. svr.stop();
  13217. t.join();
  13218. });
  13219. svr.wait_until_ready();
  13220. SSLClient cli(HOST, PORT);
  13221. cli.enable_server_certificate_verification(false);
  13222. cli.set_connection_timeout(30);
  13223. int callback_count = 0;
  13224. bool saw_leaf_cert = false;
  13225. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13226. if (ctx.cert) {
  13227. callback_count++;
  13228. // We should see at least one certificate (the leaf)
  13229. std::string cn = ctx.subject_cn();
  13230. if (!cn.empty()) { saw_leaf_cert = true; }
  13231. // Verify context fields are populated
  13232. EXPECT_NE(ctx.session, nullptr);
  13233. EXPECT_GE(ctx.depth, 0);
  13234. }
  13235. return true;
  13236. });
  13237. auto res = cli.Get("/test");
  13238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13239. EXPECT_GT(callback_count, 0);
  13240. EXPECT_TRUE(saw_leaf_cert);
  13241. }
  13242. // A verifier belongs to the client that set it, not to the thread that set it.
  13243. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13244. using namespace httplib::tls;
  13245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13246. ASSERT_TRUE(svr.is_valid());
  13247. svr.Get("/test", [](const Request &, Response &res) {
  13248. res.set_content("ok", "text/plain");
  13249. });
  13250. auto port = svr.bind_to_any_port(HOST);
  13251. thread t([&]() { svr.listen_after_bind(); });
  13252. auto se = detail::scope_exit([&] {
  13253. svr.stop();
  13254. t.join();
  13255. });
  13256. svr.wait_until_ready();
  13257. auto rejecting_calls = 0;
  13258. SSLClient rejecting(HOST, port);
  13259. rejecting.enable_server_certificate_verification(false);
  13260. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13261. rejecting_calls++;
  13262. return false;
  13263. });
  13264. auto accepting_calls = 0;
  13265. SSLClient accepting(HOST, port);
  13266. accepting.enable_server_certificate_verification(false);
  13267. // Set on another thread than the requests below.
  13268. thread([&]() {
  13269. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13270. accepting_calls++;
  13271. return true;
  13272. });
  13273. }).join();
  13274. // Requested on another thread than the verifier was set on.
  13275. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13276. EXPECT_GT(rejecting_calls, 0);
  13277. auto res = accepting.Get("/test");
  13278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13279. EXPECT_GT(accepting_calls, 0);
  13280. }
  13281. // VerifyContext::session is the same handle the other tls:: functions take.
  13282. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13283. using namespace httplib::tls;
  13284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13285. ASSERT_TRUE(svr.is_valid());
  13286. svr.Get("/test", [](const Request &, Response &res) {
  13287. res.set_content("ok", "text/plain");
  13288. });
  13289. auto port = svr.bind_to_any_port(HOST);
  13290. thread t([&]() { svr.listen_after_bind(); });
  13291. auto se = detail::scope_exit([&] {
  13292. svr.stop();
  13293. t.join();
  13294. });
  13295. svr.wait_until_ready();
  13296. SSLClient cli(HOST, port);
  13297. cli.enable_server_certificate_verification(false);
  13298. session_t verifier_session = nullptr;
  13299. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13300. verifier_session = ctx.session;
  13301. return true;
  13302. });
  13303. session_t session_verifier_session = nullptr;
  13304. cli.set_session_verifier([&](session_t session) {
  13305. session_verifier_session = session;
  13306. return SSLVerifierResponse::NoDecisionMade;
  13307. });
  13308. auto res = cli.Get("/test");
  13309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13310. EXPECT_NE(nullptr, verifier_session);
  13311. EXPECT_EQ(session_verifier_session, verifier_session);
  13312. }
  13313. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13314. using httplib::tls::TlsError;
  13315. // Test that verify_error_to_string returns empty for success
  13316. std::string success_str = TlsError::verify_error_to_string(0);
  13317. EXPECT_TRUE(success_str.empty());
  13318. // Test that verify_error_to_string returns non-empty for error codes
  13319. // Using a common error code (certificate expired)
  13320. std::string error_str =
  13321. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13322. EXPECT_FALSE(error_str.empty());
  13323. }
  13324. TEST(SessionVerifierTest, CertificateAccepted) {
  13325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13326. ASSERT_TRUE(svr.is_valid());
  13327. svr.Get("/test", [](const Request &, Response &res) {
  13328. res.set_content("ok", "text/plain");
  13329. });
  13330. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13331. auto se = detail::scope_exit([&] {
  13332. svr.stop();
  13333. t.join();
  13334. });
  13335. svr.wait_until_ready();
  13336. SSLClient cli(HOST, PORT);
  13337. cli.enable_server_certificate_verification(false);
  13338. cli.set_connection_timeout(30);
  13339. bool callback_called = false;
  13340. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13341. EXPECT_NE(session, nullptr);
  13342. callback_called = true;
  13343. return SSLVerifierResponse::CertificateAccepted;
  13344. });
  13345. auto res = cli.Get("/test");
  13346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13347. EXPECT_EQ(200, res->status);
  13348. EXPECT_TRUE(callback_called);
  13349. }
  13350. TEST(SessionVerifierTest, CertificateRejected) {
  13351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13352. ASSERT_TRUE(svr.is_valid());
  13353. svr.Get("/test", [](const Request &, Response &res) {
  13354. res.set_content("ok", "text/plain");
  13355. });
  13356. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13357. auto se = detail::scope_exit([&] {
  13358. svr.stop();
  13359. t.join();
  13360. });
  13361. svr.wait_until_ready();
  13362. SSLClient cli(HOST, PORT);
  13363. cli.enable_server_certificate_verification(false);
  13364. cli.set_connection_timeout(30);
  13365. bool callback_called = false;
  13366. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13367. EXPECT_NE(session, nullptr);
  13368. callback_called = true;
  13369. return SSLVerifierResponse::CertificateRejected;
  13370. });
  13371. auto res = cli.Get("/test");
  13372. EXPECT_FALSE(res);
  13373. EXPECT_TRUE(callback_called);
  13374. }
  13375. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13377. ASSERT_TRUE(svr.is_valid());
  13378. svr.Get("/test", [](const Request &, Response &res) {
  13379. res.set_content("ok", "text/plain");
  13380. });
  13381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13382. auto se = detail::scope_exit([&] {
  13383. svr.stop();
  13384. t.join();
  13385. });
  13386. svr.wait_until_ready();
  13387. // NoDecisionMade with verification disabled should succeed (no default check)
  13388. SSLClient cli(HOST, PORT);
  13389. cli.enable_server_certificate_verification(false);
  13390. cli.set_connection_timeout(30);
  13391. bool callback_called = false;
  13392. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13393. EXPECT_NE(session, nullptr);
  13394. callback_called = true;
  13395. return SSLVerifierResponse::NoDecisionMade;
  13396. });
  13397. auto res = cli.Get("/test");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. EXPECT_EQ(200, res->status);
  13400. EXPECT_TRUE(callback_called);
  13401. }
  13402. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13403. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13404. ASSERT_TRUE(svr.is_valid());
  13405. svr.Get("/test", [](const Request &, Response &res) {
  13406. res.set_content("ok", "text/plain");
  13407. });
  13408. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13409. auto se = detail::scope_exit([&] {
  13410. svr.stop();
  13411. t.join();
  13412. });
  13413. svr.wait_until_ready();
  13414. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13415. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13416. // so we only check that the request fails, not whether the callback was
  13417. // called.
  13418. SSLClient cli(HOST, PORT);
  13419. cli.enable_server_certificate_verification(true);
  13420. cli.set_connection_timeout(30);
  13421. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13422. EXPECT_NE(session, nullptr);
  13423. return SSLVerifierResponse::NoDecisionMade;
  13424. });
  13425. auto res = cli.Get("/test");
  13426. EXPECT_FALSE(res);
  13427. }
  13428. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13429. // Test SSL server using PemMemory constructor with client CA certificates
  13430. // Read PEM files
  13431. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13432. read_file(SERVER_CERT_FILE, server_cert_pem);
  13433. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13434. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13435. // Create SSLServer with PemMemory constructor including client CA
  13436. SSLServer::PemMemory server_pem = {
  13437. server_cert_pem.c_str(),
  13438. server_cert_pem.size(),
  13439. server_key_pem.c_str(),
  13440. server_key_pem.size(),
  13441. client_ca_pem.c_str(),
  13442. client_ca_pem.size(),
  13443. nullptr // no password for server key
  13444. };
  13445. SSLServer svr(server_pem);
  13446. ASSERT_TRUE(svr.is_valid());
  13447. // No SSL error should be recorded for valid setup
  13448. EXPECT_EQ(0, svr.ssl_last_error());
  13449. // Set up server endpoints
  13450. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13451. res.set_content("ok", "text/plain");
  13452. });
  13453. // Start server in a thread
  13454. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13455. svr.wait_until_ready();
  13456. // Connect with client certificate (using constructor with paths)
  13457. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13458. cli.enable_server_certificate_verification(false);
  13459. auto res = cli.Get("/test-pem-ca");
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. EXPECT_EQ(200, res->status);
  13462. EXPECT_EQ("ok", res->body);
  13463. svr.stop();
  13464. server_thread.join();
  13465. }
  13466. #endif
  13467. #ifdef _WIN32
  13468. TEST(CleanupTest, WSACleanup) {
  13469. int ret = WSACleanup();
  13470. ASSERT_EQ(0, ret);
  13471. }
  13472. #endif
  13473. #ifndef CPPHTTPLIB_SSL_ENABLED
  13474. TEST(NoSSLSupport, SimpleInterface) {
  13475. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13476. }
  13477. #endif
  13478. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13479. TEST(InvalidScheme, SimpleInterface) {
  13480. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13481. }
  13482. #endif
  13483. TEST(NoScheme, SimpleInterface) {
  13484. Client cli("yahoo.com:80");
  13485. ASSERT_TRUE(cli.is_valid());
  13486. }
  13487. TEST(SendAPI, SimpleInterface_Online) {
  13488. Client cli("http://yahoo.com");
  13489. Request req;
  13490. req.method = "GET";
  13491. req.path = "/";
  13492. auto res = cli.send(req);
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13495. }
  13496. TEST(SendAPI, WithParamsInRequest) {
  13497. Server svr;
  13498. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13499. EXPECT_TRUE(req.has_param("test"));
  13500. EXPECT_EQ("test_value", req.get_param_value("test"));
  13501. });
  13502. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13503. auto se = detail::scope_exit([&] {
  13504. svr.stop();
  13505. t.join();
  13506. ASSERT_FALSE(svr.is_running());
  13507. });
  13508. svr.wait_until_ready();
  13509. Client cli(HOST, PORT);
  13510. {
  13511. Request req;
  13512. req.method = "GET";
  13513. req.path = "/";
  13514. req.params.emplace("test", "test_value");
  13515. auto res = cli.send(req);
  13516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13517. }
  13518. {
  13519. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13521. }
  13522. }
  13523. TEST(ClientImplMethods, GetSocketTest) {
  13524. httplib::Server svr;
  13525. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13526. res.status = StatusCode::OK_200;
  13527. });
  13528. auto port = svr.bind_to_any_port("127.0.0.1");
  13529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13530. auto se = detail::scope_exit([&] {
  13531. svr.stop();
  13532. thread.join();
  13533. ASSERT_FALSE(svr.is_running());
  13534. });
  13535. svr.wait_until_ready();
  13536. {
  13537. httplib::Client cli("127.0.0.1", port);
  13538. cli.set_keep_alive(true);
  13539. // Use the behavior of cpp-httplib of opening the connection
  13540. // only when the first request happens. If that changes,
  13541. // this test would be obsolete.
  13542. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13543. // This also implicitly tests the server. But other tests would fail much
  13544. // earlier than this one to be considered.
  13545. auto res = cli.Get("/");
  13546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13547. EXPECT_EQ(StatusCode::OK_200, res->status);
  13548. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13549. }
  13550. }
  13551. #ifdef CPPHTTPLIB_SSL_ENABLED
  13552. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13553. Client cli("http://yahoo.com");
  13554. auto res = cli.Get("/");
  13555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13556. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13557. cli.set_follow_location(true);
  13558. res = cli.Get("/");
  13559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13560. EXPECT_EQ(StatusCode::OK_200, res->status);
  13561. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13562. }
  13563. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13564. Client cli("https://yahoo.com");
  13565. auto res = cli.Get("/");
  13566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13567. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13568. cli.set_follow_location(true);
  13569. res = cli.Get("/");
  13570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13571. EXPECT_EQ(StatusCode::OK_200, res->status);
  13572. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13573. }
  13574. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13575. Client cli("https://yahoo.com");
  13576. auto res = cli.Get("/");
  13577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13578. ASSERT_FALSE(!res);
  13579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13580. ASSERT_FALSE(res == nullptr);
  13581. ASSERT_TRUE(res != nullptr);
  13582. EXPECT_EQ(Error::Success, res.error());
  13583. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13584. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13585. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13586. cli.set_follow_location(true);
  13587. res = cli.Get("/");
  13588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13589. EXPECT_EQ(Error::Success, res.error());
  13590. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13591. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13592. EXPECT_EQ(StatusCode::OK_200, res->status);
  13593. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13594. }
  13595. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13596. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13597. Client cli("https://cdnjs.cloudflare.com");
  13598. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13599. Headers{{"Accept-Encoding", "br"}});
  13600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13601. EXPECT_EQ(StatusCode::OK_200, res->status);
  13602. EXPECT_EQ(287630U, res->body.size());
  13603. EXPECT_EQ("application/javascript; charset=utf-8",
  13604. res->get_header_value("Content-Type"));
  13605. }
  13606. #endif
  13607. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13608. #undef REDIR_HOST // Silence compiler warning
  13609. #define REDIR_HOST "https://httpbingo.org"
  13610. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13611. Client cli(REDIR_HOST);
  13612. cli.set_follow_location(true);
  13613. auto res =
  13614. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13616. EXPECT_EQ(StatusCode::OK_200, res->status);
  13617. }
  13618. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13619. Client cli(REDIR_HOST);
  13620. cli.set_follow_location(true);
  13621. Params params;
  13622. params.emplace("url", "http://example.com");
  13623. params.emplace("status_code", "302");
  13624. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13626. EXPECT_EQ(StatusCode::OK_200, res->status);
  13627. }
  13628. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13629. Client cli(REDIR_HOST);
  13630. cli.set_follow_location(true);
  13631. Params params;
  13632. params.emplace("url", "http://example.com");
  13633. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13635. EXPECT_EQ(StatusCode::OK_200, res->status);
  13636. }
  13637. TEST(HttpToHttpsRedirectTest, CertFile) {
  13638. auto ssl_port = PORT + 1;
  13639. Server svr;
  13640. ASSERT_TRUE(svr.is_valid());
  13641. svr.Get("/index", [&](const Request &, Response &res) {
  13642. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13643. "/index");
  13644. svr.stop();
  13645. });
  13646. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13647. ASSERT_TRUE(ssl_svr.is_valid());
  13648. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13649. res.set_content("test", "text/plain");
  13650. ssl_svr.stop();
  13651. });
  13652. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13653. thread t2 =
  13654. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13655. auto se = detail::scope_exit([&] {
  13656. t2.join();
  13657. t.join();
  13658. ASSERT_FALSE(svr.is_running());
  13659. });
  13660. svr.wait_until_ready();
  13661. ssl_svr.wait_until_ready();
  13662. Client cli("127.0.0.1", PORT);
  13663. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13664. cli.enable_server_certificate_verification(true);
  13665. cli.set_follow_location(true);
  13666. cli.set_connection_timeout(30);
  13667. auto res = cli.Get("/index");
  13668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13669. ASSERT_EQ(StatusCode::OK_200, res->status);
  13670. }
  13671. TEST(SSLClientRedirectTest, CertFile) {
  13672. auto ssl_port = PORT + 1;
  13673. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13674. ASSERT_TRUE(ssl_svr1.is_valid());
  13675. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13676. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13677. "/index");
  13678. ssl_svr1.stop();
  13679. });
  13680. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13681. ASSERT_TRUE(ssl_svr2.is_valid());
  13682. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13683. res.set_content("test", "text/plain");
  13684. ssl_svr2.stop();
  13685. });
  13686. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13687. thread t2 =
  13688. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13689. auto se = detail::scope_exit([&] {
  13690. t2.join();
  13691. t.join();
  13692. ASSERT_FALSE(ssl_svr1.is_running());
  13693. });
  13694. ssl_svr1.wait_until_ready();
  13695. ssl_svr2.wait_until_ready();
  13696. SSLClient cli("127.0.0.1", PORT);
  13697. std::string cert;
  13698. read_file(SERVER_CERT2_FILE, cert);
  13699. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13700. cli.enable_server_certificate_verification(true);
  13701. cli.set_follow_location(true);
  13702. cli.set_connection_timeout(30);
  13703. auto res = cli.Get("/index");
  13704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13705. ASSERT_EQ(StatusCode::OK_200, res->status);
  13706. }
  13707. #endif
  13708. #ifdef CPPHTTPLIB_SSL_ENABLED
  13709. // Test that set_ca_cert_store() skips system certs (consistent with
  13710. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13711. // should be trusted - system certs should NOT be loaded.
  13712. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13713. // Load a specific cert that is NOT a system CA cert
  13714. std::string cert;
  13715. read_file(SERVER_CERT2_FILE, cert);
  13716. SSLClient cli("google.com");
  13717. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13718. cli.enable_server_certificate_verification(true);
  13719. // This should FAIL because:
  13720. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13721. // 2. System certs should NOT be loaded when custom store is set
  13722. // If system certs WERE loaded, this would succeed
  13723. auto res = cli.Get("/");
  13724. ASSERT_FALSE(res);
  13725. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13726. }
  13727. // Same as above, but through the native store handle path. Regression test:
  13728. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13729. // merged system certs into the user-provided store.
  13730. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13731. std::string cert;
  13732. read_file(SERVER_CERT2_FILE, cert);
  13733. SSLClient cli("google.com");
  13734. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13735. cli.enable_server_certificate_verification(true);
  13736. auto res = cli.Get("/");
  13737. ASSERT_FALSE(res);
  13738. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13739. }
  13740. // A custom store set via the native handle must still verify a server whose
  13741. // cert it does contain.
  13742. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13743. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13744. ASSERT_TRUE(svr.is_valid());
  13745. svr.Get("/test", [&](const Request &, Response &res) {
  13746. res.set_content("test", "text/plain");
  13747. });
  13748. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13749. auto se = detail::scope_exit([&] {
  13750. svr.stop();
  13751. t.join();
  13752. ASSERT_FALSE(svr.is_running());
  13753. });
  13754. svr.wait_until_ready();
  13755. SSLClient cli("127.0.0.1", PORT);
  13756. std::string cert;
  13757. read_file(SERVER_CERT2_FILE, cert);
  13758. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13759. cli.enable_server_certificate_verification(true);
  13760. cli.set_connection_timeout(30);
  13761. auto res = cli.Get("/test");
  13762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13763. ASSERT_EQ(StatusCode::OK_200, res->status);
  13764. }
  13765. // CA certs loaded through the universal Client must be transferred to the
  13766. // client created internally for following an HTTPS redirect. Regression test:
  13767. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13768. // the CA data for redirect transfer.
  13769. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13770. auto ssl_port = PORT + 1;
  13771. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13772. ASSERT_TRUE(ssl_svr1.is_valid());
  13773. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13774. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13775. "/index");
  13776. });
  13777. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13778. ASSERT_TRUE(ssl_svr2.is_valid());
  13779. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13780. res.set_content("test", "text/plain");
  13781. });
  13782. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13783. thread t2 =
  13784. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13785. auto se = detail::scope_exit([&] {
  13786. ssl_svr2.stop();
  13787. ssl_svr1.stop();
  13788. t2.join();
  13789. t.join();
  13790. ASSERT_FALSE(ssl_svr1.is_running());
  13791. });
  13792. ssl_svr1.wait_until_ready();
  13793. ssl_svr2.wait_until_ready();
  13794. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13795. std::string cert;
  13796. read_file(SERVER_CERT2_FILE, cert);
  13797. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13798. cli.enable_server_certificate_verification(true);
  13799. cli.set_follow_location(true);
  13800. cli.set_connection_timeout(30);
  13801. auto res = cli.Get("/index");
  13802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13803. ASSERT_EQ(StatusCode::OK_200, res->status);
  13804. }
  13805. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13806. // so a host signed by a system CA verifies even though a custom CA is set
  13807. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13808. std::string cert;
  13809. read_file(SERVER_CERT2_FILE, cert);
  13810. SSLClient cli("google.com");
  13811. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13812. cli.enable_system_ca(true);
  13813. cli.enable_server_certificate_verification(true);
  13814. auto res = cli.Get("/");
  13815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13816. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13817. }
  13818. // The custom CA remains effective when combined with the system CA
  13819. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13820. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13821. ASSERT_TRUE(svr.is_valid());
  13822. svr.Get("/test", [&](const Request &, Response &res) {
  13823. res.set_content("test", "text/plain");
  13824. });
  13825. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13826. auto se = detail::scope_exit([&] {
  13827. svr.stop();
  13828. t.join();
  13829. ASSERT_FALSE(svr.is_running());
  13830. });
  13831. svr.wait_until_ready();
  13832. SSLClient cli("127.0.0.1", PORT);
  13833. std::string cert;
  13834. read_file(SERVER_CERT2_FILE, cert);
  13835. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13836. cli.enable_system_ca(true);
  13837. cli.enable_server_certificate_verification(true);
  13838. cli.set_connection_timeout(30);
  13839. auto res = cli.Get("/test");
  13840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13841. ASSERT_EQ(StatusCode::OK_200, res->status);
  13842. }
  13843. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13844. // skip chain verification entirely (only the certificate identity was
  13845. // checked), so a server presenting an untrusted certificate with a matching
  13846. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13847. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13848. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13849. ASSERT_TRUE(svr.is_valid());
  13850. svr.Get("/test", [&](const Request &, Response &res) {
  13851. res.set_content("test", "text/plain");
  13852. });
  13853. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13854. auto se = detail::scope_exit([&] {
  13855. svr.stop();
  13856. t.join();
  13857. ASSERT_FALSE(svr.is_running());
  13858. });
  13859. svr.wait_until_ready();
  13860. SSLClient cli("127.0.0.1", PORT);
  13861. std::string cert;
  13862. // A trusted CA that did not sign the server certificate. The server cert
  13863. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13864. // this connection.
  13865. read_file(CLIENT_CA_CERT_FILE, cert);
  13866. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13867. cli.enable_server_certificate_verification(true);
  13868. cli.set_connection_timeout(30);
  13869. auto res = cli.Get("/test");
  13870. ASSERT_FALSE(res);
  13871. }
  13872. // enable_system_ca(false) prevents system CA loading entirely
  13873. TEST(SSLClientTest, DisableSystemCa_Online) {
  13874. SSLClient cli("google.com");
  13875. cli.enable_system_ca(false);
  13876. cli.enable_server_certificate_verification(true);
  13877. auto res = cli.Get("/");
  13878. ASSERT_FALSE(res);
  13879. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13880. // itself when the CA chain is empty
  13881. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13882. res.error() == Error::SSLConnection);
  13883. }
  13884. // The universal Client forwards enable_system_ca()
  13885. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13886. std::string cert;
  13887. read_file(SERVER_CERT2_FILE, cert);
  13888. Client cli("https://google.com");
  13889. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13890. cli.enable_system_ca(true);
  13891. cli.enable_server_certificate_verification(true);
  13892. auto res = cli.Get("/");
  13893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13894. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13895. }
  13896. // The system CA policy must carry over to the client created internally for
  13897. // following a cross-host HTTPS redirect
  13898. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13899. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13900. ASSERT_TRUE(svr.is_valid());
  13901. svr.Get("/index", [&](const Request &, Response &res) {
  13902. res.set_redirect("https://www.google.com/");
  13903. });
  13904. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13905. auto se = detail::scope_exit([&] {
  13906. svr.stop();
  13907. t.join();
  13908. ASSERT_FALSE(svr.is_running());
  13909. });
  13910. svr.wait_until_ready();
  13911. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13912. std::string cert;
  13913. read_file(SERVER_CERT2_FILE, cert);
  13914. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13915. cli.enable_system_ca(true);
  13916. cli.enable_server_certificate_verification(true);
  13917. cli.set_follow_location(true);
  13918. cli.set_connection_timeout(30);
  13919. // Receiving any response proves the redirect client completed the TLS
  13920. // handshake with a system-CA-signed host
  13921. auto res = cli.Get("/index");
  13922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13923. }
  13924. TEST(MultipartFormDataTest, LargeData) {
  13925. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13926. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13927. const ContentReader &content_reader) {
  13928. if (req.is_multipart_form_data()) {
  13929. std::vector<FormData> items;
  13930. content_reader(
  13931. [&](const FormData &file) {
  13932. items.push_back(file);
  13933. return true;
  13934. },
  13935. [&](const char *data, size_t data_length) {
  13936. items.back().content.append(data, data_length);
  13937. return true;
  13938. });
  13939. EXPECT_TRUE(std::string(items[0].name) == "document");
  13940. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13941. EXPECT_TRUE(items[0].filename == "2MB_data");
  13942. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13943. EXPECT_TRUE(items[1].name == "hello");
  13944. EXPECT_TRUE(items[1].content == "world");
  13945. EXPECT_TRUE(items[1].filename == "");
  13946. EXPECT_TRUE(items[1].content_type == "");
  13947. } else {
  13948. std::string body;
  13949. content_reader([&](const char *data, size_t data_length) {
  13950. body.append(data, data_length);
  13951. return true;
  13952. });
  13953. }
  13954. });
  13955. auto port = svr.bind_to_any_port(HOST);
  13956. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13957. auto se = detail::scope_exit([&] {
  13958. svr.stop();
  13959. t.join();
  13960. ASSERT_FALSE(svr.is_running());
  13961. });
  13962. svr.wait_until_ready();
  13963. {
  13964. std::string data(1024 * 1024 * 2, '.');
  13965. std::stringstream buffer;
  13966. buffer << data;
  13967. SSLClient cli(HOST, port);
  13968. cli.enable_server_certificate_verification(false);
  13969. UploadFormDataItems items{
  13970. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13971. {"hello", "world", "", ""},
  13972. };
  13973. auto res = cli.Post("/post", items);
  13974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13975. ASSERT_EQ(StatusCode::OK_200, res->status);
  13976. }
  13977. }
  13978. TEST(MultipartFormDataTest, DataProviderItems) {
  13979. std::random_device seed_gen;
  13980. std::mt19937 random(seed_gen());
  13981. std::string rand1;
  13982. rand1.resize(1000);
  13983. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13984. std::string rand2;
  13985. rand2.resize(3000);
  13986. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13988. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13989. const ContentReader &content_reader) {
  13990. ASSERT_FALSE(req.is_multipart_form_data());
  13991. std::string body;
  13992. content_reader([&](const char *data, size_t data_length) {
  13993. body.append(data, data_length);
  13994. return true;
  13995. });
  13996. EXPECT_EQ(body, "");
  13997. });
  13998. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13999. const ContentReader &content_reader) {
  14000. ASSERT_TRUE(req.is_multipart_form_data());
  14001. std::vector<FormData> items;
  14002. content_reader(
  14003. [&](const FormData &file) {
  14004. items.push_back(file);
  14005. return true;
  14006. },
  14007. [&](const char *data, size_t data_length) {
  14008. items.back().content.append(data, data_length);
  14009. return true;
  14010. });
  14011. ASSERT_TRUE(items.size() == 2);
  14012. EXPECT_EQ(std::string(items[0].name), "name1");
  14013. EXPECT_EQ(items[0].content, "Testing123");
  14014. EXPECT_EQ(items[0].filename, "filename1");
  14015. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14016. EXPECT_EQ(items[1].name, "name2");
  14017. EXPECT_EQ(items[1].content, "Testing456");
  14018. EXPECT_EQ(items[1].filename, "");
  14019. EXPECT_EQ(items[1].content_type, "");
  14020. });
  14021. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14022. const ContentReader &content_reader) {
  14023. ASSERT_TRUE(req.is_multipart_form_data());
  14024. std::vector<FormData> items;
  14025. content_reader(
  14026. [&](const FormData &file) {
  14027. items.push_back(file);
  14028. return true;
  14029. },
  14030. [&](const char *data, size_t data_length) {
  14031. items.back().content.append(data, data_length);
  14032. return true;
  14033. });
  14034. ASSERT_TRUE(items.size() == 2);
  14035. EXPECT_EQ(items[0].name, "name3");
  14036. EXPECT_EQ(items[0].content, rand1);
  14037. EXPECT_EQ(items[0].filename, "filename3");
  14038. EXPECT_EQ(items[0].content_type, "");
  14039. EXPECT_EQ(items[1].name, "name4");
  14040. EXPECT_EQ(items[1].content, rand2);
  14041. EXPECT_EQ(items[1].filename, "filename4");
  14042. EXPECT_EQ(items[1].content_type, "");
  14043. });
  14044. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14045. const ContentReader &content_reader) {
  14046. ASSERT_TRUE(req.is_multipart_form_data());
  14047. std::vector<FormData> items;
  14048. content_reader(
  14049. [&](const FormData &file) {
  14050. items.push_back(file);
  14051. return true;
  14052. },
  14053. [&](const char *data, size_t data_length) {
  14054. items.back().content.append(data, data_length);
  14055. return true;
  14056. });
  14057. ASSERT_TRUE(items.size() == 4);
  14058. EXPECT_EQ(std::string(items[0].name), "name1");
  14059. EXPECT_EQ(items[0].content, "Testing123");
  14060. EXPECT_EQ(items[0].filename, "filename1");
  14061. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14062. EXPECT_EQ(items[1].name, "name2");
  14063. EXPECT_EQ(items[1].content, "Testing456");
  14064. EXPECT_EQ(items[1].filename, "");
  14065. EXPECT_EQ(items[1].content_type, "");
  14066. EXPECT_EQ(items[2].name, "name3");
  14067. EXPECT_EQ(items[2].content, rand1);
  14068. EXPECT_EQ(items[2].filename, "filename3");
  14069. EXPECT_EQ(items[2].content_type, "");
  14070. EXPECT_EQ(items[3].name, "name4");
  14071. EXPECT_EQ(items[3].content, rand2);
  14072. EXPECT_EQ(items[3].filename, "filename4");
  14073. EXPECT_EQ(items[3].content_type, "");
  14074. });
  14075. auto port = svr.bind_to_any_port("localhost");
  14076. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14077. auto se = detail::scope_exit([&] {
  14078. svr.stop();
  14079. t.join();
  14080. ASSERT_FALSE(svr.is_running());
  14081. });
  14082. svr.wait_until_ready();
  14083. {
  14084. SSLClient cli("localhost", port);
  14085. cli.enable_server_certificate_verification(false);
  14086. UploadFormDataItems items{
  14087. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14088. {"name2", "Testing456", "", ""}, // not a file
  14089. };
  14090. {
  14091. auto res = cli.Post("/post-none", {}, {}, {});
  14092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14093. ASSERT_EQ(StatusCode::OK_200, res->status);
  14094. }
  14095. FormDataProviderItems providers;
  14096. {
  14097. auto res =
  14098. cli.Post("/post-items", {}, items, providers); // empty providers
  14099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14100. ASSERT_EQ(StatusCode::OK_200, res->status);
  14101. }
  14102. providers.push_back({"name3",
  14103. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14104. // test the offset is given correctly at each step
  14105. if (!offset)
  14106. sink.os.write(rand1.data(), 30);
  14107. else if (offset == 30)
  14108. sink.os.write(rand1.data() + 30, 300);
  14109. else if (offset == 330)
  14110. sink.os.write(rand1.data() + 330, 670);
  14111. else if (offset == rand1.size())
  14112. sink.done();
  14113. return true;
  14114. },
  14115. "filename3",
  14116. {}});
  14117. providers.push_back({"name4",
  14118. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14119. // test the offset is given correctly at each step
  14120. if (!offset)
  14121. sink.os.write(rand2.data(), 2000);
  14122. else if (offset == 2000)
  14123. sink.os.write(rand2.data() + 2000, 1);
  14124. else if (offset == 2001)
  14125. sink.os.write(rand2.data() + 2001, 999);
  14126. else if (offset == rand2.size())
  14127. sink.done();
  14128. return true;
  14129. },
  14130. "filename4",
  14131. {}});
  14132. {
  14133. auto res = cli.Post("/post-providers", {}, {}, providers);
  14134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14135. ASSERT_EQ(StatusCode::OK_200, res->status);
  14136. }
  14137. {
  14138. auto res = cli.Post("/post-both", {}, items, providers);
  14139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14140. ASSERT_EQ(StatusCode::OK_200, res->status);
  14141. }
  14142. }
  14143. }
  14144. TEST(MultipartFormDataTest, BadHeader) {
  14145. Server svr;
  14146. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14147. res.set_content("ok", "text/plain");
  14148. });
  14149. thread t = thread([&] { svr.listen(HOST, PORT); });
  14150. auto se = detail::scope_exit([&] {
  14151. svr.stop();
  14152. t.join();
  14153. ASSERT_FALSE(svr.is_running());
  14154. });
  14155. svr.wait_until_ready();
  14156. const std::string body =
  14157. "This is the preamble. It is to be ignored, though it\r\n"
  14158. "is a handy place for composition agents to include an\r\n"
  14159. "explanatory note to non-MIME conformant readers.\r\n"
  14160. "\r\n"
  14161. "\r\n"
  14162. "--simple boundary\r\n"
  14163. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14164. ": BAD...\r\n"
  14165. "\r\n"
  14166. "value1\r\n"
  14167. "--simple boundary\r\n"
  14168. "Content-Disposition: form-data; name=\"field2\"; "
  14169. "filename=\"example.txt\"\r\n"
  14170. "\r\n"
  14171. "value2\r\n"
  14172. "--simple boundary--\r\n"
  14173. "This is the epilogue. It is also to be ignored.\r\n";
  14174. std::string content_type =
  14175. R"(multipart/form-data; boundary="simple boundary")";
  14176. Client cli(HOST, PORT);
  14177. auto res = cli.Post("/post", body, content_type.c_str());
  14178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14179. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14180. }
  14181. TEST(MultipartFormDataTest, WithPreamble) {
  14182. Server svr;
  14183. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14184. res.set_content("ok", "text/plain");
  14185. });
  14186. thread t = thread([&] { svr.listen(HOST, PORT); });
  14187. auto se = detail::scope_exit([&] {
  14188. svr.stop();
  14189. t.join();
  14190. ASSERT_FALSE(svr.is_running());
  14191. });
  14192. svr.wait_until_ready();
  14193. const std::string body =
  14194. "This is the preamble. It is to be ignored, though it\r\n"
  14195. "is a handy place for composition agents to include an\r\n"
  14196. "explanatory note to non-MIME conformant readers.\r\n"
  14197. "\r\n"
  14198. "\r\n"
  14199. "--simple boundary\r\n"
  14200. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14201. "\r\n"
  14202. "value1\r\n"
  14203. "--simple boundary\r\n"
  14204. "Content-Disposition: form-data; name=\"field2\"; "
  14205. "filename=\"example.txt\"\r\n"
  14206. "\r\n"
  14207. "value2\r\n"
  14208. "--simple boundary--\r\n"
  14209. "This is the epilogue. It is also to be ignored.\r\n";
  14210. std::string content_type =
  14211. R"(multipart/form-data; boundary="simple boundary")";
  14212. Client cli(HOST, PORT);
  14213. auto res = cli.Post("/post", body, content_type.c_str());
  14214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14215. EXPECT_EQ(StatusCode::OK_200, res->status);
  14216. }
  14217. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14219. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14220. const ContentReader &content_reader) {
  14221. if (req.is_multipart_form_data()) {
  14222. std::vector<FormData> items;
  14223. content_reader(
  14224. [&](const FormData &file) {
  14225. items.push_back(file);
  14226. return true;
  14227. },
  14228. [&](const char *data, size_t data_length) {
  14229. items.back().content.append(data, data_length);
  14230. return true;
  14231. });
  14232. EXPECT_TRUE(std::string(items[0].name) == "document");
  14233. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14234. EXPECT_TRUE(items[0].filename == "2MB_data");
  14235. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14236. EXPECT_TRUE(items[1].name == "hello");
  14237. EXPECT_TRUE(items[1].content == "world");
  14238. EXPECT_TRUE(items[1].filename == "");
  14239. EXPECT_TRUE(items[1].content_type == "");
  14240. } else {
  14241. std::string body;
  14242. content_reader([&](const char *data, size_t data_length) {
  14243. body.append(data, data_length);
  14244. return true;
  14245. });
  14246. }
  14247. });
  14248. auto port = svr.bind_to_any_port("localhost");
  14249. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop();
  14252. t.join();
  14253. ASSERT_FALSE(svr.is_running());
  14254. });
  14255. svr.wait_until_ready();
  14256. {
  14257. std::string data(1024 * 1024 * 2, '.');
  14258. std::stringstream buffer;
  14259. buffer << data;
  14260. SSLClient cli("localhost", port);
  14261. cli.enable_server_certificate_verification(false);
  14262. UploadFormDataItems items{
  14263. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14264. {"hello", "world", "", ""},
  14265. };
  14266. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14268. ASSERT_EQ(StatusCode::OK_200, res->status);
  14269. }
  14270. }
  14271. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14272. std::string data(1024 * 1024 * 2, '&');
  14273. std::stringstream buffer;
  14274. buffer << data;
  14275. Client cli("https://localhost:8080");
  14276. UploadFormDataItems items{
  14277. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14278. {"hello", "world", "", ""},
  14279. };
  14280. for (const char &c : " \t\r\n") {
  14281. auto res =
  14282. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14283. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14284. ASSERT_FALSE(res);
  14285. }
  14286. }
  14287. TEST(MultipartFormDataTest, PutFormData) {
  14288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14289. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14290. const ContentReader &content_reader) {
  14291. if (req.is_multipart_form_data()) {
  14292. std::vector<FormData> items;
  14293. content_reader(
  14294. [&](const FormData &file) {
  14295. items.push_back(file);
  14296. return true;
  14297. },
  14298. [&](const char *data, size_t data_length) {
  14299. items.back().content.append(data, data_length);
  14300. return true;
  14301. });
  14302. EXPECT_TRUE(std::string(items[0].name) == "document");
  14303. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14304. EXPECT_TRUE(items[0].filename == "2MB_data");
  14305. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14306. EXPECT_TRUE(items[1].name == "hello");
  14307. EXPECT_TRUE(items[1].content == "world");
  14308. EXPECT_TRUE(items[1].filename == "");
  14309. EXPECT_TRUE(items[1].content_type == "");
  14310. } else {
  14311. std::string body;
  14312. content_reader([&](const char *data, size_t data_length) {
  14313. body.append(data, data_length);
  14314. return true;
  14315. });
  14316. }
  14317. });
  14318. auto port = svr.bind_to_any_port("localhost");
  14319. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14320. auto se = detail::scope_exit([&] {
  14321. svr.stop();
  14322. t.join();
  14323. ASSERT_FALSE(svr.is_running());
  14324. });
  14325. svr.wait_until_ready();
  14326. {
  14327. std::string data(1024 * 1024 * 2, '&');
  14328. std::stringstream buffer;
  14329. buffer << data;
  14330. SSLClient cli("localhost", port);
  14331. cli.enable_server_certificate_verification(false);
  14332. UploadFormDataItems items{
  14333. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14334. {"hello", "world", "", ""},
  14335. };
  14336. auto res = cli.Put("/put", items);
  14337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14338. ASSERT_EQ(StatusCode::OK_200, res->status);
  14339. }
  14340. }
  14341. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14343. svr.Put("/put_customboundary",
  14344. [&](const Request &req, const Response & /*res*/,
  14345. const ContentReader &content_reader) {
  14346. if (req.is_multipart_form_data()) {
  14347. std::vector<FormData> items;
  14348. content_reader(
  14349. [&](const FormData &file) {
  14350. items.push_back(file);
  14351. return true;
  14352. },
  14353. [&](const char *data, size_t data_length) {
  14354. items.back().content.append(data, data_length);
  14355. return true;
  14356. });
  14357. EXPECT_TRUE(std::string(items[0].name) == "document");
  14358. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14359. EXPECT_TRUE(items[0].filename == "2MB_data");
  14360. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14361. EXPECT_TRUE(items[1].name == "hello");
  14362. EXPECT_TRUE(items[1].content == "world");
  14363. EXPECT_TRUE(items[1].filename == "");
  14364. EXPECT_TRUE(items[1].content_type == "");
  14365. } else {
  14366. std::string body;
  14367. content_reader([&](const char *data, size_t data_length) {
  14368. body.append(data, data_length);
  14369. return true;
  14370. });
  14371. }
  14372. });
  14373. auto port = svr.bind_to_any_port("localhost");
  14374. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14375. auto se = detail::scope_exit([&] {
  14376. svr.stop();
  14377. t.join();
  14378. ASSERT_FALSE(svr.is_running());
  14379. });
  14380. svr.wait_until_ready();
  14381. {
  14382. std::string data(1024 * 1024 * 2, '&');
  14383. std::stringstream buffer;
  14384. buffer << data;
  14385. SSLClient cli("localhost", port);
  14386. cli.enable_server_certificate_verification(false);
  14387. UploadFormDataItems items{
  14388. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14389. {"hello", "world", "", ""},
  14390. };
  14391. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14393. ASSERT_EQ(StatusCode::OK_200, res->status);
  14394. }
  14395. }
  14396. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14397. std::string data(1024 * 1024 * 2, '&');
  14398. std::stringstream buffer;
  14399. buffer << data;
  14400. Client cli("https://localhost:8080");
  14401. cli.enable_server_certificate_verification(false);
  14402. UploadFormDataItems items{
  14403. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14404. {"hello", "world", "", ""},
  14405. };
  14406. for (const char &c : " \t\r\n") {
  14407. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14408. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14409. ASSERT_FALSE(res);
  14410. }
  14411. }
  14412. TEST(MultipartFormDataTest, AlternateFilename) {
  14413. auto handled = false;
  14414. Server svr;
  14415. svr.Post("/test", [&](const Request &req, Response &res) {
  14416. ASSERT_EQ(2u, req.form.files.size());
  14417. ASSERT_EQ(1u, req.form.fields.size());
  14418. // Test files
  14419. const auto &file1 = req.form.get_file("file1");
  14420. ASSERT_EQ("file1", file1.name);
  14421. ASSERT_EQ("A.txt", file1.filename);
  14422. ASSERT_EQ("text/plain", file1.content_type);
  14423. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14424. const auto &file2 = req.form.get_file("file2");
  14425. ASSERT_EQ("file2", file2.name);
  14426. ASSERT_EQ("a.html", file2.filename);
  14427. ASSERT_EQ("text/html", file2.content_type);
  14428. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14429. file2.content);
  14430. // Test text field
  14431. const auto &text = req.form.get_field("text");
  14432. ASSERT_EQ("text default", text);
  14433. res.set_content("ok", "text/plain");
  14434. handled = true;
  14435. });
  14436. thread t = thread([&] { svr.listen(HOST, PORT); });
  14437. auto se = detail::scope_exit([&] {
  14438. svr.stop();
  14439. t.join();
  14440. ASSERT_FALSE(svr.is_running());
  14441. ASSERT_TRUE(handled);
  14442. });
  14443. svr.wait_until_ready();
  14444. auto req = "POST /test HTTP/1.1\r\n"
  14445. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14446. "Content-Length: 399\r\n"
  14447. "\r\n"
  14448. "----------\r\n"
  14449. "Content-Disposition: form-data; name=\"text\"\r\n"
  14450. "\r\n"
  14451. "text default\r\n"
  14452. "----------\r\n"
  14453. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14454. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14455. "Content-Type: text/plain\r\n"
  14456. "\r\n"
  14457. "Content of a.txt.\r\n"
  14458. "\r\n"
  14459. "----------\r\n"
  14460. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14461. "\"a.html\"\r\n"
  14462. "Content-Type: text/html\r\n"
  14463. "\r\n"
  14464. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14465. "\r\n"
  14466. "------------\r\n";
  14467. ASSERT_TRUE(send_request(1, req));
  14468. }
  14469. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14470. auto handled = false;
  14471. Server svr;
  14472. svr.Post("/test", [&](const Request &req, Response &res) {
  14473. // Case-insensitive "utf-8''" prefix with a long value
  14474. const auto &file = req.form.get_file("file1");
  14475. ASSERT_EQ("file1", file.name);
  14476. // 8000 chars exercises both the Content-Disposition parser and the
  14477. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14478. // Prior to the fix, std::regex_match on this header would cause O(N)
  14479. // stack recursion in libstdc++, leading to SIGSEGV.
  14480. std::string expected_filename(8000, 'A');
  14481. ASSERT_EQ(expected_filename, file.filename);
  14482. res.set_content("ok", "text/plain");
  14483. handled = true;
  14484. });
  14485. thread t = thread([&] { svr.listen(HOST, PORT); });
  14486. auto se = detail::scope_exit([&] {
  14487. svr.stop();
  14488. t.join();
  14489. ASSERT_FALSE(svr.is_running());
  14490. ASSERT_TRUE(handled);
  14491. });
  14492. svr.wait_until_ready();
  14493. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14494. // Regression test for GHSA-qq6v-r583-3h69
  14495. std::string long_filename(8000, 'A');
  14496. std::string body = "----------\r\n"
  14497. "Content-Disposition: form-data; name=\"file1\"; "
  14498. "filename*=\"Utf-8''" +
  14499. long_filename +
  14500. "\"\r\n"
  14501. "\r\n"
  14502. "hello\r\n"
  14503. "------------\r\n";
  14504. auto req = "POST /test HTTP/1.1\r\n"
  14505. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14506. "Content-Length: " +
  14507. std::to_string(body.size()) + "\r\n\r\n" + body;
  14508. ASSERT_TRUE(send_request(1, req));
  14509. }
  14510. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14511. auto handled = false;
  14512. Server svr;
  14513. svr.Post("/test", [&](const Request &req, Response &) {
  14514. ASSERT_EQ(2u, req.form.fields.size());
  14515. const auto &text1 = req.form.get_field("text1");
  14516. ASSERT_EQ("text1", text1);
  14517. const auto &text2 = req.form.get_field("text2");
  14518. ASSERT_EQ("text2", text2);
  14519. handled = true;
  14520. });
  14521. thread t = thread([&] { svr.listen(HOST, PORT); });
  14522. auto se = detail::scope_exit([&] {
  14523. svr.stop();
  14524. t.join();
  14525. ASSERT_FALSE(svr.is_running());
  14526. ASSERT_TRUE(handled);
  14527. });
  14528. svr.wait_until_ready();
  14529. auto req = "POST /test HTTP/1.1\r\n"
  14530. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14531. "Content-Length: 146\r\n"
  14532. "\r\n----------\r\n"
  14533. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14534. "\r\n"
  14535. "text1"
  14536. "\r\n----------\r\n"
  14537. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14538. "\r\n"
  14539. "text2"
  14540. "\r\n------------";
  14541. std::string response;
  14542. ASSERT_TRUE(send_request(1, req, &response));
  14543. ASSERT_EQ("200", response.substr(9, 3));
  14544. }
  14545. TEST(MultipartFormDataTest, ContentLength) {
  14546. auto handled = false;
  14547. Server svr;
  14548. svr.Post("/test", [&](const Request &req, Response &) {
  14549. ASSERT_EQ(2u, req.form.fields.size());
  14550. const auto &text1 = req.form.get_field("text1");
  14551. ASSERT_EQ("text1", text1);
  14552. const auto &text2 = req.form.get_field("text2");
  14553. ASSERT_EQ("text2", text2);
  14554. handled = true;
  14555. });
  14556. thread t = thread([&] { svr.listen(HOST, PORT); });
  14557. auto se = detail::scope_exit([&] {
  14558. svr.stop();
  14559. t.join();
  14560. ASSERT_FALSE(svr.is_running());
  14561. ASSERT_TRUE(handled);
  14562. });
  14563. svr.wait_until_ready();
  14564. auto req = "POST /test HTTP/1.1\r\n"
  14565. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14566. "Content-Length: 167\r\n"
  14567. "\r\n----------\r\n"
  14568. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14569. "Content-Length: 5\r\n"
  14570. "\r\n"
  14571. "text1"
  14572. "\r\n----------\r\n"
  14573. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14574. "\r\n"
  14575. "text2"
  14576. "\r\n------------\r\n";
  14577. std::string response;
  14578. ASSERT_TRUE(send_request(1, req, &response));
  14579. ASSERT_EQ("200", response.substr(9, 3));
  14580. }
  14581. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14582. auto handled = false;
  14583. Server svr;
  14584. svr.Post("/test", [&](const Request &req, Response &) {
  14585. ASSERT_EQ(2u, req.form.fields.size());
  14586. const auto &text1 = req.form.get_field("text1");
  14587. ASSERT_EQ("text1", text1);
  14588. // TODO: Add header access for text fields if needed
  14589. const auto &text2 = req.form.get_field("text2");
  14590. ASSERT_EQ("text2", text2);
  14591. // TODO: Header access for text fields needs to be implemented
  14592. // auto &headers = it->second.headers;
  14593. // ASSERT_EQ(3U, headers.size());
  14594. // auto custom_header = headers.find("x-whatever");
  14595. // ASSERT_TRUE(custom_header != headers.end());
  14596. // ASSERT_NE("customvalue", custom_header->second);
  14597. // ASSERT_EQ("CustomValue", custom_header->second);
  14598. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14599. handled = true;
  14600. });
  14601. thread t = thread([&] { svr.listen(HOST, PORT); });
  14602. auto se = detail::scope_exit([&] {
  14603. svr.stop();
  14604. t.join();
  14605. ASSERT_FALSE(svr.is_running());
  14606. ASSERT_TRUE(handled);
  14607. });
  14608. svr.wait_until_ready();
  14609. auto req = "POST /test HTTP/1.1\r\n"
  14610. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14611. "Content-Length: 232\r\n"
  14612. "\r\n----------\r\n"
  14613. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14614. "Content-Length: 5\r\n"
  14615. "X-Test: 1\r\n"
  14616. "\r\n"
  14617. "text1"
  14618. "\r\n----------\r\n"
  14619. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14620. "Content-Type: text/plain\r\n"
  14621. "X-Whatever: CustomValue\r\n"
  14622. "\r\n"
  14623. "text2"
  14624. "\r\n------------\r\n"
  14625. "That should be disregarded. Not even read";
  14626. std::string response;
  14627. ASSERT_TRUE(send_request(1, req, &response));
  14628. ASSERT_EQ("200", response.substr(9, 3));
  14629. }
  14630. TEST(MultipartFormDataTest, LargeHeader) {
  14631. auto handled = false;
  14632. Server svr;
  14633. svr.Post("/test", [&](const Request &req, Response &) {
  14634. ASSERT_EQ(1u, req.form.fields.size());
  14635. const auto &text = req.form.get_field("name1");
  14636. ASSERT_EQ("text1", text);
  14637. handled = true;
  14638. });
  14639. thread t = thread([&] { svr.listen(HOST, PORT); });
  14640. auto se = detail::scope_exit([&] {
  14641. svr.stop();
  14642. t.join();
  14643. ASSERT_FALSE(svr.is_running());
  14644. ASSERT_TRUE(handled);
  14645. });
  14646. svr.wait_until_ready();
  14647. auto boundary = std::string("cpp-httplib-multipart-data");
  14648. std::string content = "--" + boundary +
  14649. "\r\n"
  14650. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14651. "\r\n"
  14652. "text1\r\n"
  14653. "--" +
  14654. boundary + "--\r\n";
  14655. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14656. "Content-Type: multipart/form-data;boundary=" +
  14657. boundary +
  14658. "\r\n"
  14659. "Content-Length: " +
  14660. std::to_string(content.size()) +
  14661. "\r\n"
  14662. "Dummy-Header: ";
  14663. std::string header_suffix = "\r\n"
  14664. "\r\n";
  14665. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14666. size_t header_dummy_size =
  14667. read_buff_size -
  14668. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14669. auto header_dummy = std::string(header_dummy_size, '@');
  14670. auto req = header_prefix + header_dummy + header_suffix + content;
  14671. std::string response;
  14672. ASSERT_TRUE(send_request(1, req, &response));
  14673. ASSERT_EQ("200", response.substr(9, 3));
  14674. }
  14675. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14676. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14677. // (not chunked Transfer-Encoding) after the streaming refactor.
  14678. auto handled = false;
  14679. Server svr;
  14680. svr.Post("/upload", [&](const Request &req, Response &res) {
  14681. auto cl_it = req.headers.find("Content-Length");
  14682. EXPECT_TRUE(cl_it != req.headers.end());
  14683. auto te_it = req.headers.find("Transfer-Encoding");
  14684. EXPECT_TRUE(te_it == req.headers.end());
  14685. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14686. res.set_content("ok", "text/plain");
  14687. handled = true;
  14688. });
  14689. auto port = svr.bind_to_any_port(HOST);
  14690. auto t = thread([&] { svr.listen_after_bind(); });
  14691. auto se = detail::scope_exit([&] {
  14692. svr.stop();
  14693. t.join();
  14694. ASSERT_FALSE(svr.is_running());
  14695. ASSERT_TRUE(handled);
  14696. });
  14697. svr.wait_until_ready();
  14698. UploadFormDataItems items = {
  14699. {"field1", "hello", "", "text/plain"},
  14700. {"file1", "world", "test.txt", "application/octet-stream"},
  14701. };
  14702. Client cli(HOST, port);
  14703. auto res = cli.Post("/upload", {}, items);
  14704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14705. EXPECT_EQ(StatusCode::OK_200, res->status);
  14706. }
  14707. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14708. // Verify that make_multipart_content_provider coalesces many small segments
  14709. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14710. constexpr size_t kItemCount = 1000;
  14711. UploadFormDataItems items;
  14712. items.reserve(kItemCount);
  14713. for (size_t i = 0; i < kItemCount; i++) {
  14714. items.push_back(
  14715. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14716. }
  14717. const std::string boundary = "----test-boundary";
  14718. auto content_length = detail::get_multipart_content_length(items, boundary);
  14719. auto provider = detail::make_multipart_content_provider(items, boundary);
  14720. // Drive the provider the same way write_content_with_progress does
  14721. size_t write_count = 0;
  14722. size_t total_bytes = 0;
  14723. DataSink sink;
  14724. size_t offset = 0;
  14725. sink.write = [&](const char *d, size_t l) -> bool {
  14726. (void)d;
  14727. write_count++;
  14728. total_bytes += l;
  14729. offset += l;
  14730. return true;
  14731. };
  14732. sink.is_writable = []() -> bool { return true; };
  14733. while (offset < content_length) {
  14734. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14735. }
  14736. EXPECT_EQ(content_length, total_bytes);
  14737. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14738. // With buffering into 64KB blocks, write_count should be much smaller.
  14739. auto segment_count = 3 * kItemCount + 1;
  14740. EXPECT_LT(write_count, segment_count / 10);
  14741. }
  14742. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14743. // Integration test: send many UploadFormDataItems and verify the server
  14744. // receives all of them correctly (#2410).
  14745. constexpr size_t kItemCount = 500;
  14746. auto handled = false;
  14747. Server svr;
  14748. svr.Post("/upload", [&](const Request &req, Response &res) {
  14749. EXPECT_EQ(kItemCount, req.form.fields.size());
  14750. for (size_t i = 0; i < kItemCount; i++) {
  14751. auto key = "field" + std::to_string(i);
  14752. auto val = "value" + std::to_string(i);
  14753. auto it = req.form.fields.find(key);
  14754. if (it != req.form.fields.end()) {
  14755. EXPECT_EQ(val, it->second.content);
  14756. } else {
  14757. ADD_FAILURE() << "Missing field: " << key;
  14758. }
  14759. }
  14760. res.set_content("ok", "text/plain");
  14761. handled = true;
  14762. });
  14763. auto port = svr.bind_to_any_port(HOST);
  14764. auto t = thread([&] { svr.listen_after_bind(); });
  14765. auto se = detail::scope_exit([&] {
  14766. svr.stop();
  14767. t.join();
  14768. ASSERT_FALSE(svr.is_running());
  14769. ASSERT_TRUE(handled);
  14770. });
  14771. svr.wait_until_ready();
  14772. UploadFormDataItems items;
  14773. items.reserve(kItemCount);
  14774. for (size_t i = 0; i < kItemCount; i++) {
  14775. items.push_back(
  14776. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14777. }
  14778. Client cli(HOST, port);
  14779. auto res = cli.Post("/upload", items);
  14780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14781. EXPECT_EQ(StatusCode::OK_200, res->status);
  14782. }
  14783. TEST(MultipartFormDataTest, MakeFileProvider) {
  14784. // Verify make_file_provider sends a file's contents correctly.
  14785. const std::string file_content(4096, 'Z');
  14786. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14787. {
  14788. std::ofstream ofs(tmp_path, std::ios::binary);
  14789. ofs.write(file_content.data(),
  14790. static_cast<std::streamsize>(file_content.size()));
  14791. }
  14792. auto handled = false;
  14793. Server svr;
  14794. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14795. const ContentReader &content_reader) {
  14796. ASSERT_TRUE(req.is_multipart_form_data());
  14797. std::vector<FormData> items;
  14798. content_reader(
  14799. [&](const FormData &file) {
  14800. items.push_back(file);
  14801. return true;
  14802. },
  14803. [&](const char *data, size_t data_length) {
  14804. items.back().content.append(data, data_length);
  14805. return true;
  14806. });
  14807. ASSERT_EQ(1u, items.size());
  14808. EXPECT_EQ("myfile", items[0].name);
  14809. EXPECT_EQ("data.bin", items[0].filename);
  14810. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14811. EXPECT_EQ(file_content, items[0].content);
  14812. handled = true;
  14813. });
  14814. auto port = svr.bind_to_any_port(HOST);
  14815. auto t = thread([&] { svr.listen_after_bind(); });
  14816. auto se = detail::scope_exit([&] {
  14817. svr.stop();
  14818. t.join();
  14819. ASSERT_FALSE(svr.is_running());
  14820. ASSERT_TRUE(handled);
  14821. std::remove(tmp_path.c_str());
  14822. });
  14823. svr.wait_until_ready();
  14824. FormDataProviderItems providers;
  14825. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14826. "application/octet-stream"));
  14827. Client cli(HOST, port);
  14828. auto res = cli.Post("/upload", {}, {}, providers);
  14829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14830. EXPECT_EQ(StatusCode::OK_200, res->status);
  14831. }
  14832. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14833. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14834. // (100) headers is rejected with a 400 Bad Request response.
  14835. Server svr;
  14836. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14837. res.set_content("ok", "text/plain");
  14838. });
  14839. thread t = thread([&] { svr.listen(HOST, PORT); });
  14840. auto se = detail::scope_exit([&] {
  14841. svr.stop();
  14842. t.join();
  14843. ASSERT_FALSE(svr.is_running());
  14844. });
  14845. svr.wait_until_ready();
  14846. // Build a multipart part with 101 custom headers (exceeding
  14847. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14848. std::stringstream body;
  14849. body << "--simpleboundary\r\n"
  14850. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14851. for (int i = 0; i < 101; i++) {
  14852. body << "X-Custom-Header-" << i << ": value\r\n";
  14853. }
  14854. body << "\r\n"
  14855. << "value1\r\n"
  14856. << "--simpleboundary--\r\n";
  14857. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14858. Client cli(HOST, PORT);
  14859. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14862. }
  14863. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14864. // A body that never contains the declared boundary must not be accumulated
  14865. // while the parser waits for it. Buffering it would also make every read
  14866. // rescan everything seen so far, which is quadratic in the body size.
  14867. Server svr;
  14868. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14869. res.set_content("ok", "text/plain");
  14870. });
  14871. auto port = svr.bind_to_any_port(HOST);
  14872. thread t = thread([&] { svr.listen_after_bind(); });
  14873. auto se = detail::scope_exit([&] {
  14874. svr.stop();
  14875. t.join();
  14876. ASSERT_FALSE(svr.is_running());
  14877. });
  14878. svr.wait_until_ready();
  14879. Client cli(HOST, port);
  14880. cli.set_read_timeout(60, 0);
  14881. cli.set_write_timeout(60, 0);
  14882. // '-' is the worst case: it matches the first character of the boundary, so
  14883. // every position has to be checked against it.
  14884. auto post_dashes = [&](size_t size) {
  14885. const std::string body(size, '-');
  14886. auto start = std::chrono::steady_clock::now();
  14887. auto res =
  14888. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14889. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14890. std::chrono::steady_clock::now() - start)
  14891. .count();
  14892. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14893. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14894. return ms;
  14895. };
  14896. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14897. // Windows.
  14898. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14899. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14900. // Comparing the two sizes rather than checking an absolute duration keeps
  14901. // this meaningful across build types and CI load, both of which move the
  14902. // absolute numbers by more than an order of magnitude. Four times the bytes
  14903. // costs about four times the time when parsing is linear, and about sixteen
  14904. // times when the body is buffered and rescanned.
  14905. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14906. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14907. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14908. << "ms, which suggests the body is being buffered and rescanned";
  14909. }
  14910. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14911. // A boundary can only be followed by CRLF or by "--", so anything else is
  14912. // malformed no matter what comes next. The parser must say so right away
  14913. // instead of buffering the rest of the declared body.
  14914. Server svr;
  14915. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14916. res.set_content("ok", "text/plain");
  14917. });
  14918. auto port = svr.bind_to_any_port(HOST);
  14919. thread t = thread([&] { svr.listen_after_bind(); });
  14920. auto se = detail::scope_exit([&] {
  14921. svr.stop();
  14922. t.join();
  14923. ASSERT_FALSE(svr.is_running());
  14924. });
  14925. svr.wait_until_ready();
  14926. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14927. // buffers instead of failing would still be waiting for the remaining bytes.
  14928. const std::string body = "--zzzz\r\n"
  14929. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14930. "\r\n"
  14931. "text1"
  14932. "\r\n--zzzzXX";
  14933. const std::string req = "POST /post HTTP/1.1\r\n"
  14934. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14935. "Content-Length: 1048576\r\n"
  14936. "\r\n" +
  14937. body;
  14938. std::string response;
  14939. ASSERT_TRUE(send_request(3, req, &response, port));
  14940. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14941. EXPECT_EQ("400", response.substr(9, 3));
  14942. }
  14943. // Posts a multipart body split into two writes, so that the server sees the
  14944. // split at whatever offset the caller chose, and expects the single "text1"
  14945. // field to come through.
  14946. static void expect_split_multipart_ok(const std::string &body1,
  14947. const std::string &body2) {
  14948. auto handled = false;
  14949. Server svr;
  14950. svr.Post("/post", [&](const Request &req, Response &) {
  14951. EXPECT_EQ(1u, req.form.fields.size());
  14952. EXPECT_EQ("text1", req.form.get_field("text1"));
  14953. handled = true;
  14954. });
  14955. auto port = svr.bind_to_any_port(HOST);
  14956. thread t = thread([&] { svr.listen_after_bind(); });
  14957. auto se = detail::scope_exit([&] {
  14958. svr.stop();
  14959. t.join();
  14960. ASSERT_FALSE(svr.is_running());
  14961. ASSERT_TRUE(handled);
  14962. });
  14963. svr.wait_until_ready();
  14964. // "Connection: close" makes the server close once it has answered, so the
  14965. // response drain ends immediately instead of idling until the read timeout.
  14966. const std::string head =
  14967. "POST /post HTTP/1.1\r\n"
  14968. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14969. "Connection: close\r\n"
  14970. "Content-Length: " +
  14971. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14972. std::string response;
  14973. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14974. ASSERT_GE(response.size(), 12u) << "no response";
  14975. EXPECT_EQ("200", response.substr(9, 3));
  14976. }
  14977. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14978. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14979. // ignored, including when it does not arrive in the same read as the
  14980. // close-delimiter itself.
  14981. expect_split_multipart_ok("--zzzz\r\n"
  14982. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14983. "\r\n"
  14984. "text1"
  14985. "\r\n--zzzz--",
  14986. "\r\nthis epilogue must be ignored\r\n");
  14987. }
  14988. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14989. // The initial boundary may be preceded by a preamble of any length and may
  14990. // straddle a read boundary. Discarding data while waiting for it must not
  14991. // throw away a partial boundary sitting at the end of the buffer.
  14992. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14993. "zz\r\n"
  14994. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14995. "\r\n"
  14996. "text1"
  14997. "\r\n--zzzz--\r\n");
  14998. }
  14999. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15000. // The received boundary was only checked for being non-empty, so it could be
  15001. // as long as a header is allowed to be. The parser scans the body for
  15002. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15003. // costs a nearly full comparison at nearly every position, making the
  15004. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15005. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15006. Server svr;
  15007. svr.Post("/post", [](const Request &req, Response &res) {
  15008. EXPECT_EQ(1u, req.form.fields.size());
  15009. EXPECT_EQ("text1", req.form.get_field("text1"));
  15010. res.set_content("ok", "text/plain");
  15011. });
  15012. auto port = svr.bind_to_any_port(HOST);
  15013. thread t = thread([&] { svr.listen_after_bind(); });
  15014. auto se = detail::scope_exit([&] {
  15015. svr.stop();
  15016. t.join();
  15017. ASSERT_FALSE(svr.is_running());
  15018. });
  15019. svr.wait_until_ready();
  15020. Client cli(HOST, port);
  15021. auto post_with_boundary_of_length = [&](size_t len) {
  15022. const std::string boundary(len, 'a');
  15023. const std::string body =
  15024. "--" + boundary +
  15025. "\r\n"
  15026. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15027. "\r\n"
  15028. "text1"
  15029. "\r\n--" +
  15030. boundary + "--\r\n";
  15031. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15032. };
  15033. auto res = post_with_boundary_of_length(70);
  15034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15035. EXPECT_EQ(StatusCode::OK_200, res->status);
  15036. res = post_with_boundary_of_length(71);
  15037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15038. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15039. }
  15040. TEST(MakeFileBodyTest, Basic) {
  15041. const std::string file_content(4096, 'Z');
  15042. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15043. {
  15044. std::ofstream ofs(tmp_path, std::ios::binary);
  15045. ofs.write(file_content.data(),
  15046. static_cast<std::streamsize>(file_content.size()));
  15047. }
  15048. auto handled = false;
  15049. Server svr;
  15050. svr.Post("/upload", [&](const Request &req, Response &res) {
  15051. EXPECT_EQ(file_content, req.body);
  15052. handled = true;
  15053. res.status = StatusCode::OK_200;
  15054. });
  15055. auto port = svr.bind_to_any_port(HOST);
  15056. auto t = thread([&] { svr.listen_after_bind(); });
  15057. auto se = detail::scope_exit([&] {
  15058. svr.stop();
  15059. t.join();
  15060. ASSERT_FALSE(svr.is_running());
  15061. ASSERT_TRUE(handled);
  15062. std::remove(tmp_path.c_str());
  15063. });
  15064. svr.wait_until_ready();
  15065. auto fb = make_file_body(tmp_path);
  15066. ASSERT_GT(fb.first, 0u);
  15067. Client cli(HOST, port);
  15068. auto res =
  15069. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15071. EXPECT_EQ(StatusCode::OK_200, res->status);
  15072. }
  15073. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15074. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15075. {
  15076. std::ofstream ofs(path, std::ios::binary);
  15077. const std::string content(100, 'A');
  15078. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15079. }
  15080. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15081. auto body = make_file_body(path);
  15082. ASSERT_EQ(100u, body.first);
  15083. ASSERT_TRUE(static_cast<bool>(body.second));
  15084. // Rewritten shorter after its length was measured - and, on a server, after
  15085. // that length has already gone out as Content-Length.
  15086. {
  15087. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15088. const std::string content(10, 'A');
  15089. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15090. }
  15091. std::string written;
  15092. DataSink sink;
  15093. sink.write = [&](const char *d, size_t l) {
  15094. written.append(d, l);
  15095. return true;
  15096. };
  15097. // The provider has to report failure. write_content_with_progress() advances
  15098. // its offset only by what was written, so a provider that returns true
  15099. // without completing the length it promised is called again straight away,
  15100. // and again.
  15101. EXPECT_FALSE(body.second(0, body.first, sink));
  15102. EXPECT_EQ(std::string(10, 'A'), written);
  15103. }
  15104. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15105. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15106. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15107. {
  15108. std::ofstream ofs(path, std::ios::binary);
  15109. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15110. }
  15111. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15112. auto body = make_file_body(path);
  15113. ASSERT_EQ(content.size(), body.first);
  15114. ASSERT_TRUE(static_cast<bool>(body.second));
  15115. std::string written;
  15116. DataSink sink;
  15117. sink.write = [&](const char *d, size_t l) {
  15118. written.append(d, l);
  15119. return true;
  15120. };
  15121. EXPECT_TRUE(body.second(0, body.first, sink));
  15122. EXPECT_EQ(content, written);
  15123. }
  15124. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15125. static constexpr unsigned int number_of_tasks{1000000};
  15126. std::atomic_uint count{0};
  15127. std::unique_ptr<TaskQueue> task_queue{
  15128. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15129. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15130. auto queued = task_queue->enqueue(
  15131. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15132. EXPECT_TRUE(queued);
  15133. }
  15134. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15135. task_queue->shutdown();
  15136. #else
  15137. EXPECT_NO_THROW(task_queue->shutdown());
  15138. #endif
  15139. EXPECT_EQ(number_of_tasks, count.load());
  15140. }
  15141. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15142. static constexpr unsigned int number_of_tasks{1000000};
  15143. static constexpr unsigned int qlimit{2};
  15144. unsigned int queued_count{0};
  15145. std::atomic_uint count{0};
  15146. std::unique_ptr<TaskQueue> task_queue{
  15147. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15148. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15149. if (task_queue->enqueue(
  15150. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15151. queued_count++;
  15152. }
  15153. }
  15154. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15155. task_queue->shutdown();
  15156. #else
  15157. EXPECT_NO_THROW(task_queue->shutdown());
  15158. #endif
  15159. EXPECT_EQ(queued_count, count.load());
  15160. EXPECT_TRUE(queued_count <= number_of_tasks);
  15161. EXPECT_TRUE(queued_count >= qlimit);
  15162. }
  15163. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15164. // Use a short idle timeout so a dynamic thread spawns, times out and
  15165. // exits during the test, and the pool keeps working afterwards.
  15166. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15167. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15168. /*idle_timeout_sec=*/1}};
  15169. std::atomic_uint count{0};
  15170. std::condition_variable cv;
  15171. std::mutex mtx;
  15172. bool release = false;
  15173. // Block the base thread so the second task spawns a dynamic thread.
  15174. EXPECT_TRUE(task_queue->enqueue([&] {
  15175. std::unique_lock<std::mutex> lock(mtx);
  15176. while (!release) {
  15177. cv.wait(lock);
  15178. }
  15179. count++;
  15180. }));
  15181. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15182. // Let the dynamic thread finish its task and exceed the idle timeout.
  15183. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15184. {
  15185. std::unique_lock<std::mutex> lock(mtx);
  15186. release = true;
  15187. }
  15188. cv.notify_all();
  15189. // The pool must still accept and run tasks after the dynamic thread exited.
  15190. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15191. task_queue->shutdown();
  15192. EXPECT_EQ(3u, count.load());
  15193. }
  15194. TEST(TaskQueueTest, MaxQueuedRequests) {
  15195. static constexpr unsigned int qlimit{3};
  15196. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15197. std::condition_variable sem_cv;
  15198. std::mutex sem_mtx;
  15199. int credits = 0;
  15200. bool queued;
  15201. /* Fill up the queue with tasks that will block until we give them credits to
  15202. * complete. */
  15203. for (unsigned int n = 0; n <= qlimit;) {
  15204. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15205. std::unique_lock<std::mutex> lock(sem_mtx);
  15206. while (credits <= 0) {
  15207. sem_cv.wait(lock);
  15208. }
  15209. /* Consume the credit and signal the test code if they are all gone. */
  15210. if (--credits == 0) { sem_cv.notify_one(); }
  15211. });
  15212. if (n < qlimit) {
  15213. /* The first qlimit enqueues must succeed. */
  15214. EXPECT_TRUE(queued);
  15215. } else {
  15216. /* The last one will succeed only when the worker thread
  15217. * starts and dequeues the first blocking task. Although
  15218. * not necessary for the correctness of this test, we sleep for
  15219. * a short while to avoid busy waiting. */
  15220. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15221. }
  15222. if (queued) { n++; }
  15223. }
  15224. /* Further enqueues must fail since the queue is full. */
  15225. for (auto i = 0; i < 4; i++) {
  15226. queued = task_queue->enqueue([] {});
  15227. EXPECT_FALSE(queued);
  15228. }
  15229. /* Give the credits to allow the previous tasks to complete. */
  15230. {
  15231. std::unique_lock<std::mutex> lock(sem_mtx);
  15232. credits += qlimit + 1;
  15233. }
  15234. sem_cv.notify_all();
  15235. /* Wait for all the credits to be consumed. */
  15236. {
  15237. std::unique_lock<std::mutex> lock(sem_mtx);
  15238. while (credits > 0) {
  15239. sem_cv.wait(lock);
  15240. }
  15241. }
  15242. /* Check that we are able again to enqueue at least qlimit tasks. */
  15243. for (unsigned int i = 0; i < qlimit; i++) {
  15244. queued = task_queue->enqueue([] {});
  15245. EXPECT_TRUE(queued);
  15246. }
  15247. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15248. task_queue->shutdown();
  15249. #else
  15250. EXPECT_NO_THROW(task_queue->shutdown());
  15251. #endif
  15252. }
  15253. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15254. Server svr;
  15255. std::string method;
  15256. std::string body;
  15257. auto has_content_length = false;
  15258. auto has_transfer_encoding = false;
  15259. std::atomic<int> bad_requests{0};
  15260. // Leftover body bytes get parsed as a malformed request and answered with
  15261. // 400
  15262. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15263. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15264. });
  15265. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15266. res.set_redirect("/down", StatusCode::SeeOther_303);
  15267. });
  15268. svr.Get("/down", [&](const Request &req, Response &res) {
  15269. method = req.method;
  15270. body = req.body;
  15271. has_content_length = req.has_header("Content-Length");
  15272. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15273. res.set_content("ok", "text/plain");
  15274. });
  15275. auto port = svr.bind_to_any_port(HOST);
  15276. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15277. auto se = detail::scope_exit([&] {
  15278. svr.stop();
  15279. thread.join();
  15280. ASSERT_FALSE(svr.is_running());
  15281. });
  15282. svr.wait_until_ready();
  15283. const std::string payload = "SECRET-BODY";
  15284. auto check = [&](Client &cli, const Result &res) {
  15285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15286. EXPECT_EQ(StatusCode::OK_200, res->status);
  15287. EXPECT_EQ("ok", res->body);
  15288. EXPECT_EQ("GET", method);
  15289. EXPECT_TRUE(body.empty());
  15290. EXPECT_FALSE(has_content_length);
  15291. EXPECT_FALSE(has_transfer_encoding);
  15292. // Nothing of the original body may be left on the connection
  15293. auto res2 = cli.Get("/down");
  15294. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15295. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15296. EXPECT_EQ("ok", res2->body);
  15297. EXPECT_EQ(0, bad_requests);
  15298. };
  15299. // With content length
  15300. {
  15301. Client cli(HOST, port);
  15302. cli.set_keep_alive(true);
  15303. cli.set_follow_location(true);
  15304. auto res = cli.Post(
  15305. "/up", payload.size(),
  15306. [&](size_t offset, size_t length, DataSink &sink) {
  15307. return sink.write(payload.data() + offset, length);
  15308. },
  15309. "text/plain");
  15310. check(cli, res);
  15311. }
  15312. // Without content length (chunked)
  15313. {
  15314. Client cli(HOST, port);
  15315. cli.set_keep_alive(true);
  15316. cli.set_follow_location(true);
  15317. auto res = cli.Post(
  15318. "/up",
  15319. [&](size_t /*offset*/, DataSink &sink) {
  15320. sink.write(payload.data(), payload.size());
  15321. sink.done();
  15322. return true;
  15323. },
  15324. "text/plain");
  15325. check(cli, res);
  15326. }
  15327. }
  15328. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15329. Server svr;
  15330. std::string target;
  15331. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15332. // Echo the still-encoded name back in the Location
  15333. const std::string prefix = "/start/";
  15334. res.status = StatusCode::Found_302;
  15335. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15336. });
  15337. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15338. target = req.target;
  15339. res.set_content("ok", "text/plain");
  15340. });
  15341. auto port = svr.bind_to_any_port(HOST);
  15342. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15343. auto se = detail::scope_exit([&] {
  15344. svr.stop();
  15345. thread.join();
  15346. ASSERT_FALSE(svr.is_running());
  15347. });
  15348. svr.wait_until_ready();
  15349. // Decoding the Location path would turn the first four into a path
  15350. // separator, a query delimiter, a fragment delimiter and a different
  15351. // percent-encoded octet. The rest must keep reaching the server as they are.
  15352. const std::vector<std::string> names = {
  15353. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15354. };
  15355. for (auto path_encode : {true, false}) {
  15356. Client cli(HOST, port);
  15357. cli.set_follow_location(true);
  15358. cli.set_path_encode(path_encode);
  15359. for (const auto &name : names) {
  15360. target.clear();
  15361. auto res = cli.Get("/start/" + name);
  15362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15363. EXPECT_EQ(StatusCode::OK_200, res->status);
  15364. EXPECT_EQ("/dest/" + name, target);
  15365. }
  15366. }
  15367. }
  15368. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15369. Server svr;
  15370. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15371. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15372. });
  15373. svr.Get("/hello", [](const Request &req, Response &res) {
  15374. res.set_content(req.get_param_value("key"), "text/plain");
  15375. });
  15376. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15377. auto se = detail::scope_exit([&] {
  15378. svr.stop();
  15379. thread.join();
  15380. ASSERT_FALSE(svr.is_running());
  15381. });
  15382. svr.wait_until_ready();
  15383. {
  15384. Client cli(HOST, PORT);
  15385. cli.set_follow_location(true);
  15386. auto res = cli.Get("/");
  15387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15388. EXPECT_EQ(StatusCode::OK_200, res->status);
  15389. EXPECT_EQ("val&key2=val2", res->body);
  15390. }
  15391. }
  15392. #endif
  15393. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15394. Server svr;
  15395. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15396. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15397. });
  15398. svr.Get("/hello", [](const Request &req, Response &res) {
  15399. res.set_content(req.get_param_value("key"), "text/plain");
  15400. });
  15401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15402. auto se = detail::scope_exit([&] {
  15403. svr.stop();
  15404. thread.join();
  15405. ASSERT_FALSE(svr.is_running());
  15406. });
  15407. svr.wait_until_ready();
  15408. {
  15409. Client cli(HOST, PORT);
  15410. cli.set_follow_location(true);
  15411. auto res = cli.Get("/");
  15412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15413. EXPECT_EQ(StatusCode::OK_200, res->status);
  15414. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15415. }
  15416. }
  15417. TEST(RedirectTest, RedirectWithPlusInPath) {
  15418. Server svr;
  15419. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15420. res.set_redirect("/a+b");
  15421. });
  15422. // Route pattern uses regex; escape + as \\+
  15423. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15424. res.set_content(req.path, "text/plain");
  15425. });
  15426. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15427. auto se = detail::scope_exit([&] {
  15428. svr.stop();
  15429. thread.join();
  15430. ASSERT_FALSE(svr.is_running());
  15431. });
  15432. svr.wait_until_ready();
  15433. {
  15434. Client cli(HOST, PORT);
  15435. cli.set_follow_location(true);
  15436. auto res = cli.Get("/");
  15437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15438. EXPECT_EQ(StatusCode::OK_200, res->status);
  15439. EXPECT_EQ("/a+b", res->body);
  15440. }
  15441. }
  15442. TEST(RedirectTest, ResolveRelativeLocation) {
  15443. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15444. const std::vector<std::pair<std::string, std::string>> cases = {
  15445. {"g", "/b/c/g"},
  15446. {"./g", "/b/c/g"},
  15447. {"g/", "/b/c/g/"},
  15448. {"?y", "/b/c/d;p?y"},
  15449. {"g?y", "/b/c/g?y"},
  15450. {"#s", "/b/c/d;p?q#s"},
  15451. {"g#s", "/b/c/g#s"},
  15452. {"g?y#s", "/b/c/g?y#s"},
  15453. {";x", "/b/c/;x"},
  15454. {"g;x", "/b/c/g;x"},
  15455. {".", "/b/c/"},
  15456. {"./", "/b/c/"},
  15457. {"..", "/b/"},
  15458. {"../", "/b/"},
  15459. {"../g", "/b/g"},
  15460. {"../..", "/"},
  15461. {"../../", "/"},
  15462. {"../../g", "/g"},
  15463. {"../../../g", "/g"},
  15464. {"g.", "/b/c/g."},
  15465. {".g", "/b/c/.g"},
  15466. {"g..", "/b/c/g.."},
  15467. {"..g", "/b/c/..g"},
  15468. {"./../g", "/b/g"},
  15469. {"./g/.", "/b/c/g/"},
  15470. {"g/./h", "/b/c/g/h"},
  15471. {"g/../h", "/b/c/h"},
  15472. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15473. {"g;x=1/../y", "/b/c/y"},
  15474. {"g?y/./x", "/b/c/g?y/./x"},
  15475. {"g#s/../x", "/b/c/g#s/../x"},
  15476. // Not relative-path references, so left for parse_url.
  15477. {"/g", "/g"},
  15478. {"//g", "//g"},
  15479. {"http://g/x", "http://g/x"},
  15480. {"g:h", "g:h"},
  15481. };
  15482. for (const auto &c : cases) {
  15483. EXPECT_EQ(c.second,
  15484. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15485. << c.first;
  15486. }
  15487. }
  15488. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15489. Server svr;
  15490. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15491. res.set_redirect(req.get_param_value("to"));
  15492. });
  15493. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15494. res.set_content(req.target, "text/plain");
  15495. });
  15496. svr.Get("/other", [](const Request &req, Response &res) {
  15497. res.set_content(req.target, "text/plain");
  15498. });
  15499. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15500. auto se = detail::scope_exit([&] {
  15501. svr.stop();
  15502. thread.join();
  15503. ASSERT_FALSE(svr.is_running());
  15504. });
  15505. svr.wait_until_ready();
  15506. const std::vector<std::pair<std::string, std::string>> cases = {
  15507. {"next", "/dir/next"},
  15508. {"./next?x=1", "/dir/next?x=1"},
  15509. {"../other", "/other"},
  15510. };
  15511. for (const auto &c : cases) {
  15512. Client cli(HOST, PORT);
  15513. cli.set_follow_location(true);
  15514. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15515. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15516. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15517. EXPECT_EQ(c.second, res->body) << c.first;
  15518. }
  15519. }
  15520. #ifdef CPPHTTPLIB_SSL_ENABLED
  15521. TEST(RedirectTest, Issue2185_Online) {
  15522. SSLClient client("github.com");
  15523. client.set_follow_location(true);
  15524. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15525. "Coollab-Windows.zip");
  15526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15527. EXPECT_EQ(StatusCode::OK_200, res->status);
  15528. EXPECT_EQ(9920427U, res->body.size());
  15529. }
  15530. #endif
  15531. TEST(VulnerabilityTest, CRLFInjection) {
  15532. Server svr;
  15533. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15534. res.set_content("Hello 1", "text/plain");
  15535. });
  15536. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15537. res.set_content("Hello 2", "text/plain");
  15538. });
  15539. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15540. res.set_content("Hello 3", "text/plain");
  15541. });
  15542. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15543. res.set_content("Hello 4", "text/plain");
  15544. });
  15545. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15546. for (const auto &x : req.headers) {
  15547. auto key = x.first;
  15548. EXPECT_STRNE("evil", key.c_str());
  15549. }
  15550. });
  15551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15552. auto se = detail::scope_exit([&] {
  15553. svr.stop();
  15554. thread.join();
  15555. ASSERT_FALSE(svr.is_running());
  15556. });
  15557. svr.wait_until_ready();
  15558. {
  15559. Client cli(HOST, PORT);
  15560. cli.Post("/test1", "A=B",
  15561. "application/x-www-form-urlencoded\r\nevil: hello1");
  15562. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15563. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15564. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15565. }
  15566. }
  15567. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15568. auto server_thread = std::thread([] {
  15569. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15570. default_socket_options(srv);
  15571. sockaddr_in addr{};
  15572. addr.sin_family = AF_INET;
  15573. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15574. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15575. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15576. ::listen(srv, 1);
  15577. sockaddr_in cli_addr{};
  15578. socklen_t cli_len = sizeof(cli_addr);
  15579. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15580. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15581. std::string buf_all;
  15582. char buf[2048];
  15583. ssize_t n;
  15584. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15585. buf_all.append(buf, static_cast<size_t>(n));
  15586. size_t pos;
  15587. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15588. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15589. auto e = request_block.find("\r\n");
  15590. if (e != std::string::npos) {
  15591. auto request_line = request_block.substr(0, e);
  15592. std::string msg =
  15593. "CRLF injection detected in request line: '" + request_line + "'";
  15594. EXPECT_FALSE(true) << msg;
  15595. }
  15596. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15597. ::send(cli,
  15598. #ifdef _WIN32
  15599. static_cast<const char *>(resp.c_str()),
  15600. static_cast<int>(resp.size()),
  15601. #else
  15602. resp.c_str(), resp.size(),
  15603. #endif
  15604. 0);
  15605. buf_all.erase(0, pos + 4);
  15606. }
  15607. }
  15608. detail::close_socket(cli);
  15609. detail::close_socket(srv);
  15610. });
  15611. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15612. auto cli = Client("127.0.0.1", PORT + 1);
  15613. auto headers = Headers{
  15614. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15615. {"Connection", "keep-alive"}};
  15616. auto res = cli.Get("/hi", headers);
  15617. EXPECT_FALSE(res);
  15618. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15619. server_thread.join();
  15620. }
  15621. // A request rejected before any byte reaches the socket must fail right away
  15622. // instead of waiting for a response the server will never send.
  15623. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15624. // The kernel completes the TCP handshake from the listen backlog, so the
  15625. // client connects, but nothing ever reads, responds or closes.
  15626. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15627. default_socket_options(srv);
  15628. sockaddr_in addr{};
  15629. addr.sin_family = AF_INET;
  15630. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15631. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15632. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15633. ASSERT_EQ(0, ::listen(srv, 8));
  15634. auto cli = Client("127.0.0.1", PORT + 1);
  15635. cli.set_read_timeout(10, 0);
  15636. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15637. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15638. std::chrono::steady_clock::now() - start)
  15639. .count();
  15640. };
  15641. {
  15642. Request req;
  15643. req.method = "GE T";
  15644. req.path = "/";
  15645. auto start = std::chrono::steady_clock::now();
  15646. auto res = cli.send(req);
  15647. EXPECT_FALSE(res);
  15648. EXPECT_EQ(Error::Write, res.error());
  15649. EXPECT_LT(elapsed_ms(start), 1000);
  15650. }
  15651. {
  15652. auto start = std::chrono::steady_clock::now();
  15653. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15654. EXPECT_FALSE(res);
  15655. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15656. EXPECT_LT(elapsed_ms(start), 1000);
  15657. }
  15658. EXPECT_FALSE(cli.is_socket_open());
  15659. detail::close_socket(srv);
  15660. }
  15661. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15662. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15663. default_socket_options(srv);
  15664. sockaddr_in addr{};
  15665. addr.sin_family = AF_INET;
  15666. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15667. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15668. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15669. ASSERT_EQ(0, ::listen(srv, 1));
  15670. std::string received;
  15671. auto server_thread = std::thread([&] {
  15672. auto sock = ::accept(srv, nullptr, nullptr);
  15673. if (sock == INVALID_SOCKET) { return; }
  15674. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15675. char buf[2048];
  15676. ssize_t n;
  15677. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15678. received.append(buf, static_cast<size_t>(n));
  15679. }
  15680. detail::close_socket(sock);
  15681. });
  15682. {
  15683. auto cli = Client("127.0.0.1", PORT + 1);
  15684. // "Z" sorts after the default headers, so writing straight to the socket
  15685. // would have sent the request line and those headers before the rejection.
  15686. auto handle =
  15687. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15688. EXPECT_FALSE(handle.is_valid());
  15689. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15690. }
  15691. server_thread.join();
  15692. detail::close_socket(srv);
  15693. EXPECT_TRUE(received.empty()) << received;
  15694. }
  15695. TEST(PathParamsTest, StaticMatch) {
  15696. const auto pattern = "/users/all";
  15697. detail::PathParamsMatcher matcher(pattern);
  15698. Request request;
  15699. request.path = "/users/all";
  15700. ASSERT_TRUE(matcher.match(request));
  15701. std::unordered_map<std::string, std::string> expected_params = {};
  15702. EXPECT_EQ(request.path_params, expected_params);
  15703. }
  15704. TEST(PathParamsTest, StaticMismatch) {
  15705. const auto pattern = "/users/all";
  15706. detail::PathParamsMatcher matcher(pattern);
  15707. Request request;
  15708. request.path = "/users/1";
  15709. ASSERT_FALSE(matcher.match(request));
  15710. }
  15711. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15712. const auto pattern = "/users/:id/subscriptions";
  15713. detail::PathParamsMatcher matcher(pattern);
  15714. Request request;
  15715. request.path = "/users/42/subscriptions";
  15716. ASSERT_TRUE(matcher.match(request));
  15717. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15718. EXPECT_EQ(request.path_params, expected_params);
  15719. }
  15720. TEST(PathParamsTest, SingleParamInTheEnd) {
  15721. const auto pattern = "/users/:id";
  15722. detail::PathParamsMatcher matcher(pattern);
  15723. Request request;
  15724. request.path = "/users/24";
  15725. ASSERT_TRUE(matcher.match(request));
  15726. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15727. EXPECT_EQ(request.path_params, expected_params);
  15728. }
  15729. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15730. const auto pattern = "/users/:id/";
  15731. detail::PathParamsMatcher matcher(pattern);
  15732. Request request;
  15733. request.path = "/users/42/";
  15734. ASSERT_TRUE(matcher.match(request));
  15735. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15736. EXPECT_EQ(request.path_params, expected_params);
  15737. }
  15738. TEST(PathParamsTest, EmptyParam) {
  15739. const auto pattern = "/users/:id/";
  15740. detail::PathParamsMatcher matcher(pattern);
  15741. Request request;
  15742. request.path = "/users//";
  15743. ASSERT_TRUE(matcher.match(request));
  15744. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15745. EXPECT_EQ(request.path_params, expected_params);
  15746. }
  15747. TEST(PathParamsTest, FragmentMismatch) {
  15748. const auto pattern = "/users/:id/";
  15749. detail::PathParamsMatcher matcher(pattern);
  15750. Request request;
  15751. request.path = "/admins/24/";
  15752. ASSERT_FALSE(matcher.match(request));
  15753. }
  15754. TEST(PathParamsTest, ExtraFragments) {
  15755. const auto pattern = "/users/:id";
  15756. detail::PathParamsMatcher matcher(pattern);
  15757. Request request;
  15758. request.path = "/users/42/subscriptions";
  15759. ASSERT_FALSE(matcher.match(request));
  15760. }
  15761. TEST(PathParamsTest, MissingTrailingParam) {
  15762. const auto pattern = "/users/:id";
  15763. detail::PathParamsMatcher matcher(pattern);
  15764. Request request;
  15765. request.path = "/users";
  15766. ASSERT_FALSE(matcher.match(request));
  15767. }
  15768. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15769. const auto pattern = "/users/:id/subscriptions";
  15770. detail::PathParamsMatcher matcher(pattern);
  15771. Request request;
  15772. request.path = "/users/subscriptions";
  15773. ASSERT_FALSE(matcher.match(request));
  15774. }
  15775. TEST(PathParamsTest, MultipleParams) {
  15776. const auto pattern = "/users/:userid/subscriptions/:subid";
  15777. detail::PathParamsMatcher matcher(pattern);
  15778. Request request;
  15779. request.path = "/users/42/subscriptions/2";
  15780. ASSERT_TRUE(matcher.match(request));
  15781. std::unordered_map<std::string, std::string> expected_params = {
  15782. {"userid", "42"}, {"subid", "2"}};
  15783. EXPECT_EQ(request.path_params, expected_params);
  15784. }
  15785. TEST(PathParamsTest, SequenceOfParams) {
  15786. const auto pattern = "/values/:x/:y/:z";
  15787. detail::PathParamsMatcher matcher(pattern);
  15788. Request request;
  15789. request.path = "/values/1/2/3";
  15790. ASSERT_TRUE(matcher.match(request));
  15791. std::unordered_map<std::string, std::string> expected_params = {
  15792. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15793. EXPECT_EQ(request.path_params, expected_params);
  15794. }
  15795. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15796. const auto pattern = "/prefix:suffix";
  15797. detail::PathParamsMatcher matcher(pattern);
  15798. Request request;
  15799. request.path = "/prefix:suffix";
  15800. ASSERT_TRUE(matcher.match(request));
  15801. const std::unordered_map<std::string, std::string> expected_params = {};
  15802. EXPECT_EQ(request.path_params, expected_params);
  15803. }
  15804. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15805. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15806. // calling thread's stack on a long enough path for a quantified pattern;
  15807. // RegexMatcher must refuse to run regex matching on paths beyond
  15808. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15809. detail::RegexMatcher matcher("/files/(.*)");
  15810. Request within_limit;
  15811. within_limit.path = "/files/" + std::string(10, 'A');
  15812. EXPECT_TRUE(matcher.match(within_limit));
  15813. Request over_limit;
  15814. over_limit.path =
  15815. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15816. EXPECT_FALSE(matcher.match(over_limit));
  15817. }
  15818. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15819. Server svr;
  15820. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15821. res.set_content("ok", "text/plain");
  15822. });
  15823. auto port = svr.bind_to_any_port(HOST);
  15824. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15825. auto se = detail::scope_exit([&] {
  15826. svr.stop();
  15827. thread.join();
  15828. ASSERT_FALSE(svr.is_running());
  15829. });
  15830. svr.wait_until_ready();
  15831. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15832. // request URI limit; this used to be able to crash the process.
  15833. std::string path =
  15834. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15835. std::string req = "GET " + path +
  15836. " HTTP/1.1\r\n"
  15837. "Host: " +
  15838. std::string(HOST) + ":" + std::to_string(port) +
  15839. "\r\n"
  15840. "Connection: close\r\n"
  15841. "\r\n";
  15842. std::string response;
  15843. ASSERT_TRUE(send_request(5, req, &response, port));
  15844. EXPECT_NE(std::string::npos, response.find("404"));
  15845. }
  15846. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15847. Server svr;
  15848. auto handler = [](const Request & /*req*/, Response &res) {
  15849. res.set_content("hit", "text/plain");
  15850. };
  15851. // No regex metacharacter, so this one is compared literally
  15852. svr.Get("/literal/route", handler);
  15853. // '.' is a regex metacharacter, so this one must keep regex semantics
  15854. svr.Get("/a.c", handler);
  15855. auto port = svr.bind_to_any_port(HOST);
  15856. std::thread t([&]() { svr.listen_after_bind(); });
  15857. auto se = detail::scope_exit([&] {
  15858. svr.stop();
  15859. t.join();
  15860. ASSERT_FALSE(svr.is_running());
  15861. });
  15862. svr.wait_until_ready();
  15863. Client cli(HOST, port);
  15864. struct {
  15865. const char *path;
  15866. int status;
  15867. } cases[] = {
  15868. {"/literal/route", StatusCode::OK_200},
  15869. {"/literal/routes", StatusCode::NotFound_404},
  15870. {"/literal/rout", StatusCode::NotFound_404},
  15871. {"/abc", StatusCode::OK_200},
  15872. {"/a.c", StatusCode::OK_200},
  15873. };
  15874. for (const auto &x : cases) {
  15875. auto res = cli.Get(x.path);
  15876. ASSERT_TRUE(res) << x.path;
  15877. EXPECT_EQ(x.status, res->status) << x.path;
  15878. }
  15879. }
  15880. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15881. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15882. // from exhausting the stack, so it must only constrain routes that actually
  15883. // run a regular expression. A literal route is matched by comparison and
  15884. // stays usable at any length.
  15885. Server svr;
  15886. const std::string pattern =
  15887. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15888. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15889. res.set_content("hit", "text/plain");
  15890. });
  15891. auto port = svr.bind_to_any_port(HOST);
  15892. std::thread t([&]() { svr.listen_after_bind(); });
  15893. auto se = detail::scope_exit([&] {
  15894. svr.stop();
  15895. t.join();
  15896. ASSERT_FALSE(svr.is_running());
  15897. });
  15898. svr.wait_until_ready();
  15899. Client cli(HOST, port);
  15900. auto res = cli.Get(pattern);
  15901. ASSERT_TRUE(res);
  15902. EXPECT_EQ(StatusCode::OK_200, res->status);
  15903. }
  15904. TEST(ParseUrlTest, VariousPatterns) {
  15905. {
  15906. detail::UrlComponents uc;
  15907. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15908. EXPECT_EQ("http", uc.scheme);
  15909. EXPECT_EQ("example.com", uc.host);
  15910. EXPECT_EQ("8080", uc.port);
  15911. EXPECT_EQ("/path", uc.path);
  15912. EXPECT_EQ("?q=1", uc.query);
  15913. }
  15914. {
  15915. detail::UrlComponents uc;
  15916. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15917. EXPECT_EQ("https", uc.scheme);
  15918. EXPECT_EQ("example.com", uc.host);
  15919. EXPECT_TRUE(uc.port.empty());
  15920. EXPECT_EQ("/path", uc.path);
  15921. }
  15922. {
  15923. detail::UrlComponents uc;
  15924. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15925. EXPECT_EQ("::1", uc.host);
  15926. EXPECT_EQ("8080", uc.port);
  15927. EXPECT_EQ("/path", uc.path);
  15928. }
  15929. {
  15930. detail::UrlComponents uc;
  15931. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15932. }
  15933. {
  15934. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15935. // the path while the connection still targets the bracketed host.
  15936. detail::UrlComponents uc;
  15937. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15938. }
  15939. {
  15940. detail::UrlComponents uc;
  15941. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15942. }
  15943. {
  15944. detail::UrlComponents uc;
  15945. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15946. EXPECT_EQ("::1", uc.host);
  15947. EXPECT_TRUE(uc.port.empty());
  15948. EXPECT_EQ("/path", uc.path);
  15949. }
  15950. {
  15951. detail::UrlComponents uc;
  15952. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15953. EXPECT_TRUE(uc.scheme.empty());
  15954. EXPECT_EQ("example.com", uc.host);
  15955. EXPECT_EQ("/path", uc.path);
  15956. EXPECT_EQ("?q=1", uc.query);
  15957. }
  15958. {
  15959. detail::UrlComponents uc;
  15960. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15961. EXPECT_TRUE(uc.host.empty());
  15962. EXPECT_EQ("/path", uc.path);
  15963. EXPECT_EQ("?q=1", uc.query);
  15964. }
  15965. {
  15966. detail::UrlComponents uc;
  15967. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15968. EXPECT_EQ("example.com", uc.host);
  15969. EXPECT_EQ("8080", uc.port);
  15970. }
  15971. {
  15972. // Unix socket path — must not be parsed as host
  15973. detail::UrlComponents uc;
  15974. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15975. EXPECT_TRUE(uc.host.empty());
  15976. }
  15977. {
  15978. detail::UrlComponents uc;
  15979. ASSERT_TRUE(detail::parse_url("", uc));
  15980. EXPECT_TRUE(uc.host.empty());
  15981. EXPECT_TRUE(uc.path.empty());
  15982. }
  15983. {
  15984. detail::UrlComponents uc;
  15985. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15986. }
  15987. {
  15988. detail::UrlComponents uc;
  15989. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15990. }
  15991. {
  15992. // Accepted by parse_url; callers restrict to http/https
  15993. detail::UrlComponents uc;
  15994. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15995. EXPECT_EQ("ftp", uc.scheme);
  15996. }
  15997. {
  15998. detail::UrlComponents uc;
  15999. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16000. }
  16001. {
  16002. detail::UrlComponents uc;
  16003. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16004. }
  16005. }
  16006. TEST(ParseUrlTest, FragmentHandling) {
  16007. {
  16008. detail::UrlComponents uc;
  16009. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16010. EXPECT_EQ("/path", uc.path);
  16011. EXPECT_TRUE(uc.query.empty());
  16012. }
  16013. {
  16014. detail::UrlComponents uc;
  16015. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16016. EXPECT_TRUE(uc.path.empty());
  16017. EXPECT_TRUE(uc.query.empty());
  16018. }
  16019. }
  16020. TEST(ParseUrlTest, UserinfoHandling) {
  16021. // Userinfo with @ but no colon — host includes @
  16022. detail::UrlComponents uc;
  16023. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16024. EXPECT_EQ("user@host.com", uc.host);
  16025. EXPECT_EQ("/path", uc.path);
  16026. }
  16027. TEST(ParseUrlTest, IPv6EdgeCases) {
  16028. {
  16029. detail::UrlComponents uc;
  16030. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16031. EXPECT_TRUE(uc.scheme.empty());
  16032. EXPECT_EQ("::1", uc.host);
  16033. EXPECT_EQ("8080", uc.port);
  16034. }
  16035. {
  16036. // Zone ID '%25' is not in [a-fA-F0-9:]
  16037. detail::UrlComponents uc;
  16038. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16039. }
  16040. }
  16041. TEST(ParseUrlTest, SchemeEdgeCases) {
  16042. {
  16043. detail::UrlComponents uc;
  16044. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16045. }
  16046. {
  16047. detail::UrlComponents uc;
  16048. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16049. }
  16050. {
  16051. detail::UrlComponents uc;
  16052. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16053. }
  16054. }
  16055. TEST(ParseUrlTest, PortEdgeCases) {
  16056. {
  16057. detail::UrlComponents uc;
  16058. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16059. EXPECT_TRUE(uc.port.empty());
  16060. EXPECT_EQ("/path", uc.path);
  16061. }
  16062. {
  16063. // parse_url accepts any port string; validation is done by parse_port
  16064. detail::UrlComponents uc;
  16065. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16066. EXPECT_EQ("abc", uc.port);
  16067. }
  16068. }
  16069. TEST(ParseUrlTest, WebSocketPatterns) {
  16070. {
  16071. detail::UrlComponents uc;
  16072. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16073. EXPECT_EQ("ws", uc.scheme);
  16074. EXPECT_EQ("echo.example.com", uc.host);
  16075. EXPECT_EQ("8080", uc.port);
  16076. EXPECT_EQ("/ws", uc.path);
  16077. }
  16078. {
  16079. detail::UrlComponents uc;
  16080. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16081. EXPECT_EQ("wss", uc.scheme);
  16082. EXPECT_EQ("echo.example.com", uc.host);
  16083. EXPECT_TRUE(uc.port.empty());
  16084. EXPECT_EQ("/ws", uc.path);
  16085. }
  16086. }
  16087. TEST(ParseUrlTest, QueryOnly) {
  16088. detail::UrlComponents uc;
  16089. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16090. EXPECT_TRUE(uc.host.empty());
  16091. EXPECT_TRUE(uc.path.empty());
  16092. EXPECT_EQ("?q=1&r=2", uc.query);
  16093. }
  16094. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16095. detail::UrlComponents uc;
  16096. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16097. EXPECT_TRUE(uc.scheme.empty());
  16098. EXPECT_EQ("example.com", uc.host);
  16099. EXPECT_EQ("443", uc.port);
  16100. EXPECT_EQ("/path", uc.path);
  16101. }
  16102. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16103. // If ipv6 regex working, regex match codepath is taken.
  16104. // else port will default to 80 in Client impl
  16105. int clientImplMagicPort = 80;
  16106. int port = 4321;
  16107. // above ports must be different to avoid false negative
  16108. EXPECT_NE(clientImplMagicPort, port);
  16109. std::string ipV6TestURL = "http://[ff06::c3]";
  16110. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16111. CLIENT_PRIVATE_KEY_FILE);
  16112. EXPECT_EQ(cli.port(), port);
  16113. }
  16114. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16115. auto file_path = "./www/dir/index.html";
  16116. auto dir_path = "./www/dir";
  16117. detail::FileStat stat_file(file_path);
  16118. EXPECT_TRUE(stat_file.is_file());
  16119. EXPECT_FALSE(stat_file.is_dir());
  16120. detail::FileStat stat_dir(dir_path);
  16121. EXPECT_FALSE(stat_dir.is_file());
  16122. EXPECT_TRUE(stat_dir.is_dir());
  16123. }
  16124. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16125. // IPv4 with default HTTP port (80)
  16126. EXPECT_EQ("example.com",
  16127. detail::make_host_and_port_string("example.com", 80, false));
  16128. // IPv4 with default HTTPS port (443)
  16129. EXPECT_EQ("example.com",
  16130. detail::make_host_and_port_string("example.com", 443, true));
  16131. // IPv4 with non-default HTTP port
  16132. EXPECT_EQ("example.com:8080",
  16133. detail::make_host_and_port_string("example.com", 8080, false));
  16134. // IPv4 with non-default HTTPS port
  16135. EXPECT_EQ("example.com:8443",
  16136. detail::make_host_and_port_string("example.com", 8443, true));
  16137. // IPv6 with default HTTP port (80)
  16138. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16139. // IPv6 with default HTTPS port (443)
  16140. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16141. // IPv6 with non-default HTTP port
  16142. EXPECT_EQ("[::1]:8080",
  16143. detail::make_host_and_port_string("::1", 8080, false));
  16144. // IPv6 with non-default HTTPS port
  16145. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16146. // IPv6 full address with default port
  16147. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16148. detail::make_host_and_port_string(
  16149. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16150. // IPv6 full address with non-default port
  16151. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16152. detail::make_host_and_port_string(
  16153. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16154. // IPv6 localhost with non-default port
  16155. EXPECT_EQ("[::1]:3000",
  16156. detail::make_host_and_port_string("::1", 3000, false));
  16157. // IPv6 with zone ID (link-local address) with default port
  16158. EXPECT_EQ("[fe80::1%eth0]",
  16159. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16160. // IPv6 with zone ID (link-local address) with non-default port
  16161. EXPECT_EQ("[fe80::1%eth0]:8080",
  16162. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16163. // Edge case: Port 443 with is_ssl=false (should add port)
  16164. EXPECT_EQ("example.com:443",
  16165. detail::make_host_and_port_string("example.com", 443, false));
  16166. // Edge case: Port 80 with is_ssl=true (should add port)
  16167. EXPECT_EQ("example.com:80",
  16168. detail::make_host_and_port_string("example.com", 80, true));
  16169. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16170. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16171. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16172. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16173. // Security fix: Already bracketed IPv6 should not get double brackets
  16174. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16175. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16176. EXPECT_EQ("[::1]:8080",
  16177. detail::make_host_and_port_string("[::1]", 8080, false));
  16178. EXPECT_EQ("[2001:db8::1]:8080",
  16179. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16180. EXPECT_EQ("[fe80::1%eth0]",
  16181. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16182. EXPECT_EQ("[fe80::1%eth0]:8080",
  16183. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16184. // Edge case: Empty host (should return as-is)
  16185. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16186. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16187. // This is a known limitation but shouldn't crash
  16188. EXPECT_EQ("[host:name]",
  16189. detail::make_host_and_port_string("host:name", 80, false));
  16190. // Port number edge cases (no validation, but should not crash)
  16191. EXPECT_EQ("example.com:0",
  16192. detail::make_host_and_port_string("example.com", 0, false));
  16193. EXPECT_EQ("example.com:-1",
  16194. detail::make_host_and_port_string("example.com", -1, false));
  16195. EXPECT_EQ("example.com:65535",
  16196. detail::make_host_and_port_string("example.com", 65535, false));
  16197. EXPECT_EQ("example.com:65536",
  16198. detail::make_host_and_port_string("example.com", 65536, false));
  16199. }
  16200. #ifdef CPPHTTPLIB_SSL_ENABLED
  16201. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16202. httplib::SSLClient cli("roblox.com", 443);
  16203. cli.set_follow_location(true);
  16204. auto res = cli.Get("/");
  16205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16206. EXPECT_EQ(StatusCode::OK_200, res->status);
  16207. }
  16208. #endif
  16209. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16210. Server svr;
  16211. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16212. EXPECT_EQ(res.status, 400);
  16213. });
  16214. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16215. auto se = detail::scope_exit([&] {
  16216. svr.stop();
  16217. thread.join();
  16218. ASSERT_FALSE(svr.is_running());
  16219. });
  16220. svr.wait_until_ready();
  16221. Client cli(HOST, PORT);
  16222. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16223. }
  16224. TEST(InvalidHeaderCharsTest, is_field_name) {
  16225. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16226. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16227. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16228. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16229. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16230. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16231. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16232. EXPECT_FALSE(detail::fields::is_field_name(""));
  16233. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16234. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16235. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16236. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16237. }
  16238. TEST(InvalidHeaderCharsTest, is_field_value) {
  16239. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16240. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16241. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16242. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16243. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16244. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16245. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16246. EXPECT_TRUE(detail::fields::is_field_value(""));
  16247. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16248. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16249. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16250. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16251. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16252. }
  16253. TEST(InvalidHeaderCharsTest, OnServer) {
  16254. Server svr;
  16255. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16256. std::string header = "Not Set";
  16257. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16258. res.set_header(header, "value");
  16259. res.set_content("Page Content Page Content", "text/plain");
  16260. });
  16261. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16262. std::string header = "Not Set";
  16263. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16264. res.set_header("X-Test", header);
  16265. res.set_content("Page Content Page Content", "text/plain");
  16266. });
  16267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16268. auto se = detail::scope_exit([&] {
  16269. svr.stop();
  16270. thread.join();
  16271. ASSERT_FALSE(svr.is_running());
  16272. });
  16273. svr.wait_until_ready();
  16274. Client cli(HOST, PORT);
  16275. {
  16276. auto res = cli.Get(
  16277. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16279. EXPECT_EQ("Page Content Page Content", res->body);
  16280. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16281. }
  16282. {
  16283. auto res = cli.Get(
  16284. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16286. EXPECT_EQ("Page Content Page Content", res->body);
  16287. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16288. }
  16289. }
  16290. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16291. auto handled = false;
  16292. Server svr;
  16293. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16294. thread t = thread([&] { svr.listen(HOST, PORT); });
  16295. auto se = detail::scope_exit([&] {
  16296. svr.stop();
  16297. t.join();
  16298. ASSERT_FALSE(svr.is_running());
  16299. ASSERT_FALSE(handled);
  16300. });
  16301. svr.wait_until_ready();
  16302. auto req = "POST /test HTTP/1.1\r\n"
  16303. "Content-Length: x\r\n"
  16304. "\r\n";
  16305. std::string response;
  16306. ASSERT_TRUE(send_request(1, req, &response));
  16307. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16308. response.substr(0, response.find("\r\n")));
  16309. }
  16310. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16311. // case-insensitive, and a server that receives a 100-continue expectation in
  16312. // an HTTP/1.0 request MUST ignore it.
  16313. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16314. std::string response;
  16315. ASSERT_TRUE(send_request(1, req, &response, port));
  16316. *got_100 = response.find("100 Continue") != std::string::npos;
  16317. }
  16318. class ExpectTokenTest : public ::testing::Test {
  16319. protected:
  16320. void SetUp() override {
  16321. svr_.Post("/p", [](const Request &, Response &res) {
  16322. res.set_content("ok", "text/plain");
  16323. });
  16324. port_ = svr_.bind_to_any_port(HOST);
  16325. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16326. svr_.wait_until_ready();
  16327. }
  16328. void TearDown() override {
  16329. svr_.stop();
  16330. if (thread_.joinable()) { thread_.join(); }
  16331. }
  16332. std::string request(const char *version, const char *expect_value) const {
  16333. return std::string("POST /p ") + version +
  16334. "\r\n"
  16335. "Host: localhost\r\n"
  16336. "Content-Length: 2\r\n"
  16337. "Connection: close\r\n"
  16338. "Expect: " +
  16339. expect_value +
  16340. "\r\n"
  16341. "\r\n"
  16342. "hi";
  16343. }
  16344. Server svr_;
  16345. int port_ = 0;
  16346. thread thread_;
  16347. };
  16348. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16349. bool got_100 = false;
  16350. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16351. EXPECT_TRUE(got_100);
  16352. }
  16353. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16354. bool got_100 = true;
  16355. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16356. EXPECT_FALSE(got_100);
  16357. }
  16358. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16359. bool got_100 = false;
  16360. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16361. EXPECT_TRUE(got_100);
  16362. }
  16363. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16364. bool got_100 = false;
  16365. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16366. EXPECT_TRUE(got_100);
  16367. }
  16368. // `100 Continue` is sent only when the server starts reading the body, so a
  16369. // request rejected before that never invites the client to send it. The
  16370. // requests below carry the expectation but withhold the body, as a client
  16371. // waiting for `100 Continue` would.
  16372. // A POST that expects `100 Continue` and withholds its two-byte body.
  16373. static std::string expect_headers_only(const std::string &path) {
  16374. return "POST " + path +
  16375. " HTTP/1.1\r\n"
  16376. "Host: localhost\r\n"
  16377. "Content-Length: 2\r\n"
  16378. "Expect: 100-continue\r\n"
  16379. "\r\n";
  16380. }
  16381. class ExpectLazyContinueTest : public ::testing::Test {
  16382. protected:
  16383. void SetUp() override {
  16384. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16385. if (req.path == "/pre-routing") {
  16386. res.status = StatusCode::Unauthorized_401;
  16387. return Server::HandlerResponse::Handled;
  16388. }
  16389. return Server::HandlerResponse::Unhandled;
  16390. });
  16391. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16392. if (req.matched_route == "/pre-request") {
  16393. res.status = StatusCode::Forbidden_403;
  16394. return Server::HandlerResponse::Handled;
  16395. }
  16396. return Server::HandlerResponse::Unhandled;
  16397. });
  16398. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16399. res.set_content("ok", "text/plain");
  16400. });
  16401. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16402. res.set_content("ok", "text/plain");
  16403. });
  16404. svr_.Post("/reader-used", [](const Request &, Response &res,
  16405. const ContentReader &content_reader) {
  16406. std::string body;
  16407. content_reader([&](const char *data, size_t len) {
  16408. body.append(data, len);
  16409. return true;
  16410. });
  16411. res.set_content(body, "text/plain");
  16412. });
  16413. svr_.Post("/reader-unused",
  16414. [](const Request &, Response &res, const ContentReader &) {
  16415. res.set_content("ignored", "text/plain");
  16416. });
  16417. port_ = svr_.bind_to_any_port(HOST);
  16418. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16419. svr_.wait_until_ready();
  16420. }
  16421. void TearDown() override {
  16422. svr_.stop();
  16423. if (thread_.joinable()) { thread_.join(); }
  16424. }
  16425. // Sends `req` and reads until the server closes the connection. Returns
  16426. // false if the read had to wait for the client-side timeout instead.
  16427. bool send_until_closed(const std::string &req, std::string *resp) const {
  16428. auto start = std::chrono::steady_clock::now();
  16429. if (!send_request(3, req, resp, port_)) { return false; }
  16430. auto elapsed = std::chrono::steady_clock::now() - start;
  16431. return elapsed < std::chrono::seconds(2);
  16432. }
  16433. // The final response comes without `100 Continue`, and the server closes
  16434. // the connection since the body may or may not follow.
  16435. void expect_final_without_interim(const std::string &path,
  16436. const char *status_line) const {
  16437. std::string resp;
  16438. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16439. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16440. EXPECT_EQ(0u, resp.find(status_line));
  16441. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16442. }
  16443. Server svr_;
  16444. int port_ = 0;
  16445. thread thread_;
  16446. };
  16447. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16448. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16449. }
  16450. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16451. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16452. }
  16453. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16454. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16455. }
  16456. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16457. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16458. }
  16459. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16460. // The body follows once `100 Continue` has had time to arrive.
  16461. auto req = expect_headers_only("/reader-used");
  16462. req.insert(req.size() - 2, "Connection: close\r\n");
  16463. std::string resp;
  16464. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16465. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16466. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16467. EXPECT_NE(std::string::npos, resp.find("hi"));
  16468. }
  16469. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16470. // Large enough for the client to add `Expect: 100-continue` itself.
  16471. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16472. std::atomic<bool> body_sent{false};
  16473. Client cli(HOST, port_);
  16474. auto res = cli.Post(
  16475. "/pre-request", length,
  16476. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16477. body_sent = true;
  16478. std::string chunk(len, 'x');
  16479. sink.write(chunk.data(), chunk.size());
  16480. return true;
  16481. },
  16482. "application/octet-stream");
  16483. ASSERT_TRUE(res);
  16484. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16485. EXPECT_FALSE(body_sent);
  16486. }
  16487. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16488. Server svr;
  16489. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16490. return StatusCode::ExpectationFailed_417;
  16491. });
  16492. svr.Post("/p", [](const Request &, Response &res) {
  16493. res.set_content("ok", "text/plain");
  16494. });
  16495. auto port = svr.bind_to_any_port(HOST);
  16496. thread t = thread([&] { svr.listen_after_bind(); });
  16497. auto se = detail::scope_exit([&] {
  16498. svr.stop();
  16499. t.join();
  16500. });
  16501. svr.wait_until_ready();
  16502. std::string resp;
  16503. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16504. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16505. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16506. // Exactly one response: the route handler must not run after the 417.
  16507. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16508. }
  16509. #ifndef _WIN32
  16510. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16511. static constexpr char reject[] = "Unauthorized";
  16512. static constexpr char accept[] = "Upload accepted";
  16513. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16514. Server svr;
  16515. svr.set_expect_100_continue_handler(
  16516. [](const Request & /*req*/, Response &res) {
  16517. res.status = StatusCode::Unauthorized_401;
  16518. res.set_content(reject, "text/plain");
  16519. return res.status;
  16520. });
  16521. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16522. res.set_content(accept, "text/plain");
  16523. });
  16524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16525. auto se = detail::scope_exit([&] {
  16526. svr.stop();
  16527. thread.join();
  16528. ASSERT_FALSE(svr.is_running());
  16529. });
  16530. svr.wait_until_ready();
  16531. {
  16532. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16533. curl_easy_init(), &curl_easy_cleanup};
  16534. ASSERT_NE(curl, nullptr);
  16535. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16536. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16537. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16538. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16539. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16540. &curl_slist_free_all};
  16541. ASSERT_NE(list, nullptr);
  16542. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16543. struct read_data {
  16544. size_t read_size;
  16545. size_t total_size;
  16546. } data = {0, total_size};
  16547. using read_callback_t =
  16548. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16549. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16550. void *userdata) -> size_t {
  16551. read_data *d = (read_data *)userdata;
  16552. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16553. std::fill_n(ptr, size * nmemb, 'A');
  16554. d->read_size += size * nmemb;
  16555. return size * nmemb;
  16556. };
  16557. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16558. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16559. std::vector<char> buffer;
  16560. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16561. using write_callback_t =
  16562. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16563. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16564. void *userdata) -> size_t {
  16565. std::vector<char> *buf = (std::vector<char> *)userdata;
  16566. buf->reserve(buf->size() + size * nmemb + 1);
  16567. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16568. return size * nmemb;
  16569. };
  16570. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16571. {
  16572. const auto res = curl_easy_perform(curl.get());
  16573. ASSERT_EQ(res, CURLE_OK);
  16574. }
  16575. {
  16576. auto response_code = long{};
  16577. const auto res =
  16578. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16579. ASSERT_EQ(res, CURLE_OK);
  16580. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16581. }
  16582. {
  16583. auto dl = curl_off_t{};
  16584. const auto res =
  16585. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16586. ASSERT_EQ(res, CURLE_OK);
  16587. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16588. }
  16589. {
  16590. buffer.push_back('\0');
  16591. ASSERT_STRCASEEQ(buffer.data(), reject);
  16592. }
  16593. }
  16594. }
  16595. #endif
  16596. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16597. // Regression test for #2458.
  16598. //
  16599. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16600. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16601. // ticket can make the client socket spuriously readable during the
  16602. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16603. // the client withholds the body and then blocks reading a response that never
  16604. // comes, failing with `Failed to read connection`.
  16605. //
  16606. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16607. // within the timeout. This raw OpenSSL server deliberately never sends
  16608. // `100 Continue`; the client must still deliver the body and receive 200.
  16609. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16610. signal(SIGPIPE, SIG_IGN);
  16611. const auto port = PORT + 4;
  16612. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16613. ASSERT_NE(srv, INVALID_SOCKET);
  16614. int opt = 1;
  16615. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16616. sockaddr_in addr{};
  16617. addr.sin_family = AF_INET;
  16618. addr.sin_port = htons(static_cast<uint16_t>(port));
  16619. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16620. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16621. ASSERT_EQ(0, ::listen(srv, 1));
  16622. std::atomic<size_t> server_body_bytes{0};
  16623. auto server_thread = std::thread([&] {
  16624. sockaddr_in cli_addr{};
  16625. socklen_t cli_len = sizeof(cli_addr);
  16626. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16627. if (cli == INVALID_SOCKET) { return; }
  16628. // Bound the lifetime of the server side so a buggy client (which never
  16629. // sends the body) cannot make this thread block forever on join.
  16630. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16631. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16632. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16633. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16634. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16635. SSL *ssl = SSL_new(ctx);
  16636. SSL_set_fd(ssl, static_cast<int>(cli));
  16637. if (SSL_accept(ssl) > 0) {
  16638. // Read the request headers. Reading here also flushes the TLS 1.3
  16639. // session tickets to the client. Deliberately do NOT send
  16640. // `100 Continue`.
  16641. std::string buf;
  16642. char tmp[1024];
  16643. while (buf.find("\r\n\r\n") == std::string::npos) {
  16644. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16645. if (n <= 0) { break; }
  16646. buf.append(tmp, static_cast<size_t>(n));
  16647. }
  16648. // A correct client sends the body now; count what arrives.
  16649. auto pos = buf.find("\r\n\r\n");
  16650. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16651. while (body < 4096) {
  16652. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16653. if (n <= 0) { break; }
  16654. body += static_cast<size_t>(n);
  16655. }
  16656. server_body_bytes = body;
  16657. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16658. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16659. SSL_shutdown(ssl);
  16660. }
  16661. SSL_free(ssl);
  16662. detail::close_socket(cli);
  16663. SSL_CTX_free(ctx);
  16664. });
  16665. auto se = detail::scope_exit([&] {
  16666. server_thread.join();
  16667. detail::close_socket(srv);
  16668. });
  16669. SSLClient cli("127.0.0.1", port);
  16670. cli.enable_server_certificate_verification(false);
  16671. cli.set_connection_timeout(5, 0);
  16672. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16673. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16674. std::string body(4096, 'A');
  16675. auto res = cli.Put("/api/test", body, "application/json");
  16676. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16677. EXPECT_EQ(StatusCode::OK_200, res->status);
  16678. EXPECT_EQ(body.size(), server_body_bytes.load());
  16679. }
  16680. #endif
  16681. template <typename S, typename C>
  16682. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16683. svr.Get("/stream", [&](const Request &, Response &res) {
  16684. auto data = new std::string("01234567890123456789");
  16685. res.set_content_provider(
  16686. data->size(), "text/plain",
  16687. [&, data](size_t offset, size_t length, DataSink &sink) {
  16688. const size_t DATA_CHUNK_SIZE = 4;
  16689. const auto &d = *data;
  16690. std::this_thread::sleep_for(std::chrono::seconds(1));
  16691. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16692. return true;
  16693. },
  16694. [data](bool success) {
  16695. EXPECT_FALSE(success);
  16696. delete data;
  16697. });
  16698. });
  16699. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16700. auto i = new size_t(0);
  16701. res.set_content_provider(
  16702. "text/plain",
  16703. [i](size_t, DataSink &sink) {
  16704. if (*i < 5) {
  16705. std::this_thread::sleep_for(std::chrono::seconds(1));
  16706. sink.write("abcd", 4);
  16707. (*i)++;
  16708. } else {
  16709. sink.done();
  16710. }
  16711. return true;
  16712. },
  16713. [i](bool success) {
  16714. EXPECT_FALSE(success);
  16715. delete i;
  16716. });
  16717. });
  16718. svr.Get("/chunked", [&](const Request &, Response &res) {
  16719. auto i = new size_t(0);
  16720. res.set_chunked_content_provider(
  16721. "text/plain",
  16722. [i](size_t, DataSink &sink) {
  16723. if (*i < 5) {
  16724. std::this_thread::sleep_for(std::chrono::seconds(1));
  16725. sink.os << "abcd";
  16726. (*i)++;
  16727. } else {
  16728. sink.done();
  16729. }
  16730. return true;
  16731. },
  16732. [i](bool success) {
  16733. EXPECT_FALSE(success);
  16734. delete i;
  16735. });
  16736. });
  16737. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16738. auto se = detail::scope_exit([&] {
  16739. svr.stop();
  16740. listen_thread.join();
  16741. ASSERT_FALSE(svr.is_running());
  16742. });
  16743. svr.wait_until_ready();
  16744. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16745. {
  16746. auto start = std::chrono::steady_clock::now();
  16747. auto res = cli.Get("/stream");
  16748. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16749. std::chrono::steady_clock::now() - start)
  16750. .count();
  16751. ASSERT_FALSE(res);
  16752. EXPECT_EQ(Error::Read, res.error());
  16753. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16754. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16755. }
  16756. {
  16757. auto start = std::chrono::steady_clock::now();
  16758. auto res = cli.Get("/stream_without_length");
  16759. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16760. std::chrono::steady_clock::now() - start)
  16761. .count();
  16762. ASSERT_FALSE(res);
  16763. EXPECT_EQ(Error::Read, res.error());
  16764. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16765. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16766. }
  16767. {
  16768. auto start = std::chrono::steady_clock::now();
  16769. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16770. EXPECT_EQ("abcd", string(data, data_length));
  16771. return true;
  16772. });
  16773. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16774. std::chrono::steady_clock::now() - start)
  16775. .count();
  16776. ASSERT_FALSE(res);
  16777. EXPECT_EQ(Error::Read, res.error());
  16778. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16779. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16780. }
  16781. }
  16782. TEST(MaxTimeoutTest, ContentStream) {
  16783. time_t timeout = 2000;
  16784. time_t threshold = 200;
  16785. Server svr;
  16786. Client cli("localhost", PORT);
  16787. max_timeout_test(svr, cli, timeout, threshold);
  16788. }
  16789. #ifdef CPPHTTPLIB_SSL_ENABLED
  16790. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16791. time_t timeout = 2000;
  16792. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16794. SSLClient cli("localhost", PORT);
  16795. cli.enable_server_certificate_verification(false);
  16796. max_timeout_test(svr, cli, timeout, threshold);
  16797. }
  16798. #endif
  16799. class EventDispatcher {
  16800. public:
  16801. EventDispatcher() {}
  16802. bool wait_event(DataSink *sink) {
  16803. unique_lock<mutex> lk(m_);
  16804. int id = id_;
  16805. // Wait with timeout to prevent hanging if client disconnects
  16806. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16807. [&] { return cid_ == id; })) {
  16808. return false; // Timeout occurred
  16809. }
  16810. sink->write(message_.data(), message_.size());
  16811. return true;
  16812. }
  16813. void send_event(const string &message) {
  16814. lock_guard<mutex> lk(m_);
  16815. cid_ = id_++;
  16816. message_ = message;
  16817. cv_.notify_all();
  16818. }
  16819. private:
  16820. mutex m_;
  16821. condition_variable cv_;
  16822. atomic_int id_{0};
  16823. atomic_int cid_{-1};
  16824. string message_;
  16825. };
  16826. TEST(ClientInThreadTest, Issue2068) {
  16827. EventDispatcher ed;
  16828. Server svr;
  16829. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16830. res.set_chunked_content_provider("text/event-stream",
  16831. [&](size_t /*offset*/, DataSink &sink) {
  16832. return ed.wait_event(&sink);
  16833. });
  16834. });
  16835. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16836. svr.wait_until_ready();
  16837. thread event_thread([&] {
  16838. int id = 0;
  16839. while (svr.is_running()) {
  16840. this_thread::sleep_for(chrono::milliseconds(500));
  16841. std::stringstream ss;
  16842. ss << "data: " << id << "\n\n";
  16843. ed.send_event(ss.str());
  16844. id++;
  16845. }
  16846. });
  16847. auto se = detail::scope_exit([&] {
  16848. svr.stop();
  16849. listen_thread.join();
  16850. event_thread.join();
  16851. ASSERT_FALSE(svr.is_running());
  16852. });
  16853. {
  16854. auto client = detail::make_unique<Client>(HOST, PORT);
  16855. client->set_read_timeout(std::chrono::minutes(10));
  16856. std::atomic<bool> stop{false};
  16857. std::thread t([&] {
  16858. client->Get("/event1",
  16859. [&](const char *, size_t) -> bool { return !stop; });
  16860. });
  16861. std::this_thread::sleep_for(std::chrono::seconds(2));
  16862. stop = true;
  16863. client->stop();
  16864. t.join();
  16865. // Reset client after thread has finished
  16866. client.reset();
  16867. }
  16868. }
  16869. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16870. auto handled = false;
  16871. Server svr;
  16872. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16874. auto se = detail::scope_exit([&] {
  16875. svr.stop();
  16876. t.join();
  16877. ASSERT_FALSE(svr.is_running());
  16878. ASSERT_FALSE(handled);
  16879. });
  16880. svr.wait_until_ready();
  16881. // Two Content-Length headers with different values — must be rejected
  16882. auto req = "POST /test HTTP/1.1\r\n"
  16883. "Content-Length: 5\r\n"
  16884. "Content-Length: 10\r\n"
  16885. "\r\n"
  16886. "hello";
  16887. std::string response;
  16888. ASSERT_TRUE(send_request(1, req, &response));
  16889. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16890. response.substr(0, response.find("\r\n")));
  16891. }
  16892. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16893. auto handled = false;
  16894. Server svr;
  16895. svr.Post("/test", [&](const Request &, Response &res) {
  16896. handled = true;
  16897. res.set_content("ok", "text/plain");
  16898. });
  16899. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16900. auto se = detail::scope_exit([&] {
  16901. svr.stop();
  16902. t.join();
  16903. ASSERT_FALSE(svr.is_running());
  16904. ASSERT_TRUE(handled);
  16905. });
  16906. svr.wait_until_ready();
  16907. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16908. auto req = "POST /test HTTP/1.1\r\n"
  16909. "Content-Length: 5\r\n"
  16910. "Content-Length: 5\r\n"
  16911. "\r\n"
  16912. "hello";
  16913. std::string response;
  16914. ASSERT_TRUE(send_request(1, req, &response));
  16915. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16916. }
  16917. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16918. Server svr;
  16919. svr.Get("/test", [](const Request &, Response &res) {
  16920. res.set_content("ok", "text/plain");
  16921. });
  16922. auto port = svr.bind_to_any_port(HOST);
  16923. thread t = thread([&] { svr.listen_after_bind(); });
  16924. auto se = detail::scope_exit([&] {
  16925. svr.stop();
  16926. t.join();
  16927. ASSERT_FALSE(svr.is_running());
  16928. });
  16929. svr.wait_until_ready();
  16930. auto status_line = [&](const std::string &host_lines) {
  16931. std::string res;
  16932. send_request(
  16933. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16934. &res, port);
  16935. return res.substr(0, res.find("\r\n"));
  16936. };
  16937. const char *accepted[] = {
  16938. "Host: localhost\r\n",
  16939. "Host: a.example:8080\r\n",
  16940. "Host: my_service\r\n",
  16941. "Host: [::1]:8080\r\n",
  16942. "Host: [fe80::1%25eth0]\r\n",
  16943. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16944. };
  16945. for (auto host_lines : accepted) {
  16946. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16947. }
  16948. const char *rejected[] = {
  16949. "Host: a.example\r\nHost: b.example\r\n",
  16950. "Host: a.example\r\nHost: a.example\r\n",
  16951. "Host: a@b.example\r\n",
  16952. "Host: a.example/b\r\n",
  16953. "Host: a.example\\b\r\n",
  16954. "Host: a.example?b\r\n",
  16955. "Host: a.example#b\r\n",
  16956. "Host: a.example b.example\r\n",
  16957. };
  16958. for (auto host_lines : rejected) {
  16959. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16960. << host_lines;
  16961. }
  16962. }
  16963. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16964. Server svr;
  16965. svr.Get("/", [](const Request &req, Response &res) {
  16966. EXPECT_EQ(2U, req.trailers.size());
  16967. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16968. // Denied
  16969. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16970. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16971. // Accepted
  16972. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16973. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16974. EXPECT_TRUE(req.has_trailer("X-World"));
  16975. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16976. res.set_content("ok", "text/plain");
  16977. });
  16978. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16979. auto se = detail::scope_exit([&] {
  16980. svr.stop();
  16981. t.join();
  16982. ASSERT_FALSE(svr.is_running());
  16983. });
  16984. svr.wait_until_ready();
  16985. const std::string req = "GET / HTTP/1.1\r\n"
  16986. "Transfer-Encoding: chunked\r\n"
  16987. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16988. "\r\n"
  16989. "0\r\n"
  16990. "Content-Length: 10\r\n"
  16991. "Host: internal.local\r\n"
  16992. "Content-Type: malicious/content\r\n"
  16993. "Cookie: any\r\n"
  16994. "Set-Cookie: any\r\n"
  16995. "X-Forwarded-For: attacker.com\r\n"
  16996. "X-Real-Ip: 1.1.1.1\r\n"
  16997. "X-Hello: hello\r\n"
  16998. "X-World: world\r\n"
  16999. "\r\n";
  17000. std::string res;
  17001. ASSERT_TRUE(send_request(1, req, &res));
  17002. }
  17003. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17004. // several field lines, and the combined value is what has to be parsed. A
  17005. // Trailer field split across lines therefore declares every name it lists;
  17006. // reading only the first line silently drops the trailers the later lines
  17007. // declare. The prohibited-trailer filter still applies to every line.
  17008. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17009. Server svr;
  17010. size_t observed_trailer_count = 0;
  17011. std::string observed_hello;
  17012. std::string observed_world;
  17013. bool observed_content_length = true;
  17014. svr.Get("/", [&](const Request &req, Response &res) {
  17015. observed_trailer_count = req.trailers.size();
  17016. observed_hello = req.get_trailer_value("X-Hello");
  17017. observed_world = req.get_trailer_value("X-World");
  17018. observed_content_length = req.has_trailer("Content-Length");
  17019. res.set_content("ok", "text/plain");
  17020. });
  17021. auto port = svr.bind_to_any_port(HOST);
  17022. thread t = thread([&]() { svr.listen_after_bind(); });
  17023. auto se = detail::scope_exit([&] {
  17024. svr.stop();
  17025. t.join();
  17026. ASSERT_FALSE(svr.is_running());
  17027. });
  17028. svr.wait_until_ready();
  17029. const std::string req = "GET / HTTP/1.1\r\n"
  17030. "Transfer-Encoding: chunked\r\n"
  17031. "Trailer: X-Hello\r\n"
  17032. "Trailer: X-World, Content-Length\r\n"
  17033. "\r\n"
  17034. "0\r\n"
  17035. "X-Hello: hello\r\n"
  17036. "X-World: world\r\n"
  17037. "Content-Length: 10\r\n"
  17038. "\r\n";
  17039. std::string res;
  17040. ASSERT_TRUE(send_request(1, req, &res, port));
  17041. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17042. // Accepted: both field lines contribute to the declared set
  17043. EXPECT_EQ(2U, observed_trailer_count);
  17044. EXPECT_EQ(observed_hello, "hello");
  17045. EXPECT_EQ(observed_world, "world");
  17046. // Denied: a prohibited name stays prohibited on a later field line
  17047. EXPECT_FALSE(observed_content_length);
  17048. }
  17049. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17050. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17051. // unbounded run of fields that are never declared, because the counter would
  17052. // only advance for declared fields.
  17053. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17054. Server svr;
  17055. bool handler_called = false;
  17056. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17057. handler_called = true;
  17058. res.set_content("ok", "text/plain");
  17059. });
  17060. auto port = svr.bind_to_any_port(HOST);
  17061. thread t = thread([&]() { svr.listen_after_bind(); });
  17062. auto se = detail::scope_exit([&] {
  17063. svr.stop();
  17064. t.join();
  17065. ASSERT_FALSE(svr.is_running());
  17066. });
  17067. svr.wait_until_ready();
  17068. // Declare nothing, then send far more undeclared trailer fields than the
  17069. // header-count limit. Parsing must stop and reject the request rather than
  17070. // read every line.
  17071. std::string req = "GET / HTTP/1.1\r\n"
  17072. "Transfer-Encoding: chunked\r\n"
  17073. "\r\n"
  17074. "0\r\n";
  17075. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17076. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17077. }
  17078. req += "\r\n";
  17079. std::string res;
  17080. ASSERT_TRUE(send_request(1, req, &res, port));
  17081. // The request is rejected before the handler runs.
  17082. EXPECT_FALSE(handler_called);
  17083. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17084. }
  17085. // The set of declared trailer names is capped so a peer cannot grow it without
  17086. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17087. // declared past the cap is not honored, even if the field is actually sent.
  17088. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17089. Server svr;
  17090. // One name inside the cap and one past it, so the test tracks the cap rather
  17091. // than a fixed count.
  17092. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17093. const std::string within_cap_name = "X-T-0";
  17094. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17095. bool observed_within_cap = false;
  17096. bool observed_past_cap = false;
  17097. svr.Get("/", [&](const Request &req, Response &res) {
  17098. observed_within_cap = req.has_trailer(within_cap_name);
  17099. observed_past_cap = req.has_trailer(past_cap_name);
  17100. res.set_content("ok", "text/plain");
  17101. });
  17102. auto port = svr.bind_to_any_port(HOST);
  17103. thread t = thread([&]() { svr.listen_after_bind(); });
  17104. auto se = detail::scope_exit([&] {
  17105. svr.stop();
  17106. t.join();
  17107. ASSERT_FALSE(svr.is_running());
  17108. });
  17109. svr.wait_until_ready();
  17110. // Declare more trailer names than the cap in a single Trailer field, then
  17111. // actually send the first (within the cap) and the last (past it).
  17112. std::string trailer_decl = "Trailer: ";
  17113. for (int i = 0; i < declared_count; i++) {
  17114. if (i != 0) { trailer_decl += ", "; }
  17115. trailer_decl += "X-T-" + std::to_string(i);
  17116. }
  17117. trailer_decl += "\r\n";
  17118. const std::string req = "GET / HTTP/1.1\r\n"
  17119. "Transfer-Encoding: chunked\r\n" +
  17120. trailer_decl +
  17121. "\r\n"
  17122. "0\r\n" +
  17123. within_cap_name + ": a\r\n" + past_cap_name +
  17124. ": b\r\n"
  17125. "\r\n";
  17126. std::string res;
  17127. ASSERT_TRUE(send_request(1, req, &res, port));
  17128. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17129. // A name within the cap is honored; one declared past the cap is dropped.
  17130. EXPECT_TRUE(observed_within_cap);
  17131. EXPECT_FALSE(observed_past_cap);
  17132. }
  17133. // A direct client that is not listed in trusted_proxies must not be able to
  17134. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17135. // the peer address on the actual TCP connection determines whether the
  17136. // header is honored.
  17137. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17138. Server svr;
  17139. // Deliberately does NOT include the loopback address the test client
  17140. // actually connects from, so the direct connection is not a trusted proxy.
  17141. svr.set_trusted_proxies({"203.0.113.66"});
  17142. std::string observed_remote_addr;
  17143. svr.Get("/ip", [&](const Request &req, Response &res) {
  17144. observed_remote_addr = req.remote_addr;
  17145. res.set_content("ok", "text/plain");
  17146. });
  17147. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17148. auto se = detail::scope_exit([&] {
  17149. svr.stop();
  17150. t.join();
  17151. ASSERT_FALSE(svr.is_running());
  17152. });
  17153. svr.wait_until_ready();
  17154. Client cli(HOST, PORT);
  17155. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17157. EXPECT_EQ(StatusCode::OK_200, res->status);
  17158. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17159. // ignored entirely and the real connection-level address retained.
  17160. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17161. observed_remote_addr == "127.0.0.1");
  17162. }
  17163. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17164. Server svr;
  17165. std::string observed_remote_addr;
  17166. std::string observed_xff;
  17167. svr.Get("/ip", [&](const Request &req, Response &res) {
  17168. observed_remote_addr = req.remote_addr;
  17169. observed_xff = req.get_header_value("X-Forwarded-For");
  17170. res.set_content("ok", "text/plain");
  17171. });
  17172. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17173. auto se = detail::scope_exit([&] {
  17174. svr.stop();
  17175. t.join();
  17176. ASSERT_FALSE(svr.is_running());
  17177. });
  17178. svr.wait_until_ready();
  17179. Client cli(HOST, PORT);
  17180. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17182. EXPECT_EQ(StatusCode::OK_200, res->status);
  17183. EXPECT_EQ(observed_xff, "203.0.113.66");
  17184. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17185. observed_remote_addr == "127.0.0.1");
  17186. }
  17187. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17188. Server svr;
  17189. svr.set_trusted_proxies({"203.0.113.66"});
  17190. std::string observed_remote_addr;
  17191. std::string observed_xff;
  17192. svr.Get("/ip", [&](const Request &req, Response &res) {
  17193. observed_remote_addr = req.remote_addr;
  17194. observed_xff = req.get_header_value("X-Forwarded-For");
  17195. res.set_content("ok", "text/plain");
  17196. });
  17197. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17198. auto se = detail::scope_exit([&] {
  17199. svr.stop();
  17200. t.join();
  17201. ASSERT_FALSE(svr.is_running());
  17202. });
  17203. svr.wait_until_ready();
  17204. Client cli(HOST, PORT);
  17205. auto res = cli.Get("/ip");
  17206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17207. EXPECT_EQ(StatusCode::OK_200, res->status);
  17208. EXPECT_EQ(observed_xff, "");
  17209. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17210. observed_remote_addr == "127.0.0.1");
  17211. }
  17212. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17213. Server svr;
  17214. // Include the loopback address the test client actually connects from, so
  17215. // the direct connection itself is recognized as the trusted proxy hop.
  17216. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17217. std::string observed_remote_addr;
  17218. std::string observed_xff;
  17219. svr.Get("/ip", [&](const Request &req, Response &res) {
  17220. observed_remote_addr = req.remote_addr;
  17221. observed_xff = req.get_header_value("X-Forwarded-For");
  17222. res.set_content("ok", "text/plain");
  17223. });
  17224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17225. auto se = detail::scope_exit([&] {
  17226. svr.stop();
  17227. t.join();
  17228. ASSERT_FALSE(svr.is_running());
  17229. });
  17230. svr.wait_until_ready();
  17231. Client cli(HOST, PORT);
  17232. auto res = cli.Get(
  17233. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17235. EXPECT_EQ(StatusCode::OK_200, res->status);
  17236. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17237. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17238. }
  17239. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17240. Server svr;
  17241. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17242. std::string observed_remote_addr;
  17243. std::string observed_xff;
  17244. svr.Get("/ip", [&](const Request &req, Response &res) {
  17245. observed_remote_addr = req.remote_addr;
  17246. observed_xff = req.get_header_value("X-Forwarded-For");
  17247. res.set_content("ok", "text/plain");
  17248. });
  17249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17250. auto se = detail::scope_exit([&] {
  17251. svr.stop();
  17252. t.join();
  17253. ASSERT_FALSE(svr.is_running());
  17254. });
  17255. svr.wait_until_ready();
  17256. Client cli(HOST, PORT);
  17257. auto res = cli.Get(
  17258. "/ip",
  17259. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17261. EXPECT_EQ(StatusCode::OK_200, res->status);
  17262. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17263. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17264. }
  17265. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17266. Server svr;
  17267. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17268. std::string observed_remote_addr;
  17269. std::string observed_xff;
  17270. svr.Get("/ip", [&](const Request &req, Response &res) {
  17271. observed_remote_addr = req.remote_addr;
  17272. observed_xff = req.get_header_value("X-Forwarded-For");
  17273. res.set_content("ok", "text/plain");
  17274. });
  17275. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17276. auto se = detail::scope_exit([&] {
  17277. svr.stop();
  17278. t.join();
  17279. ASSERT_FALSE(svr.is_running());
  17280. });
  17281. svr.wait_until_ready();
  17282. Client cli(HOST, PORT);
  17283. auto res = cli.Get(
  17284. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17286. EXPECT_EQ(StatusCode::OK_200, res->status);
  17287. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17288. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17289. // and must not be selected.
  17290. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17291. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17292. }
  17293. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17294. Server svr;
  17295. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17296. std::string observed_remote_addr;
  17297. svr.Get("/ip", [&](const Request &req, Response &res) {
  17298. observed_remote_addr = req.remote_addr;
  17299. res.set_content("ok", "text/plain");
  17300. });
  17301. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17302. auto se = detail::scope_exit([&] {
  17303. svr.stop();
  17304. t.join();
  17305. ASSERT_FALSE(svr.is_running());
  17306. });
  17307. svr.wait_until_ready();
  17308. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17309. // a forged address and the trusted proxy's own address; the forged value must
  17310. // not win over the address the trusted proxy actually recorded.
  17311. Client cli(HOST, PORT);
  17312. auto res = cli.Get(
  17313. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17315. EXPECT_EQ(StatusCode::OK_200, res->status);
  17316. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17317. }
  17318. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17319. Server svr;
  17320. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17321. std::string observed_remote_addr;
  17322. std::string observed_xff;
  17323. svr.Get("/ip", [&](const Request &req, Response &res) {
  17324. observed_remote_addr = req.remote_addr;
  17325. observed_xff = req.get_header_value("X-Forwarded-For");
  17326. res.set_content("ok", "text/plain");
  17327. });
  17328. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17329. auto se = detail::scope_exit([&] {
  17330. svr.stop();
  17331. t.join();
  17332. ASSERT_FALSE(svr.is_running());
  17333. });
  17334. svr.wait_until_ready();
  17335. Client cli(HOST, PORT);
  17336. auto res = cli.Get(
  17337. "/ip",
  17338. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17340. EXPECT_EQ(StatusCode::OK_200, res->status);
  17341. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17342. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17343. }
  17344. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17345. Server svr;
  17346. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17347. std::string observed_remote_addr;
  17348. std::string observed_xff;
  17349. svr.Get("/ip", [&](const Request &req, Response &res) {
  17350. observed_remote_addr = req.remote_addr;
  17351. observed_xff = req.get_header_value("X-Forwarded-For");
  17352. res.set_content("ok", "text/plain");
  17353. });
  17354. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17355. auto se = detail::scope_exit([&] {
  17356. svr.stop();
  17357. t.join();
  17358. ASSERT_FALSE(svr.is_running());
  17359. });
  17360. svr.wait_until_ready();
  17361. std::string raw_req =
  17362. "GET /ip HTTP/1.1\r\n"
  17363. "Host: localhost\r\n"
  17364. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17365. "Connection: close\r\n"
  17366. "\r\n";
  17367. std::string out;
  17368. ASSERT_TRUE(send_request(5, raw_req, &out));
  17369. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17370. // Header parser trims surrounding whitespace of the header value
  17371. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17372. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17373. }
  17374. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17375. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17376. // their own X-Forwarded-For as a separate field line rather than extending the
  17377. // one the client sent, so every occurrence has to be taken into account.
  17378. // Reading only the first one hands back the address the client chose.
  17379. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17380. Server svr;
  17381. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17382. std::string observed_remote_addr;
  17383. size_t observed_xff_count = 0;
  17384. svr.Get("/ip", [&](const Request &req, Response &res) {
  17385. observed_remote_addr = req.remote_addr;
  17386. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17387. res.set_content("ok", "text/plain");
  17388. });
  17389. auto port = svr.bind_to_any_port(HOST);
  17390. thread t = thread([&]() { svr.listen_after_bind(); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. t.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. svr.wait_until_ready();
  17397. // The client supplies the first field line; the trusted proxy appends the
  17398. // address it observed as a second one.
  17399. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17400. "Host: localhost\r\n"
  17401. "X-Forwarded-For: 1.2.3.4\r\n"
  17402. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17403. "Connection: close\r\n"
  17404. "\r\n";
  17405. std::string out;
  17406. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17407. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17408. EXPECT_EQ(observed_xff_count, 2U);
  17409. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17410. // The same chain spread over one field line per hop derives the same client
  17411. // address, i.e. the split and the comma-joined representations agree.
  17412. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17413. "Host: localhost\r\n"
  17414. "X-Forwarded-For: 1.2.3.4\r\n"
  17415. "X-Forwarded-For: 198.51.100.23\r\n"
  17416. "X-Forwarded-For: 192.0.2.45\r\n"
  17417. "Connection: close\r\n"
  17418. "\r\n";
  17419. out.clear();
  17420. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17421. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17422. EXPECT_EQ(observed_xff_count, 3U);
  17423. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17424. }
  17425. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17426. // crash the server (it used to call front() on an empty vector inside
  17427. // get_client_ip). The connection-level remote address must be retained instead.
  17428. static void run_malformed_xff_test(const std::string &xff_value) {
  17429. Server svr;
  17430. svr.set_trusted_proxies({"192.0.2.45"});
  17431. std::string observed_remote_addr;
  17432. svr.Get("/ip", [&](const Request &req, Response &res) {
  17433. observed_remote_addr = req.remote_addr;
  17434. res.set_content("ok", "text/plain");
  17435. });
  17436. int port = 0;
  17437. thread t = thread([&]() {
  17438. port = svr.bind_to_any_port(HOST);
  17439. svr.listen_after_bind();
  17440. });
  17441. auto se = detail::scope_exit([&] {
  17442. svr.stop();
  17443. t.join();
  17444. ASSERT_FALSE(svr.is_running());
  17445. });
  17446. svr.wait_until_ready();
  17447. Client cli(HOST, port);
  17448. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17450. EXPECT_EQ(StatusCode::OK_200, res->status);
  17451. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17452. observed_remote_addr == "127.0.0.1");
  17453. }
  17454. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17455. run_malformed_xff_test("");
  17456. }
  17457. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17458. run_malformed_xff_test(",");
  17459. }
  17460. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17461. run_malformed_xff_test(", , ,");
  17462. }
  17463. // The same rule applies to Accept: a request whose acceptable types are spread
  17464. // over several field lines must be negotiated against all of them.
  17465. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17466. // case-insensitive connection options. Comparing the whole field value against
  17467. // one option misses a client that sends several of them, and misses every
  17468. // casing but the one written in the comparison.
  17469. //
  17470. // Sends req, reads the response, then reuses the same socket for a second
  17471. // request to find out whether the server kept the connection.
  17472. static void probe_connection_reuse(int port, const std::string &req,
  17473. bool *announced_close, bool *reusable) {
  17474. auto error = Error::Success;
  17475. auto sock = detail::create_client_socket(
  17476. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17477. /*connection_timeout_sec=*/5, 0,
  17478. /*read_timeout_sec=*/1, 0,
  17479. /*write_timeout_sec=*/5, 0, std::string(), error);
  17480. ASSERT_NE(sock, INVALID_SOCKET);
  17481. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17482. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17483. "Host: localhost\r\n"
  17484. "Connection: close\r\n"
  17485. "\r\n";
  17486. std::string first_response;
  17487. std::string second_response;
  17488. detail::process_client_socket(
  17489. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17490. [&](Stream &strm) {
  17491. if (strm.write(req.data(), req.size()) !=
  17492. static_cast<ssize_t>(req.size())) {
  17493. return false;
  17494. }
  17495. char buf[512];
  17496. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17497. // Headers plus the two-byte body of the handler below
  17498. while (reader.getline()) {
  17499. first_response += reader.ptr();
  17500. if (first_response.find("ok") != std::string::npos) { break; }
  17501. }
  17502. if (strm.write(second.data(), second.size()) !=
  17503. static_cast<ssize_t>(second.size())) {
  17504. return true;
  17505. }
  17506. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17507. while (reader2.getline()) {
  17508. second_response += reader2.ptr();
  17509. if (second_response.find("ok") != std::string::npos) { break; }
  17510. }
  17511. return true;
  17512. });
  17513. *announced_close =
  17514. first_response.find("Connection: close") != std::string::npos;
  17515. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17516. }
  17517. class ConnectionTokenTest : public ::testing::Test {
  17518. protected:
  17519. void SetUp() override {
  17520. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17521. res.set_content("ok", "text/plain");
  17522. });
  17523. port_ = svr_.bind_to_any_port(HOST);
  17524. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17525. svr_.wait_until_ready();
  17526. }
  17527. void TearDown() override {
  17528. svr_.stop();
  17529. if (thread_.joinable()) { thread_.join(); }
  17530. }
  17531. Server svr_;
  17532. int port_ = 0;
  17533. thread thread_;
  17534. };
  17535. // "close" alongside another option still closes the connection, and the
  17536. // response says so rather than leaving the peer to discover it.
  17537. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17538. bool announced_close = false;
  17539. bool reusable = true;
  17540. probe_connection_reuse(port_,
  17541. "GET /keepalive HTTP/1.1\r\n"
  17542. "Host: localhost\r\n"
  17543. "Connection: keep-alive, close\r\n"
  17544. "\r\n",
  17545. &announced_close, &reusable);
  17546. EXPECT_TRUE(announced_close);
  17547. EXPECT_FALSE(reusable);
  17548. }
  17549. // "close" split over two field lines is the same list, so it is honored too.
  17550. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17551. bool announced_close = false;
  17552. bool reusable = true;
  17553. probe_connection_reuse(port_,
  17554. "GET /keepalive HTTP/1.1\r\n"
  17555. "Host: localhost\r\n"
  17556. "Connection: keep-alive\r\n"
  17557. "Connection: close\r\n"
  17558. "\r\n",
  17559. &announced_close, &reusable);
  17560. EXPECT_TRUE(announced_close);
  17561. EXPECT_FALSE(reusable);
  17562. }
  17563. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17564. // keep-alive in the spelling everyone actually sends keeps its connection.
  17565. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17566. bool announced_close = false;
  17567. bool reusable = false;
  17568. probe_connection_reuse(port_,
  17569. "GET /keepalive HTTP/1.0\r\n"
  17570. "Host: localhost\r\n"
  17571. "Connection: keep-alive\r\n"
  17572. "\r\n",
  17573. &announced_close, &reusable);
  17574. EXPECT_FALSE(announced_close);
  17575. EXPECT_TRUE(reusable);
  17576. }
  17577. // A token the value merely contains is not the token itself.
  17578. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17579. bool announced_close = false;
  17580. bool reusable = false;
  17581. probe_connection_reuse(port_,
  17582. "GET /keepalive HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "Connection: notclose\r\n"
  17585. "\r\n",
  17586. &announced_close, &reusable);
  17587. EXPECT_FALSE(announced_close);
  17588. EXPECT_TRUE(reusable);
  17589. }
  17590. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17591. Server svr;
  17592. std::vector<std::string> observed_types;
  17593. svr.Get("/", [&](const Request &req, Response &res) {
  17594. observed_types = req.accept_content_types;
  17595. res.set_content("ok", "text/plain");
  17596. });
  17597. auto port = svr.bind_to_any_port(HOST);
  17598. thread t = thread([&]() { svr.listen_after_bind(); });
  17599. auto se = detail::scope_exit([&] {
  17600. svr.stop();
  17601. t.join();
  17602. ASSERT_FALSE(svr.is_running());
  17603. });
  17604. svr.wait_until_ready();
  17605. Client cli(HOST, port);
  17606. Headers headers;
  17607. headers.emplace("Accept", "text/plain;q=0.5");
  17608. headers.emplace("Accept", "application/json");
  17609. auto res = cli.Get("/", headers);
  17610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17611. EXPECT_EQ(StatusCode::OK_200, res->status);
  17612. // Sorted by q-value, so the second field line's type comes first
  17613. ASSERT_EQ(2U, observed_types.size());
  17614. EXPECT_EQ("application/json", observed_types[0]);
  17615. EXPECT_EQ("text/plain", observed_types[1]);
  17616. }
  17617. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17618. // empty field line must not contribute a bare comma to the combined value.
  17619. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17620. Server svr;
  17621. std::vector<std::string> observed_types;
  17622. svr.Get("/", [&](const Request &req, Response &res) {
  17623. observed_types = req.accept_content_types;
  17624. res.set_content("ok", "text/plain");
  17625. });
  17626. auto port = svr.bind_to_any_port(HOST);
  17627. thread t = thread([&]() { svr.listen_after_bind(); });
  17628. auto se = detail::scope_exit([&] {
  17629. svr.stop();
  17630. t.join();
  17631. ASSERT_FALSE(svr.is_running());
  17632. });
  17633. svr.wait_until_ready();
  17634. // Empty first field line, then a real one
  17635. std::string raw_req = "GET / HTTP/1.1\r\n"
  17636. "Host: localhost\r\n"
  17637. "Accept:\r\n"
  17638. "Accept: application/json\r\n"
  17639. "Connection: close\r\n"
  17640. "\r\n";
  17641. std::string out;
  17642. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17643. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17644. ASSERT_EQ(1U, observed_types.size());
  17645. EXPECT_EQ("application/json", observed_types[0]);
  17646. }
  17647. // The skip in get_combined_header_value() is what keeps an empty field line
  17648. // from contributing a bare comma. Only a trailing empty field line exercises
  17649. // it: a leading one is already covered by the "combined is still empty" check,
  17650. // and parse_accept_header() now ignores the empty element either way, so the
  17651. // request-level test above can no longer tell the two apart.
  17652. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17653. Headers headers;
  17654. headers.emplace("Accept", "text/html");
  17655. headers.emplace("Accept", "");
  17656. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17657. headers.clear();
  17658. headers.emplace("Accept", "");
  17659. headers.emplace("Accept", "application/json");
  17660. EXPECT_EQ("application/json",
  17661. detail::get_combined_header_value(headers, "Accept"));
  17662. }
  17663. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17664. // An encoding offered on a later Accept-Encoding field line is still offered.
  17665. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17666. Server svr;
  17667. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17668. res.set_content(std::string(1024, 'x'), "text/plain");
  17669. });
  17670. auto port = svr.bind_to_any_port(HOST);
  17671. thread t = thread([&]() { svr.listen_after_bind(); });
  17672. auto se = detail::scope_exit([&] {
  17673. svr.stop();
  17674. t.join();
  17675. ASSERT_FALSE(svr.is_running());
  17676. });
  17677. svr.wait_until_ready();
  17678. Client cli(HOST, port);
  17679. cli.set_decompress(false);
  17680. Headers headers;
  17681. headers.emplace("Accept-Encoding", "identity");
  17682. headers.emplace("Accept-Encoding", "gzip");
  17683. auto res = cli.Get("/", headers);
  17684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17685. EXPECT_EQ(StatusCode::OK_200, res->status);
  17686. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17687. }
  17688. #endif
  17689. #ifndef _WIN32
  17690. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17691. Server svr;
  17692. svr.Post("/post", [&](const Request &req, Response &res) {
  17693. res.set_content(req.body, "text/plain");
  17694. });
  17695. svr.Put("/put", [&](const Request &req, Response &res) {
  17696. res.set_content(req.body, "text/plain");
  17697. });
  17698. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17699. res.set_content(req.body, "text/plain");
  17700. });
  17701. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17702. res.set_content(req.body, "text/plain");
  17703. });
  17704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17705. auto se = detail::scope_exit([&] {
  17706. svr.stop();
  17707. t.join();
  17708. ASSERT_FALSE(svr.is_running());
  17709. });
  17710. svr.wait_until_ready();
  17711. std::string resp;
  17712. // POST without Content-Length
  17713. ASSERT_TRUE(send_request(5,
  17714. "POST /post HTTP/1.1\r\n"
  17715. "Host: localhost\r\n"
  17716. "Connection: close\r\n"
  17717. "\r\n",
  17718. &resp));
  17719. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17720. // PUT without Content-Length
  17721. resp.clear();
  17722. ASSERT_TRUE(send_request(5,
  17723. "PUT /put HTTP/1.1\r\n"
  17724. "Host: localhost\r\n"
  17725. "Connection: close\r\n"
  17726. "\r\n",
  17727. &resp));
  17728. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17729. // PATCH without Content-Length
  17730. resp.clear();
  17731. ASSERT_TRUE(send_request(5,
  17732. "PATCH /patch HTTP/1.1\r\n"
  17733. "Host: localhost\r\n"
  17734. "Connection: close\r\n"
  17735. "\r\n",
  17736. &resp));
  17737. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17738. // DELETE without Content-Length
  17739. resp.clear();
  17740. ASSERT_TRUE(send_request(5,
  17741. "DELETE /delete HTTP/1.1\r\n"
  17742. "Host: localhost\r\n"
  17743. "Connection: close\r\n"
  17744. "\r\n",
  17745. &resp));
  17746. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17747. }
  17748. #endif
  17749. //==============================================================================
  17750. // open_stream() Tests
  17751. //==============================================================================
  17752. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17753. std::string result;
  17754. char buf[8192];
  17755. ssize_t n;
  17756. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17757. result.append(buf, static_cast<size_t>(n));
  17758. }
  17759. return result;
  17760. }
  17761. // Mock stream for unit tests
  17762. class MockStream : public Stream {
  17763. public:
  17764. std::string data;
  17765. size_t pos = 0;
  17766. ssize_t error_after = -1; // -1 = no error
  17767. explicit MockStream(const std::string &d, ssize_t err = -1)
  17768. : data(d), error_after(err) {}
  17769. bool is_readable() const override { return true; }
  17770. bool wait_readable() const override { return true; }
  17771. bool wait_writable() const override { return true; }
  17772. ssize_t read(char *ptr, size_t size) override {
  17773. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17774. if (pos >= data.size()) return 0;
  17775. size_t limit =
  17776. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17777. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17778. std::memcpy(ptr, data.data() + pos, to_read);
  17779. pos += to_read;
  17780. return static_cast<ssize_t>(to_read);
  17781. }
  17782. ssize_t write(const char *, size_t) override { return -1; }
  17783. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17784. ip = "127.0.0.1";
  17785. port = 0;
  17786. }
  17787. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17788. ip = "127.0.0.1";
  17789. port = 0;
  17790. }
  17791. socket_t socket() const override { return INVALID_SOCKET; }
  17792. time_t duration() const override { return 0; }
  17793. };
  17794. TEST(StreamHandleTest, Basic) {
  17795. ClientImpl::StreamHandle handle;
  17796. EXPECT_FALSE(handle.is_valid());
  17797. handle.response = detail::make_unique<Response>();
  17798. handle.error = Error::Connection;
  17799. EXPECT_FALSE(handle.is_valid());
  17800. handle.error = Error::Success;
  17801. EXPECT_TRUE(handle.is_valid());
  17802. }
  17803. TEST(BodyReaderTest, Basic) {
  17804. MockStream stream("Hello, World!");
  17805. detail::BodyReader reader;
  17806. reader.stream = &stream;
  17807. reader.content_length = 13;
  17808. char buf[32];
  17809. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17810. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17811. EXPECT_TRUE(reader.eof);
  17812. }
  17813. TEST(BodyReaderTest, NoStream) {
  17814. detail::BodyReader reader;
  17815. char buf[32];
  17816. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17817. EXPECT_EQ(Error::Connection, reader.last_error);
  17818. }
  17819. TEST(BodyReaderTest, Error) {
  17820. MockStream stream("Hello, World!", 5);
  17821. detail::BodyReader reader;
  17822. reader.stream = &stream;
  17823. reader.content_length = 13;
  17824. char buf[32];
  17825. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17826. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17827. EXPECT_EQ(Error::Read, reader.last_error);
  17828. }
  17829. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17830. // Mock-based StreamHandle tests relying on private internals are removed.
  17831. class OpenStreamTest : public ::testing::Test {
  17832. protected:
  17833. void SetUp() override {
  17834. svr_.Get("/hello", [](const Request &, Response &res) {
  17835. res.set_content("Hello World!", "text/plain");
  17836. });
  17837. svr_.Get("/large", [](const Request &, Response &res) {
  17838. res.set_content(std::string(10000, 'X'), "text/plain");
  17839. });
  17840. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17841. res.set_content("Hello World!", "image/jpeg");
  17842. res.set_header("Content-Encoding", "UTF-8");
  17843. });
  17844. svr_.Get("/chunked", [](const Request &, Response &res) {
  17845. res.set_chunked_content_provider("text/plain",
  17846. [](size_t offset, DataSink &sink) {
  17847. if (offset < 15) {
  17848. sink.write("chunk", 5);
  17849. return true;
  17850. }
  17851. sink.done();
  17852. return true;
  17853. });
  17854. });
  17855. svr_.Get("/compressible", [](const Request &, Response &res) {
  17856. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17857. DataSink &sink) {
  17858. if (offset < 100 * 1024) {
  17859. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17860. sink.write(chunk.data(), chunk.size());
  17861. return true;
  17862. }
  17863. sink.done();
  17864. return true;
  17865. });
  17866. });
  17867. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17868. [](const Request & /*req*/, Response &res) {
  17869. auto i = new int(0);
  17870. res.set_header("Trailer", "Content-Length, X-Allowed");
  17871. res.set_chunked_content_provider(
  17872. "text/plain",
  17873. [i](size_t /*offset*/, DataSink &sink) {
  17874. switch (*i) {
  17875. case 0: sink.os << "123"; break;
  17876. case 1: sink.os << "456"; break;
  17877. case 2: sink.os << "789"; break;
  17878. case 3: {
  17879. sink.done_with_trailer(
  17880. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17881. } break;
  17882. }
  17883. (*i)++;
  17884. return true;
  17885. },
  17886. [i](bool success) {
  17887. EXPECT_TRUE(success);
  17888. delete i;
  17889. });
  17890. });
  17891. // Echo headers endpoint for header-related tests
  17892. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17893. std::string body;
  17894. for (const auto &h : req.headers) {
  17895. body.append(h.first);
  17896. body.push_back(':');
  17897. body.append(h.second);
  17898. body.push_back('\n');
  17899. }
  17900. res.set_content(body, "text/plain");
  17901. });
  17902. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17903. std::string body;
  17904. for (const auto &h : req.headers) {
  17905. body.append(h.first);
  17906. body.push_back(':');
  17907. body.append(h.second);
  17908. body.push_back('\n');
  17909. }
  17910. res.set_content(body, "text/plain");
  17911. });
  17912. port_ = svr_.bind_to_any_port("127.0.0.1");
  17913. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17914. svr_.wait_until_ready();
  17915. }
  17916. void TearDown() override {
  17917. svr_.stop();
  17918. if (thread_.joinable()) thread_.join();
  17919. }
  17920. Server svr_;
  17921. std::thread thread_;
  17922. int port_ = 0;
  17923. };
  17924. TEST_F(OpenStreamTest, Basic) {
  17925. Client cli("127.0.0.1", port_);
  17926. auto handle = cli.open_stream("GET", "/hello");
  17927. EXPECT_TRUE(handle.is_valid());
  17928. EXPECT_EQ("Hello World!", read_all(handle));
  17929. }
  17930. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17931. Client cli("127.0.0.1", port_);
  17932. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17933. ASSERT_TRUE(handle.is_valid());
  17934. EXPECT_EQ("Hello World!", read_all(handle));
  17935. }
  17936. TEST_F(OpenStreamTest, SmallBuffer) {
  17937. Client cli("127.0.0.1", port_);
  17938. auto handle = cli.open_stream("GET", "/hello");
  17939. std::string result;
  17940. char buf[4];
  17941. ssize_t n;
  17942. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17943. result.append(buf, static_cast<size_t>(n));
  17944. EXPECT_EQ("Hello World!", result);
  17945. }
  17946. TEST_F(OpenStreamTest, DefaultHeaders) {
  17947. Client cli("127.0.0.1", port_);
  17948. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17949. {
  17950. auto handle = cli.open_stream("GET", "/echo-headers");
  17951. ASSERT_TRUE(handle.is_valid());
  17952. auto body = read_all(handle);
  17953. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17954. std::string::npos);
  17955. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17956. std::string::npos);
  17957. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17958. }
  17959. // open_stream POST with body and no explicit content_type should NOT add
  17960. // text/plain Content-Type (behavior differs from non-streaming path), but
  17961. // should include Content-Length
  17962. {
  17963. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17964. ASSERT_TRUE(handle.is_valid());
  17965. auto body = read_all(handle);
  17966. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17967. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17968. }
  17969. // open_stream POST with explicit Content-Type should preserve it
  17970. {
  17971. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17972. {{"Content-Type", "application/custom"}},
  17973. "{}", "application/custom");
  17974. ASSERT_TRUE(handle.is_valid());
  17975. auto body = read_all(handle);
  17976. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17977. }
  17978. // User-specified User-Agent must not be overwritten for stream API
  17979. {
  17980. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17981. {{"User-Agent", "MyAgent/1.2"}});
  17982. ASSERT_TRUE(handle.is_valid());
  17983. auto body = read_all(handle);
  17984. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17985. }
  17986. }
  17987. TEST_F(OpenStreamTest, Large) {
  17988. Client cli("127.0.0.1", port_);
  17989. auto handle = cli.open_stream("GET", "/large");
  17990. EXPECT_EQ(10000u, read_all(handle).size());
  17991. }
  17992. TEST_F(OpenStreamTest, ConnectionError) {
  17993. Client cli("127.0.0.1", 9999);
  17994. auto handle = cli.open_stream("GET", "/hello");
  17995. EXPECT_FALSE(handle.is_valid());
  17996. }
  17997. TEST_F(OpenStreamTest, Chunked) {
  17998. Client cli("127.0.0.1", port_);
  17999. auto handle = cli.open_stream("GET", "/chunked");
  18000. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18001. "Transfer-Encoding") == "chunked");
  18002. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18003. }
  18004. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18005. Client cli("127.0.0.1", port_);
  18006. auto handle =
  18007. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18008. ASSERT_TRUE(handle.is_valid());
  18009. // Consume body to allow trailers to be received/parsed
  18010. auto body = read_all(handle);
  18011. // Explicitly parse trailers (ensure trailers are available for assertion)
  18012. handle.parse_trailers_if_needed();
  18013. EXPECT_EQ(std::string("123456789"), body);
  18014. // The response should include a Trailer header declaring both names
  18015. ASSERT_TRUE(handle.response);
  18016. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18017. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18018. handle.response->get_header_value("Trailer"));
  18019. // Prohibited trailer must not be present
  18020. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18021. // Allowed trailer should be present
  18022. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18023. EXPECT_EQ(std::string("yes"),
  18024. handle.response->get_trailer_value("X-Allowed"));
  18025. // Verify trailers are NOT present as regular headers
  18026. EXPECT_EQ(std::string(""),
  18027. handle.response->get_header_value("Content-Length"));
  18028. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18029. }
  18030. static std::thread serve_single_response(std::promise<int> &port_promise,
  18031. const std::string &response) {
  18032. return std::thread([&port_promise, response] {
  18033. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18034. default_socket_options(srv);
  18035. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18036. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18037. sockaddr_in addr{};
  18038. addr.sin_family = AF_INET;
  18039. addr.sin_port = htons(0); // Let OS assign a free port
  18040. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18041. int opt = 1;
  18042. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18043. #ifdef _WIN32
  18044. reinterpret_cast<const char *>(&opt),
  18045. #else
  18046. &opt,
  18047. #endif
  18048. sizeof(opt));
  18049. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18050. ::listen(srv, 1) != 0) {
  18051. port_promise.set_value(-1);
  18052. detail::close_socket(srv);
  18053. return;
  18054. }
  18055. socklen_t addr_len = sizeof(addr);
  18056. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18057. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18058. sockaddr_in cli_addr{};
  18059. socklen_t cli_len = sizeof(cli_addr);
  18060. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18061. if (cli != INVALID_SOCKET) {
  18062. // Read the complete HTTP request (until the blank line that terminates
  18063. // headers) before sending the response. If the server closes the socket
  18064. // while the client's request data is still unread in the kernel receive
  18065. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18066. // connection on both sides: it discards the client's receive buffer
  18067. // (which already holds our response) and causes any in-progress write on
  18068. // the client to fail with ECONNRESET. Reading all request data first
  18069. // ensures close() emits a graceful FIN.
  18070. {
  18071. char rbuf[256];
  18072. std::string req;
  18073. while (req.find("\r\n\r\n") == std::string::npos) {
  18074. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18075. if (n <= 0) { break; }
  18076. req.append(rbuf, static_cast<size_t>(n));
  18077. }
  18078. }
  18079. ::send(cli,
  18080. #ifdef _WIN32
  18081. static_cast<const char *>(response.c_str()),
  18082. static_cast<int>(response.size()),
  18083. #else
  18084. response.c_str(), response.size(),
  18085. #endif
  18086. 0);
  18087. detail::close_socket(cli);
  18088. }
  18089. detail::close_socket(srv);
  18090. });
  18091. }
  18092. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18093. #ifndef _WIN32
  18094. signal(SIGPIPE, SIG_IGN);
  18095. #endif
  18096. std::promise<int> port_promise;
  18097. auto port_future = port_promise.get_future();
  18098. auto server_thread =
  18099. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18100. "Content-Type: text/plain\r\n"
  18101. "Content-Length: not-a-number\r\n"
  18102. "Connection: close\r\n"
  18103. "\r\n"
  18104. "hello");
  18105. auto port = port_future.get();
  18106. ASSERT_GT(port, 0);
  18107. Client cli("127.0.0.1", port);
  18108. auto handle = cli.open_stream("GET", "/");
  18109. EXPECT_FALSE(handle.is_valid());
  18110. server_thread.join();
  18111. }
  18112. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18113. #ifndef _WIN32
  18114. signal(SIGPIPE, SIG_IGN);
  18115. #endif
  18116. std::promise<int> port_promise;
  18117. auto port_future = port_promise.get_future();
  18118. auto server_thread = serve_single_response(
  18119. port_promise, "HTTP/1.1 200 OK\r\n"
  18120. "Content-Type: text/plain\r\n"
  18121. "Content-Length: 99999999999999999999999999\r\n"
  18122. "Connection: close\r\n"
  18123. "\r\n"
  18124. "hello");
  18125. auto port = port_future.get();
  18126. ASSERT_GT(port, 0);
  18127. // Historically std::stoull would throw std::out_of_range here and crash
  18128. // the process, then parsing silently clamped to a bogus framing length and
  18129. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18130. // so the stream fails to open, matching the not-a-number case above. The
  18131. // process still must NOT terminate.
  18132. Client cli("127.0.0.1", port);
  18133. auto handle = cli.open_stream("GET", "/");
  18134. EXPECT_FALSE(handle.is_valid());
  18135. server_thread.join();
  18136. }
  18137. // Serves `response` to the single request `fn` makes with a fresh client.
  18138. template <typename Fn>
  18139. static void with_single_response(const std::string &response, Fn fn) {
  18140. #ifndef _WIN32
  18141. signal(SIGPIPE, SIG_IGN);
  18142. #endif
  18143. std::promise<int> port_promise;
  18144. auto port_future = port_promise.get_future();
  18145. auto server_thread = serve_single_response(port_promise, response);
  18146. auto se = detail::scope_exit([&] { server_thread.join(); });
  18147. auto port = port_future.get();
  18148. ASSERT_GT(port, 0);
  18149. Client cli("127.0.0.1", port);
  18150. fn(cli);
  18151. }
  18152. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18153. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18154. // the chunked coding and drop Content-Length, so a front-end that trusts
  18155. // Content-Length would disagree about where the body ends (response
  18156. // smuggling). The client must reject such a response.
  18157. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18158. for (const char *te : {"chunked", "gzip, chunked"}) {
  18159. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18160. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18161. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18162. "5\r\nhello\r\n0\r\n\r\n";
  18163. with_single_response(response, [&](Client &cli) {
  18164. auto res = cli.Get("/");
  18165. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18166. EXPECT_EQ(Error::Read, res.error()) << te;
  18167. });
  18168. with_single_response(response, [&](Client &cli) {
  18169. auto handle = cli.open_stream("GET", "/");
  18170. EXPECT_FALSE(handle.is_valid()) << te;
  18171. EXPECT_EQ(Error::Read, handle.error) << te;
  18172. });
  18173. }
  18174. }
  18175. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18176. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18177. // closing the connection (unlike a request, which must be rejected).
  18178. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18179. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18180. "Transfer-Encoding: chunked\r\n"
  18181. "Connection: close\r\n"
  18182. "\r\n"
  18183. "5\r\nhello\r\n0\r\n\r\n",
  18184. "HTTP/1.1 200 OK\r\n"
  18185. "Transfer-Encoding: gzip\r\n"
  18186. "Connection: close\r\n"
  18187. "\r\n"
  18188. "hello"}) {
  18189. with_single_response(response, [&](Client &cli) {
  18190. auto res = cli.Get("/");
  18191. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18192. EXPECT_EQ("hello", res->body);
  18193. });
  18194. with_single_response(response, [&](Client &cli) {
  18195. auto handle = cli.open_stream("GET", "/");
  18196. ASSERT_TRUE(handle.is_valid()) << response;
  18197. EXPECT_EQ("hello", read_all(handle));
  18198. });
  18199. }
  18200. }
  18201. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18202. // framing headers describe nothing to read and must not be rejected.
  18203. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18204. const std::string framing = "Content-Length: 5\r\n"
  18205. "Transfer-Encoding: chunked\r\n"
  18206. "Connection: close\r\n"
  18207. "\r\n";
  18208. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18209. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18210. });
  18211. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18212. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18213. });
  18214. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18215. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18216. with_single_response(response, [&](Client &cli) {
  18217. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18218. });
  18219. with_single_response(response, [&](Client &cli) {
  18220. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18221. });
  18222. }
  18223. }
  18224. // A payload max length of 0 means no limit, however the body is framed.
  18225. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18226. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18227. "Transfer-Encoding: chunked\r\n"
  18228. "\r\n"
  18229. "5\r\nhello\r\n0\r\n\r\n",
  18230. "HTTP/1.1 200 OK\r\n"
  18231. "Connection: close\r\n"
  18232. "\r\n"
  18233. "hello"}) {
  18234. with_single_response(response, [&](Client &cli) {
  18235. cli.set_payload_max_length(0);
  18236. auto res = cli.Get("/");
  18237. ASSERT_TRUE(res) << response;
  18238. EXPECT_EQ("hello", res->body) << response;
  18239. });
  18240. }
  18241. }
  18242. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18243. Server svr;
  18244. svr.set_payload_max_length(0);
  18245. svr.Post("/echo", [](const Request &req, Response &res) {
  18246. res.set_content(req.body, "text/plain");
  18247. });
  18248. auto port = svr.bind_to_any_port(HOST);
  18249. thread t = thread([&] { svr.listen_after_bind(); });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. t.join();
  18253. ASSERT_FALSE(svr.is_running());
  18254. });
  18255. svr.wait_until_ready();
  18256. Client cli(HOST, port);
  18257. auto res = cli.Post(
  18258. "/echo",
  18259. [](size_t /*offset*/, DataSink &sink) {
  18260. sink.write("hello", 5);
  18261. sink.done();
  18262. return true;
  18263. },
  18264. "text/plain");
  18265. ASSERT_TRUE(res);
  18266. EXPECT_EQ(StatusCode::OK_200, res->status);
  18267. EXPECT_EQ("hello", res->body);
  18268. }
  18269. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18270. TEST_F(OpenStreamTest, Gzip) {
  18271. Client cli("127.0.0.1", port_);
  18272. auto handle = cli.open_stream("GET", "/compressible", {},
  18273. {{"Accept-Encoding", "gzip"}});
  18274. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18275. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18276. }
  18277. #endif
  18278. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18279. TEST_F(OpenStreamTest, Brotli) {
  18280. Client cli("127.0.0.1", port_);
  18281. auto handle =
  18282. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18283. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18284. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18285. }
  18286. #endif
  18287. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18288. TEST_F(OpenStreamTest, Zstd) {
  18289. Client cli("127.0.0.1", port_);
  18290. auto handle = cli.open_stream("GET", "/compressible", {},
  18291. {{"Accept-Encoding", "zstd"}});
  18292. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18293. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18294. }
  18295. #endif
  18296. #ifdef CPPHTTPLIB_SSL_ENABLED
  18297. class SSLOpenStreamTest : public ::testing::Test {
  18298. protected:
  18299. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18300. void SetUp() override {
  18301. svr_.Get("/hello", [](const Request &, Response &res) {
  18302. res.set_content("Hello SSL World!", "text/plain");
  18303. });
  18304. svr_.Get("/chunked", [](const Request &, Response &res) {
  18305. res.set_chunked_content_provider("text/plain",
  18306. [](size_t offset, DataSink &sink) {
  18307. if (offset < 15) {
  18308. sink.write("chunk", 5);
  18309. return true;
  18310. }
  18311. sink.done();
  18312. return true;
  18313. });
  18314. });
  18315. svr_.Post("/echo", [](const Request &req, Response &res) {
  18316. res.set_content(req.body, req.get_header_value("Content-Type"));
  18317. });
  18318. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18319. std::string body = req.body;
  18320. res.set_chunked_content_provider(
  18321. "text/plain", [body](size_t offset, DataSink &sink) {
  18322. if (offset < body.size()) {
  18323. sink.write(body.data() + offset, body.size() - offset);
  18324. }
  18325. sink.done();
  18326. return true;
  18327. });
  18328. });
  18329. port_ = svr_.bind_to_any_port("127.0.0.1");
  18330. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18331. svr_.wait_until_ready();
  18332. }
  18333. void TearDown() override {
  18334. svr_.stop();
  18335. if (thread_.joinable()) thread_.join();
  18336. }
  18337. SSLServer svr_;
  18338. std::thread thread_;
  18339. int port_ = 0;
  18340. };
  18341. TEST_F(SSLOpenStreamTest, Basic) {
  18342. SSLClient cli("127.0.0.1", port_);
  18343. cli.enable_server_certificate_verification(false);
  18344. auto handle = cli.open_stream("GET", "/hello");
  18345. ASSERT_TRUE(handle.is_valid());
  18346. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18347. }
  18348. TEST_F(SSLOpenStreamTest, Chunked) {
  18349. SSLClient cli("127.0.0.1", port_);
  18350. cli.enable_server_certificate_verification(false);
  18351. auto handle = cli.open_stream("GET", "/chunked");
  18352. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18353. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18354. "Transfer-Encoding") == "chunked");
  18355. auto body = read_all(handle);
  18356. EXPECT_EQ("chunkchunkchunk", body);
  18357. }
  18358. TEST_F(SSLOpenStreamTest, Post) {
  18359. SSLClient cli("127.0.0.1", port_);
  18360. cli.enable_server_certificate_verification(false);
  18361. auto handle =
  18362. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18363. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18364. EXPECT_EQ(200, handle.response->status);
  18365. auto body = read_all(handle);
  18366. EXPECT_EQ("Hello SSL POST", body);
  18367. }
  18368. TEST_F(SSLOpenStreamTest, PostChunked) {
  18369. SSLClient cli("127.0.0.1", port_);
  18370. cli.enable_server_certificate_verification(false);
  18371. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18372. "Chunked SSL Data", "text/plain");
  18373. ASSERT_TRUE(handle.is_valid());
  18374. EXPECT_EQ(200, handle.response->status);
  18375. auto body = read_all(handle);
  18376. EXPECT_EQ("Chunked SSL Data", body);
  18377. }
  18378. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18379. // Content-Length is terminated by the server closing the connection. When the
  18380. // SSL peer sends a close_notify after the body, the client must treat it as a
  18381. // clean EOF and return a successful response rather than an error.
  18382. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18384. ASSERT_TRUE(svr.is_valid());
  18385. svr.set_keep_alive_max_count(1);
  18386. const std::string expected_body = "Hello from connection-close response!";
  18387. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18388. res.set_content_provider("text/plain",
  18389. [&](size_t offset, DataSink &sink) -> bool {
  18390. if (offset < expected_body.size()) {
  18391. sink.write(expected_body.data() + offset,
  18392. expected_body.size() - offset);
  18393. }
  18394. sink.done();
  18395. return true;
  18396. });
  18397. });
  18398. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18399. auto se = detail::scope_exit([&] {
  18400. svr.stop();
  18401. listen_thread.join();
  18402. ASSERT_FALSE(svr.is_running());
  18403. });
  18404. svr.wait_until_ready();
  18405. SSLClient cli(HOST, PORT);
  18406. cli.enable_server_certificate_verification(false);
  18407. auto res = cli.Get("/no-content-length");
  18408. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18409. EXPECT_EQ(StatusCode::OK_200, res->status);
  18410. EXPECT_EQ(expected_body, res->body);
  18411. }
  18412. #endif // CPPHTTPLIB_SSL_ENABLED
  18413. //==============================================================================
  18414. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18415. // results for various scenarios.
  18416. //==============================================================================
  18417. TEST(ParityTest, GetVsOpenStream) {
  18418. Server svr;
  18419. const std::string path = "/parity";
  18420. const std::string content = "Parity test content: hello world";
  18421. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18422. res.set_content(content, "text/plain");
  18423. });
  18424. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18425. auto se = detail::scope_exit([&] {
  18426. svr.stop();
  18427. t.join();
  18428. ASSERT_FALSE(svr.is_running());
  18429. });
  18430. svr.wait_until_ready();
  18431. Client cli(HOST, PORT);
  18432. // Non-stream path
  18433. auto r1 = cli.Get(path);
  18434. ASSERT_TRUE(r1);
  18435. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18436. // Stream path
  18437. auto h = cli.open_stream("GET", path);
  18438. ASSERT_TRUE(h.is_valid());
  18439. EXPECT_EQ(r1->body, read_all(h));
  18440. }
  18441. // Helper to compress data with provided compressor type T
  18442. template <typename Compressor>
  18443. static std::string compress_payload_for_parity(const std::string &in) {
  18444. std::string out;
  18445. Compressor compressor;
  18446. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18447. [&](const char *data, size_t n) {
  18448. out.append(data, n);
  18449. return true;
  18450. });
  18451. EXPECT_TRUE(ok);
  18452. return out;
  18453. }
  18454. // Helper function for compression parity tests
  18455. template <typename Compressor>
  18456. static void test_compression_parity(const std::string &original,
  18457. const std::string &path,
  18458. const std::string &encoding) {
  18459. const std::string compressed =
  18460. compress_payload_for_parity<Compressor>(original);
  18461. Server svr;
  18462. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18463. res.set_content(compressed, "application/octet-stream");
  18464. res.set_header("Content-Encoding", encoding);
  18465. });
  18466. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18467. auto se = detail::scope_exit([&] {
  18468. svr.stop();
  18469. t.join();
  18470. ASSERT_FALSE(svr.is_running());
  18471. });
  18472. svr.wait_until_ready();
  18473. Client cli(HOST, PORT);
  18474. // Non-streaming
  18475. {
  18476. auto res = cli.Get(path);
  18477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18478. EXPECT_EQ(StatusCode::OK_200, res->status);
  18479. EXPECT_EQ(original, res->body);
  18480. }
  18481. // Streaming
  18482. {
  18483. auto h = cli.open_stream("GET", path);
  18484. ASSERT_TRUE(h.is_valid());
  18485. EXPECT_EQ(original, read_all(h));
  18486. }
  18487. }
  18488. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18489. TEST(ParityTest, Gzip) {
  18490. test_compression_parity<detail::gzip_compressor>(
  18491. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18492. }
  18493. #endif
  18494. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18495. TEST(ParityTest, Brotli) {
  18496. test_compression_parity<detail::brotli_compressor>(
  18497. "Hello, brotli parity test payload", "/parity-br", "br");
  18498. }
  18499. #endif
  18500. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18501. TEST(ParityTest, Zstd) {
  18502. test_compression_parity<detail::zstd_compressor>(
  18503. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18504. }
  18505. #endif
  18506. //==============================================================================
  18507. // New Stream API Tests
  18508. //==============================================================================
  18509. inline std::string read_body(httplib::stream::Result &result) {
  18510. std::string body;
  18511. while (result.next()) {
  18512. body.append(result.data(), result.size());
  18513. }
  18514. return body;
  18515. }
  18516. TEST(ClientConnectionTest, Basic) {
  18517. httplib::ClientConnection conn;
  18518. EXPECT_FALSE(conn.is_open());
  18519. conn.sock = 1;
  18520. EXPECT_TRUE(conn.is_open());
  18521. httplib::ClientConnection conn2(std::move(conn));
  18522. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18523. conn2.sock = INVALID_SOCKET;
  18524. }
  18525. // Unified test server for all stream::* tests
  18526. class StreamApiTest : public ::testing::Test {
  18527. protected:
  18528. void SetUp() override {
  18529. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18530. res.set_content("Hello World!", "text/plain");
  18531. });
  18532. svr_.Get("/echo-params",
  18533. [](const httplib::Request &req, httplib::Response &res) {
  18534. std::string r;
  18535. for (const auto &p : req.params) {
  18536. if (!r.empty()) r += "&";
  18537. r += p.first + "=" + p.second;
  18538. }
  18539. res.set_content(r, "text/plain");
  18540. });
  18541. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18542. res.set_content(req.body, req.get_header_value("Content-Type"));
  18543. });
  18544. svr_.Post("/echo-headers",
  18545. [](const httplib::Request &req, httplib::Response &res) {
  18546. std::string r;
  18547. for (const auto &h : req.headers)
  18548. r += h.first + ": " + h.second + "\n";
  18549. res.set_content(r, "text/plain");
  18550. });
  18551. svr_.Post("/echo-params",
  18552. [](const httplib::Request &req, httplib::Response &res) {
  18553. std::string r = "params:";
  18554. for (const auto &p : req.params)
  18555. r += p.first + "=" + p.second + ";";
  18556. res.set_content(r + " body:" + req.body, "text/plain");
  18557. });
  18558. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18559. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18560. });
  18561. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18562. res.set_content("PUT:" + req.body, "text/plain");
  18563. });
  18564. svr_.Patch("/echo",
  18565. [](const httplib::Request &req, httplib::Response &res) {
  18566. res.set_content("PATCH:" + req.body, "text/plain");
  18567. });
  18568. svr_.Delete(
  18569. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18570. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18571. "text/plain");
  18572. });
  18573. svr_.Get("/head-test",
  18574. [](const httplib::Request &, httplib::Response &res) {
  18575. res.set_content("body for HEAD", "text/plain");
  18576. });
  18577. svr_.Options("/options",
  18578. [](const httplib::Request &, httplib::Response &res) {
  18579. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18580. });
  18581. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18582. svr_.wait_until_ready();
  18583. }
  18584. void TearDown() override {
  18585. svr_.stop();
  18586. if (thread_.joinable()) thread_.join();
  18587. }
  18588. httplib::Server svr_;
  18589. std::thread thread_;
  18590. };
  18591. // stream::Get tests
  18592. TEST_F(StreamApiTest, GetBasic) {
  18593. httplib::Client cli(HOST, PORT);
  18594. auto result = httplib::stream::Get(cli, "/hello");
  18595. ASSERT_TRUE(result.is_valid());
  18596. EXPECT_EQ(200, result.status());
  18597. EXPECT_EQ("Hello World!", read_body(result));
  18598. }
  18599. TEST_F(StreamApiTest, GetWithParams) {
  18600. httplib::Client cli(HOST, PORT);
  18601. httplib::Params params{{"foo", "bar"}};
  18602. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18603. ASSERT_TRUE(result.is_valid());
  18604. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18605. }
  18606. TEST_F(StreamApiTest, GetConnectionError) {
  18607. httplib::Client cli(HOST, 9999);
  18608. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18609. }
  18610. TEST_F(StreamApiTest, Get404) {
  18611. httplib::Client cli(HOST, PORT);
  18612. auto result = httplib::stream::Get(cli, "/nonexistent");
  18613. EXPECT_TRUE(result.is_valid());
  18614. EXPECT_EQ(404, result.status());
  18615. }
  18616. // stream::Post tests
  18617. TEST_F(StreamApiTest, PostBasic) {
  18618. httplib::Client cli(HOST, PORT);
  18619. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18620. "application/json");
  18621. ASSERT_TRUE(result.is_valid());
  18622. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18623. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18624. }
  18625. TEST_F(StreamApiTest, PostWithHeaders) {
  18626. httplib::Client cli(HOST, PORT);
  18627. httplib::Headers headers{{"X-Custom", "value"}};
  18628. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18629. "text/plain");
  18630. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18631. }
  18632. TEST_F(StreamApiTest, PostWithParams) {
  18633. httplib::Client cli(HOST, PORT);
  18634. httplib::Params params{{"k", "v"}};
  18635. auto result =
  18636. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18637. auto body = read_body(result);
  18638. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18639. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18640. }
  18641. TEST_F(StreamApiTest, PostLarge) {
  18642. httplib::Client cli(HOST, PORT);
  18643. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18644. size_t total = 0;
  18645. while (result.next()) {
  18646. total += result.size();
  18647. }
  18648. EXPECT_EQ(100u * 1024u, total);
  18649. }
  18650. // stream::Put/Patch tests
  18651. TEST_F(StreamApiTest, PutAndPatch) {
  18652. httplib::Client cli(HOST, PORT);
  18653. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18654. EXPECT_EQ("PUT:test", read_body(put));
  18655. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18656. EXPECT_EQ("PATCH:test", read_body(patch));
  18657. }
  18658. // stream::Delete tests
  18659. TEST_F(StreamApiTest, Delete) {
  18660. httplib::Client cli(HOST, PORT);
  18661. auto del1 = httplib::stream::Delete(cli, "/resource");
  18662. EXPECT_EQ("Deleted", read_body(del1));
  18663. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18664. EXPECT_EQ("Deleted:data", read_body(del2));
  18665. }
  18666. // stream::Head/Options tests
  18667. TEST_F(StreamApiTest, HeadAndOptions) {
  18668. httplib::Client cli(HOST, PORT);
  18669. auto head = httplib::stream::Head(cli, "/head-test");
  18670. EXPECT_TRUE(head.is_valid());
  18671. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18672. auto opts = httplib::stream::Options(cli, "/options");
  18673. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18674. }
  18675. // SSL stream::* tests
  18676. #ifdef CPPHTTPLIB_SSL_ENABLED
  18677. class SSLStreamApiTest : public ::testing::Test {
  18678. protected:
  18679. void SetUp() override {
  18680. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18681. res.set_content("Hello SSL!", "text/plain");
  18682. });
  18683. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18684. res.set_content(req.body, "text/plain");
  18685. });
  18686. port_ = svr_.bind_to_any_port("127.0.0.1");
  18687. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18688. svr_.wait_until_ready();
  18689. }
  18690. void TearDown() override {
  18691. svr_.stop();
  18692. if (thread_.joinable()) thread_.join();
  18693. }
  18694. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18695. std::thread thread_;
  18696. int port_ = 0;
  18697. };
  18698. TEST_F(SSLStreamApiTest, GetAndPost) {
  18699. httplib::SSLClient cli("127.0.0.1", port_);
  18700. cli.enable_server_certificate_verification(false);
  18701. auto get = httplib::stream::Get(cli, "/hello");
  18702. EXPECT_EQ("Hello SSL!", read_body(get));
  18703. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18704. EXPECT_EQ("test", read_body(post));
  18705. }
  18706. #endif
  18707. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18708. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18709. // BodyReader
  18710. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18711. // Test that read timeout during streaming is detected
  18712. // Use a large content-length response where server delays mid-stream
  18713. Server svr;
  18714. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18715. // Send a large response with delay in the middle
  18716. res.set_content_provider(
  18717. 1000, // content_length
  18718. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18719. if (offset < 100) {
  18720. // Send first 100 bytes immediately
  18721. std::string data(100, 'A');
  18722. sink.write(data.c_str(), data.size());
  18723. return true;
  18724. }
  18725. // Then delay longer than client timeout
  18726. std::this_thread::sleep_for(std::chrono::seconds(3));
  18727. std::string data(900, 'B');
  18728. sink.write(data.c_str(), data.size());
  18729. return true;
  18730. });
  18731. });
  18732. auto port = 8091;
  18733. std::thread t([&]() { svr.listen("localhost", port); });
  18734. svr.wait_until_ready();
  18735. Client cli("localhost", port);
  18736. cli.set_read_timeout(1, 0); // 1 second timeout
  18737. auto handle = cli.open_stream("GET", "/slow-stream");
  18738. ASSERT_TRUE(handle.is_valid());
  18739. char buf[256];
  18740. ssize_t total = 0;
  18741. ssize_t n;
  18742. bool got_error = false;
  18743. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18744. total += n;
  18745. }
  18746. if (n < 0) {
  18747. got_error = true;
  18748. // Should be timeout or read error
  18749. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18750. handle.get_read_error() == Error::Read)
  18751. << "Actual error: " << to_string(handle.get_read_error());
  18752. }
  18753. // Either we got an error, or we got less data than expected
  18754. EXPECT_TRUE(got_error || total < 1000)
  18755. << "Expected timeout but got all " << total << " bytes";
  18756. svr.stop();
  18757. t.join();
  18758. }
  18759. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18760. // Test connection closed detection via BodyReader
  18761. Server svr;
  18762. std::atomic<bool> close_now{false};
  18763. svr.Get("/will-close", [&](const Request &, Response &res) {
  18764. res.set_content_provider(
  18765. 10000, // Large content_length that we won't fully send
  18766. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18767. if (offset < 100) {
  18768. std::string data(100, 'X');
  18769. sink.write(data.c_str(), data.size());
  18770. return true;
  18771. }
  18772. // Wait for signal then abort
  18773. while (!close_now) {
  18774. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18775. }
  18776. return false; // Abort - server will close connection
  18777. });
  18778. });
  18779. auto port = 8092;
  18780. std::thread t([&]() { svr.listen("localhost", port); });
  18781. svr.wait_until_ready();
  18782. Client cli("localhost", port);
  18783. auto handle = cli.open_stream("GET", "/will-close");
  18784. ASSERT_TRUE(handle.is_valid());
  18785. char buf[256];
  18786. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18787. EXPECT_GT(n, 0) << "First read should succeed";
  18788. // Signal server to close
  18789. close_now = true;
  18790. // Keep reading until error or EOF
  18791. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18792. // Keep reading
  18793. }
  18794. // Should get an error since content_length wasn't satisfied
  18795. if (n < 0) {
  18796. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18797. handle.get_read_error() == Error::Read)
  18798. << "Actual error: " << to_string(handle.get_read_error());
  18799. }
  18800. svr.stop();
  18801. t.join();
  18802. }
  18803. #ifdef CPPHTTPLIB_SSL_ENABLED
  18804. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18805. // Test that read timeout during SSL streaming is detected
  18806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18807. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18808. res.set_content_provider(
  18809. 1000, "text/plain",
  18810. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18811. if (offset < 100) {
  18812. std::string data(100, 'A');
  18813. sink.write(data.c_str(), data.size());
  18814. return true;
  18815. }
  18816. std::this_thread::sleep_for(std::chrono::seconds(3));
  18817. std::string data(900, 'B');
  18818. sink.write(data.c_str(), data.size());
  18819. return true;
  18820. });
  18821. });
  18822. auto port = 8093;
  18823. std::thread t([&]() { svr.listen("localhost", port); });
  18824. svr.wait_until_ready();
  18825. SSLClient cli("localhost", port);
  18826. cli.enable_server_certificate_verification(false);
  18827. cli.set_read_timeout(1, 0); // 1 second timeout
  18828. auto handle = cli.open_stream("GET", "/slow-stream");
  18829. ASSERT_TRUE(handle.is_valid());
  18830. char buf[256];
  18831. ssize_t total = 0;
  18832. ssize_t n;
  18833. bool got_error = false;
  18834. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18835. total += n;
  18836. }
  18837. if (n < 0) {
  18838. got_error = true;
  18839. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18840. handle.get_read_error() == Error::Read)
  18841. << "Actual error: " << to_string(handle.get_read_error());
  18842. }
  18843. EXPECT_TRUE(got_error || total < 1000)
  18844. << "Expected timeout but got all " << total << " bytes";
  18845. svr.stop();
  18846. t.join();
  18847. }
  18848. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18849. // Test SSL connection closed detection
  18850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18851. std::atomic<bool> close_now{false};
  18852. svr.Get("/will-close", [&](const Request &, Response &res) {
  18853. res.set_content_provider(
  18854. 10000, "text/plain",
  18855. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18856. if (offset < 100) {
  18857. std::string data(100, 'X');
  18858. sink.write(data.c_str(), data.size());
  18859. return true;
  18860. }
  18861. while (!close_now) {
  18862. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18863. }
  18864. return false;
  18865. });
  18866. });
  18867. auto port = 8094;
  18868. std::thread t([&]() { svr.listen("localhost", port); });
  18869. svr.wait_until_ready();
  18870. SSLClient cli("localhost", port);
  18871. cli.enable_server_certificate_verification(false);
  18872. auto handle = cli.open_stream("GET", "/will-close");
  18873. ASSERT_TRUE(handle.is_valid());
  18874. char buf[256];
  18875. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18876. EXPECT_GT(n, 0);
  18877. // Signal server to close
  18878. close_now = true;
  18879. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18880. // Keep reading
  18881. }
  18882. if (n < 0) {
  18883. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18884. handle.get_read_error() == Error::Read)
  18885. << "Actual error: " << to_string(handle.get_read_error());
  18886. }
  18887. svr.stop();
  18888. t.join();
  18889. }
  18890. #endif
  18891. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18892. using namespace httplib;
  18893. // Create a test file
  18894. const char *fname = "etag_testfile.txt";
  18895. const char *content = "etag-content";
  18896. {
  18897. std::ofstream ofs(fname);
  18898. ofs << content;
  18899. ASSERT_TRUE(ofs.good());
  18900. }
  18901. Server svr;
  18902. svr.set_mount_point("/static", ".");
  18903. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18904. svr.wait_until_ready();
  18905. Client cli(HOST, PORT);
  18906. // First request: should get 200 with ETag header
  18907. auto res1 = cli.Get("/static/etag_testfile.txt");
  18908. ASSERT_TRUE(res1);
  18909. ASSERT_EQ(200, res1->status);
  18910. ASSERT_TRUE(res1->has_header("ETag"));
  18911. std::string etag = res1->get_header_value("ETag");
  18912. EXPECT_FALSE(etag.empty());
  18913. // Verify ETag format: W/"hex-hex"
  18914. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18915. EXPECT_EQ('W', etag[0]);
  18916. EXPECT_EQ('/', etag[1]);
  18917. EXPECT_EQ('"', etag[2]);
  18918. EXPECT_EQ('"', etag.back());
  18919. // Exact match: expect 304 Not Modified
  18920. Headers h2 = {{"If-None-Match", etag}};
  18921. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18922. ASSERT_TRUE(res2);
  18923. EXPECT_EQ(304, res2->status);
  18924. // Wildcard match: expect 304 Not Modified
  18925. Headers h3 = {{"If-None-Match", "*"}};
  18926. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18927. ASSERT_TRUE(res3);
  18928. EXPECT_EQ(304, res3->status);
  18929. // Non-matching ETag: expect 200
  18930. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18931. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18932. ASSERT_TRUE(res4);
  18933. EXPECT_EQ(200, res4->status);
  18934. // Multiple ETags with one matching: expect 304
  18935. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18936. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18937. ASSERT_TRUE(res5);
  18938. EXPECT_EQ(304, res5->status);
  18939. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18940. // that equivalent to the single comma-separated list above, so the match on
  18941. // the second line must still be found.
  18942. Headers h6;
  18943. h6.emplace("If-None-Match", "W/\"other\"");
  18944. h6.emplace("If-None-Match", etag);
  18945. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18946. ASSERT_TRUE(res6);
  18947. EXPECT_EQ(304, res6->status);
  18948. svr.stop();
  18949. t.join();
  18950. std::remove(fname);
  18951. }
  18952. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18953. using namespace httplib;
  18954. Server svr;
  18955. svr.set_mount_point("/static", ".");
  18956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18957. svr.wait_until_ready();
  18958. Client cli(HOST, PORT);
  18959. // Send If-None-Match: * to a non-existent file
  18960. Headers h = {{"If-None-Match", "*"}};
  18961. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18963. EXPECT_EQ(404, res->status);
  18964. svr.stop();
  18965. t.join();
  18966. }
  18967. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18968. using namespace httplib;
  18969. // Create a test file
  18970. const char *fname = "etag_boundary_testfile.txt";
  18971. const char *content = "boundary-test";
  18972. {
  18973. std::ofstream ofs(fname);
  18974. ofs << content;
  18975. ASSERT_TRUE(ofs.good());
  18976. }
  18977. Server svr;
  18978. svr.set_mount_point("/static", ".");
  18979. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18980. svr.wait_until_ready();
  18981. Client cli(HOST, PORT);
  18982. // Get the actual ETag
  18983. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18984. ASSERT_TRUE(res1);
  18985. ASSERT_EQ(200, res1->status);
  18986. ASSERT_TRUE(res1->has_header("ETag"));
  18987. std::string etag = res1->get_header_value("ETag");
  18988. // Test 1: Very long ETag value (longer than actual ETag)
  18989. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18990. Headers h1 = {{"If-None-Match", "W/"
  18991. "\"very-long-etag-value-that-is-much-longer-"
  18992. "than-the-actual-etag-value\""}};
  18993. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18994. ASSERT_TRUE(res2);
  18995. EXPECT_EQ(200, res2->status); // Should not match
  18996. // Test 2: Long string followed by wildcard
  18997. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18998. // string)
  18999. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19000. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19001. ASSERT_TRUE(res3);
  19002. EXPECT_EQ(304, res3->status); // Should match on "*"
  19003. // Test 3: Wildcard followed by long string
  19004. // Should match on "*" immediately and return 304
  19005. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19006. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19007. ASSERT_TRUE(res4);
  19008. EXPECT_EQ(304, res4->status); // Should match on "*"
  19009. // Test 4: Multiple long non-matching values
  19010. // Should NOT match and return 200 (test that all comparisons are safe)
  19011. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19012. "W/\"second-long-non-matching-value\", "
  19013. "W/\"third-long-non-matching-value\""}};
  19014. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19015. ASSERT_TRUE(res5);
  19016. EXPECT_EQ(200, res5->status); // Should not match
  19017. // Test 5: Single character that is not "*" (edge case)
  19018. Headers h5 = {{"If-None-Match", "X"}};
  19019. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19020. ASSERT_TRUE(res6);
  19021. EXPECT_EQ(200, res6->status); // Should not match
  19022. svr.stop();
  19023. t.join();
  19024. std::remove(fname);
  19025. }
  19026. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19027. using namespace httplib;
  19028. // Create a test file
  19029. const char *fname = "ims_testfile.txt";
  19030. const char *content = "if-modified-since-test";
  19031. {
  19032. std::ofstream ofs(fname);
  19033. ofs << content;
  19034. ASSERT_TRUE(ofs.good());
  19035. }
  19036. Server svr;
  19037. svr.set_mount_point("/static", ".");
  19038. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19039. svr.wait_until_ready();
  19040. Client cli(HOST, PORT);
  19041. // First request: should get 200 with Last-Modified header
  19042. auto res1 = cli.Get("/static/ims_testfile.txt");
  19043. ASSERT_TRUE(res1);
  19044. ASSERT_EQ(200, res1->status);
  19045. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19046. std::string last_modified = res1->get_header_value("Last-Modified");
  19047. EXPECT_FALSE(last_modified.empty());
  19048. // If-Modified-Since with same time: expect 304
  19049. Headers h2 = {{"If-Modified-Since", last_modified}};
  19050. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19051. ASSERT_TRUE(res2);
  19052. EXPECT_EQ(304, res2->status);
  19053. // If-Modified-Since with future time: expect 304
  19054. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19055. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19056. ASSERT_TRUE(res3);
  19057. EXPECT_EQ(304, res3->status);
  19058. // If-Modified-Since with past time: expect 200
  19059. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19060. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19061. ASSERT_TRUE(res4);
  19062. EXPECT_EQ(200, res4->status);
  19063. // If-None-Match takes precedence over If-Modified-Since
  19064. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19065. ASSERT_TRUE(res1->has_header("ETag"));
  19066. std::string etag = res1->get_header_value("ETag");
  19067. Headers h5 = {{"If-None-Match", etag},
  19068. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19069. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19070. ASSERT_TRUE(res5);
  19071. EXPECT_EQ(304, res5->status);
  19072. svr.stop();
  19073. t.join();
  19074. std::remove(fname);
  19075. }
  19076. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19077. using namespace httplib;
  19078. Server svr;
  19079. // Endpoint that returns compressible content
  19080. svr.Get("/compressible", [](const Request &, Response &res) {
  19081. // Return a large enough body to trigger compression
  19082. std::string body(1000, 'a');
  19083. res.set_content(body, "text/plain");
  19084. });
  19085. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19086. svr.wait_until_ready();
  19087. Client cli(HOST, PORT);
  19088. // Request with gzip support: should get Vary header when compressed
  19089. cli.set_compress(true);
  19090. auto res1 = cli.Get("/compressible");
  19091. ASSERT_TRUE(res1);
  19092. EXPECT_EQ(200, res1->status);
  19093. // If Content-Encoding is set, Vary should also be set
  19094. if (res1->has_header("Content-Encoding")) {
  19095. EXPECT_TRUE(res1->has_header("Vary"));
  19096. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19097. }
  19098. // Request without Accept-Encoding header: should not have compression
  19099. Headers h_no_compress;
  19100. auto res2 = cli.Get("/compressible", h_no_compress);
  19101. ASSERT_TRUE(res2);
  19102. EXPECT_EQ(200, res2->status);
  19103. // Verify Vary header is present when compression is applied
  19104. // (the exact behavior depends on server configuration)
  19105. svr.stop();
  19106. t.join();
  19107. }
  19108. TEST(ETagTest, IfRangeWithETag) {
  19109. using namespace httplib;
  19110. // Create a test file with known content
  19111. const char *fname = "if_range_testfile.txt";
  19112. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19113. {
  19114. std::ofstream ofs(fname);
  19115. ofs << content;
  19116. ASSERT_TRUE(ofs.good());
  19117. }
  19118. Server svr;
  19119. svr.set_mount_point("/static", ".");
  19120. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19121. svr.wait_until_ready();
  19122. Client cli(HOST, PORT);
  19123. // First request: get ETag
  19124. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19125. ASSERT_TRUE(res1);
  19126. ASSERT_EQ(200, res1->status);
  19127. ASSERT_TRUE(res1->has_header("ETag"));
  19128. std::string etag = res1->get_header_value("ETag");
  19129. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19130. // Since our server generates weak ETags (W/"..."), If-Range with our
  19131. // ETag should NOT result in partial content - it should return full content.
  19132. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19133. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19134. ASSERT_TRUE(res2);
  19135. // Weak ETag in If-Range -> full content (200), not partial (206)
  19136. EXPECT_EQ(200, res2->status);
  19137. EXPECT_EQ(content, res2->body);
  19138. EXPECT_FALSE(res2->has_header("Content-Range"));
  19139. // Range request with non-matching If-Range (ETag): should get 200 (full
  19140. // content)
  19141. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19142. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19143. ASSERT_TRUE(res3);
  19144. EXPECT_EQ(200, res3->status);
  19145. EXPECT_EQ(content, res3->body);
  19146. EXPECT_FALSE(res3->has_header("Content-Range"));
  19147. // Range request with strong ETag (hypothetical - our server doesn't generate
  19148. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19149. // should return full content)
  19150. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19151. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19152. ASSERT_TRUE(res4);
  19153. EXPECT_EQ(200, res4->status);
  19154. EXPECT_EQ(content, res4->body);
  19155. EXPECT_FALSE(res4->has_header("Content-Range"));
  19156. svr.stop();
  19157. t.join();
  19158. std::remove(fname);
  19159. }
  19160. TEST(ETagTest, IfRangeWithDate) {
  19161. using namespace httplib;
  19162. // Create a test file
  19163. const char *fname = "if_range_date_testfile.txt";
  19164. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19165. {
  19166. std::ofstream ofs(fname);
  19167. ofs << content;
  19168. ASSERT_TRUE(ofs.good());
  19169. }
  19170. Server svr;
  19171. svr.set_mount_point("/static", ".");
  19172. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19173. svr.wait_until_ready();
  19174. Client cli(HOST, PORT);
  19175. // First request: get Last-Modified
  19176. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19177. ASSERT_TRUE(res1);
  19178. ASSERT_EQ(200, res1->status);
  19179. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19180. std::string last_modified = res1->get_header_value("Last-Modified");
  19181. // Range request with matching If-Range (date): should get 206
  19182. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19183. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19184. ASSERT_TRUE(res2);
  19185. EXPECT_EQ(206, res2->status);
  19186. EXPECT_EQ("FGHIJ", res2->body);
  19187. // Range request with old If-Range date: should get 200 (full content)
  19188. Headers h3 = {{"Range", "bytes=5-9"},
  19189. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19190. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19191. ASSERT_TRUE(res3);
  19192. EXPECT_EQ(200, res3->status);
  19193. EXPECT_EQ(content, res3->body);
  19194. // Range request with future If-Range date: should get 206
  19195. Headers h4 = {{"Range", "bytes=0-4"},
  19196. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19197. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19198. ASSERT_TRUE(res4);
  19199. EXPECT_EQ(206, res4->status);
  19200. EXPECT_EQ("ABCDE", res4->body);
  19201. svr.stop();
  19202. t.join();
  19203. std::remove(fname);
  19204. }
  19205. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19206. using namespace httplib;
  19207. const char *fname = "etag_malformed.txt";
  19208. const char *content = "malformed-etag";
  19209. {
  19210. std::ofstream ofs(fname);
  19211. ofs << content;
  19212. ASSERT_TRUE(ofs.good());
  19213. }
  19214. Server svr;
  19215. svr.set_mount_point("/static", ".");
  19216. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19217. svr.wait_until_ready();
  19218. Client cli(HOST, PORT);
  19219. // baseline: should get 200 and an ETag
  19220. auto res1 = cli.Get("/static/etag_malformed.txt");
  19221. ASSERT_TRUE(res1);
  19222. ASSERT_EQ(200, res1->status);
  19223. ASSERT_TRUE(res1->has_header("ETag"));
  19224. // Malformed ETag value (missing quotes) should be treated as non-matching
  19225. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19226. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19227. ASSERT_TRUE(res_bad);
  19228. EXPECT_EQ(200, res_bad->status);
  19229. // Whitespace-only header value should be considered invalid / non-matching
  19230. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19231. "Host: localhost\r\n"
  19232. "If-None-Match: \r\n"
  19233. "Connection: close\r\n"
  19234. "\r\n";
  19235. std::string out;
  19236. ASSERT_TRUE(send_request(5, raw_req, &out));
  19237. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19238. svr.stop();
  19239. t.join();
  19240. std::remove(fname);
  19241. }
  19242. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19243. using namespace httplib;
  19244. const char *fname = "ims_invalid_format.txt";
  19245. const char *content = "ims-bad-format";
  19246. {
  19247. std::ofstream ofs(fname);
  19248. ofs << content;
  19249. ASSERT_TRUE(ofs.good());
  19250. }
  19251. Server svr;
  19252. svr.set_mount_point("/static", ".");
  19253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19254. svr.wait_until_ready();
  19255. Client cli(HOST, PORT);
  19256. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19257. ASSERT_TRUE(res1);
  19258. ASSERT_EQ(200, res1->status);
  19259. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19260. // If-Modified-Since with invalid format should not result in 304
  19261. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19262. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19263. ASSERT_TRUE(res_bad);
  19264. EXPECT_EQ(200, res_bad->status);
  19265. // If-Range with invalid date format should be treated as mismatch -> full
  19266. // content (200)
  19267. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19268. {"If-Range", "invalid-date"}};
  19269. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19270. ASSERT_TRUE(res_ifrange);
  19271. EXPECT_EQ(200, res_ifrange->status);
  19272. svr.stop();
  19273. t.join();
  19274. std::remove(fname);
  19275. }
  19276. TEST(ETagTest, IfRangeWithMalformedETag) {
  19277. using namespace httplib;
  19278. const char *fname = "ifrange_malformed.txt";
  19279. const std::string content = "0123456789";
  19280. {
  19281. std::ofstream ofs(fname);
  19282. ofs << content;
  19283. ASSERT_TRUE(ofs.good());
  19284. }
  19285. Server svr;
  19286. svr.set_mount_point("/static", ".");
  19287. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19288. svr.wait_until_ready();
  19289. Client cli(HOST, PORT);
  19290. // First request: get ETag
  19291. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19292. ASSERT_TRUE(res1);
  19293. ASSERT_EQ(200, res1->status);
  19294. ASSERT_TRUE(res1->has_header("ETag"));
  19295. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19296. // full content (200)
  19297. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19298. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19299. ASSERT_TRUE(res2);
  19300. EXPECT_EQ(200, res2->status);
  19301. EXPECT_EQ(content, res2->body);
  19302. svr.stop();
  19303. t.join();
  19304. std::remove(fname);
  19305. }
  19306. TEST(ETagTest, ExtremeLargeDateValues) {
  19307. using namespace httplib;
  19308. const char *fname = "ims_extreme_date.txt";
  19309. const char *content = "ims-extreme-date";
  19310. {
  19311. std::ofstream ofs(fname);
  19312. ofs << content;
  19313. ASSERT_TRUE(ofs.good());
  19314. }
  19315. Server svr;
  19316. svr.set_mount_point("/static", ".");
  19317. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19318. svr.wait_until_ready();
  19319. Client cli(HOST, PORT);
  19320. auto res1 = cli.Get(std::string("/static/") + fname);
  19321. ASSERT_TRUE(res1);
  19322. ASSERT_EQ(200, res1->status);
  19323. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19324. // Extremely large year that may overflow date parsing routines.
  19325. Headers h_large_date = {
  19326. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19327. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19328. ASSERT_TRUE(res_bad);
  19329. // Expect server to treat this as invalid/mismatch and return full content
  19330. EXPECT_EQ(200, res_bad->status);
  19331. // If-Range with extremely large date should be treated as mismatch -> full
  19332. // content (200)
  19333. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19334. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19335. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19336. ASSERT_TRUE(res_ifrange);
  19337. EXPECT_EQ(200, res_ifrange->status);
  19338. svr.stop();
  19339. t.join();
  19340. std::remove(fname);
  19341. }
  19342. TEST(ETagTest, NegativeFileModificationTime) {
  19343. using namespace httplib;
  19344. const char *fname = "ims_negative_mtime.txt";
  19345. const std::string content = "negative-mtime";
  19346. {
  19347. std::ofstream ofs(fname);
  19348. ofs << content;
  19349. ASSERT_TRUE(ofs.good());
  19350. }
  19351. // Try to set file mtime to a negative value. This may fail on some
  19352. // platforms/filesystems; if it fails, the test will still verify server
  19353. // behaves safely by performing a regular conditional request.
  19354. #if defined(__APPLE__) || defined(__linux__)
  19355. bool set_negative = false;
  19356. do {
  19357. struct timeval times[2];
  19358. // access time: now
  19359. times[0].tv_sec = time(nullptr);
  19360. times[0].tv_usec = 0;
  19361. // modification time: negative (e.g., -1)
  19362. times[1].tv_sec = -1;
  19363. times[1].tv_usec = 0;
  19364. if (utimes(fname, times) == 0) { set_negative = true; }
  19365. } while (0);
  19366. #else
  19367. bool set_negative = false;
  19368. #endif
  19369. Server svr;
  19370. svr.set_mount_point("/static", ".");
  19371. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19372. svr.wait_until_ready();
  19373. Client cli(HOST, PORT);
  19374. auto res1 = cli.Get(std::string("/static/") + fname);
  19375. ASSERT_TRUE(res1);
  19376. ASSERT_EQ(200, res1->status);
  19377. bool has_last_modified = res1->has_header("Last-Modified");
  19378. std::string last_modified;
  19379. if (has_last_modified) {
  19380. last_modified = res1->get_header_value("Last-Modified");
  19381. }
  19382. if (set_negative) {
  19383. // If we successfully set a negative mtime, ensure server returns a
  19384. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19385. // with an old date and ensure server handles it without crash.
  19386. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19387. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19388. ASSERT_TRUE(res2);
  19389. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19390. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19391. } else {
  19392. // Could not set negative mtime on this platform; fall back to verifying
  19393. // that normal invalid/malformed dates are treated safely (non-304).
  19394. Headers h_bad_date = {
  19395. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19396. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19397. ASSERT_TRUE(res_bad);
  19398. EXPECT_EQ(200, res_bad->status);
  19399. }
  19400. svr.stop();
  19401. t.join();
  19402. std::remove(fname);
  19403. }
  19404. //==============================================================================
  19405. // Integration Tests with Server
  19406. //==============================================================================
  19407. class SSEIntegrationTest : public ::testing::Test {
  19408. protected:
  19409. void SetUp() override {
  19410. stop_server_.store(false);
  19411. events_.clear();
  19412. server_ = httplib::detail::make_unique<Server>();
  19413. setup_server();
  19414. start_server();
  19415. }
  19416. void TearDown() override {
  19417. stop_server_.store(true);
  19418. event_cv_.notify_all();
  19419. server_->stop();
  19420. if (server_thread_.joinable()) { server_thread_.join(); }
  19421. }
  19422. void setup_server() {
  19423. // Simple SSE endpoint
  19424. server_->Get("/events", [this](const Request &req, Response &res) {
  19425. auto last_id = req.get_header_value("Last-Event-ID");
  19426. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19427. res.set_chunked_content_provider(
  19428. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19429. std::unique_lock<std::mutex> lock(event_mutex_);
  19430. if (event_cv_.wait_for(
  19431. lock, std::chrono::milliseconds(200), [this] {
  19432. return !events_.empty() || stop_server_.load();
  19433. })) {
  19434. if (stop_server_.load()) { return false; }
  19435. if (!events_.empty()) {
  19436. std::string event = events_.front();
  19437. events_.erase(events_.begin());
  19438. sink.write(event.data(), event.size());
  19439. return true;
  19440. }
  19441. }
  19442. return !stop_server_.load();
  19443. });
  19444. });
  19445. // Endpoint that returns error
  19446. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19447. res.status = 500;
  19448. res.set_content("Internal Server Error", "text/plain");
  19449. });
  19450. // Endpoint for custom event types
  19451. server_->Get("/custom-events", [](const Request &, Response &res) {
  19452. res.set_chunked_content_provider(
  19453. "text/event-stream", [](size_t offset, DataSink &sink) {
  19454. if (offset == 0) {
  19455. std::string event = "event: update\ndata: updated\n\n"
  19456. "event: delete\ndata: deleted\n\n";
  19457. sink.write(event.data(), event.size());
  19458. }
  19459. return false; // End stream after sending
  19460. });
  19461. });
  19462. }
  19463. void start_server() {
  19464. port_ = server_->bind_to_any_port(HOST);
  19465. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19466. // Wait for server to start
  19467. while (!server_->is_running()) {
  19468. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19469. }
  19470. }
  19471. int get_port() const { return port_; }
  19472. void send_event(const std::string &event) {
  19473. std::lock_guard<std::mutex> lock(event_mutex_);
  19474. events_.push_back(event);
  19475. event_cv_.notify_all();
  19476. }
  19477. std::unique_ptr<Server> server_;
  19478. std::thread server_thread_;
  19479. std::mutex event_mutex_;
  19480. std::condition_variable event_cv_;
  19481. std::vector<std::string> events_;
  19482. std::atomic<bool> stop_server_{false};
  19483. std::string last_received_event_id_;
  19484. int port_ = 0;
  19485. };
  19486. //==============================================================================
  19487. // SSE Parsing Tests
  19488. //==============================================================================
  19489. class SSEParsingTest : public SSEIntegrationTest {
  19490. protected:
  19491. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19492. // A trailing sentinel event tells when the whole stream has been parsed.
  19493. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19494. auto body = stream + "event: end\ndata: end\n\n";
  19495. server_->Get("/parse", [body](const Request &, Response &res) {
  19496. res.set_content(body, "text/event-stream");
  19497. });
  19498. return collect("/parse");
  19499. }
  19500. // Runs SSEClient against path until an "end" event arrives and returns the
  19501. // messages dispatched before it
  19502. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19503. Client client(HOST, get_port());
  19504. sse::SSEClient sse(client, path);
  19505. std::mutex mutex;
  19506. std::condition_variable cv;
  19507. std::vector<sse::SSEMessage> messages;
  19508. auto done = false;
  19509. sse.on_message([&](const sse::SSEMessage &msg) {
  19510. std::lock_guard<std::mutex> lock(mutex);
  19511. // Ignore a replay from a reconnect that races with stop()
  19512. if (!done) { messages.push_back(msg); }
  19513. });
  19514. sse.on_event("end", [&](const sse::SSEMessage &) {
  19515. std::lock_guard<std::mutex> lock(mutex);
  19516. done = true;
  19517. cv.notify_all();
  19518. });
  19519. sse.set_reconnect_interval(100);
  19520. sse.start_async();
  19521. {
  19522. std::unique_lock<std::mutex> lock(mutex);
  19523. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19524. }
  19525. sse.stop();
  19526. EXPECT_TRUE(done);
  19527. return messages;
  19528. }
  19529. };
  19530. TEST_F(SSEParsingTest, SingleLineData) {
  19531. auto msgs = parse("data: hello\n\n");
  19532. ASSERT_EQ(msgs.size(), 1u);
  19533. EXPECT_EQ(msgs[0].data, "hello");
  19534. EXPECT_EQ(msgs[0].event, "message");
  19535. }
  19536. TEST_F(SSEParsingTest, MultiLineData) {
  19537. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19538. ASSERT_EQ(msgs.size(), 1u);
  19539. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19540. }
  19541. TEST_F(SSEParsingTest, CustomEventType) {
  19542. auto msgs = parse("event: update\ndata: payload\n\n");
  19543. ASSERT_EQ(msgs.size(), 1u);
  19544. EXPECT_EQ(msgs[0].event, "update");
  19545. EXPECT_EQ(msgs[0].data, "payload");
  19546. }
  19547. TEST_F(SSEParsingTest, EventIdHandling) {
  19548. auto msgs = parse("id: 12345\ndata: test\n\n");
  19549. ASSERT_EQ(msgs.size(), 1u);
  19550. EXPECT_EQ(msgs[0].id, "12345");
  19551. }
  19552. TEST_F(SSEParsingTest, EmptyEventId) {
  19553. auto msgs = parse("id:\ndata: test\n\n");
  19554. ASSERT_EQ(msgs.size(), 1u);
  19555. EXPECT_EQ(msgs[0].id, "");
  19556. }
  19557. TEST_F(SSEParsingTest, CommentsIgnored) {
  19558. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19559. ASSERT_EQ(msgs.size(), 1u);
  19560. EXPECT_EQ(msgs[0].data, "hello");
  19561. EXPECT_EQ(msgs[0].event, "message");
  19562. }
  19563. TEST_F(SSEParsingTest, ColonInValue) {
  19564. auto msgs = parse("data: hello:world:test\n\n");
  19565. ASSERT_EQ(msgs.size(), 1u);
  19566. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19567. }
  19568. TEST_F(SSEParsingTest, FieldNameOnly) {
  19569. // A line without a colon is a field name with an empty value
  19570. auto msgs = parse("data\n\n");
  19571. ASSERT_EQ(msgs.size(), 1u);
  19572. EXPECT_EQ(msgs[0].data, "");
  19573. }
  19574. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19575. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19576. ASSERT_EQ(msgs.size(), 1u);
  19577. EXPECT_EQ(msgs[0].event, "update");
  19578. EXPECT_EQ(msgs[0].data, "hello");
  19579. }
  19580. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19581. auto msgs = parse("data\r\n\r\n");
  19582. ASSERT_EQ(msgs.size(), 1u);
  19583. EXPECT_EQ(msgs[0].data, "");
  19584. }
  19585. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19586. auto msgs = parse("event: update\rdata: hello\r\r");
  19587. ASSERT_EQ(msgs.size(), 1u);
  19588. EXPECT_EQ(msgs[0].event, "update");
  19589. EXPECT_EQ(msgs[0].data, "hello");
  19590. }
  19591. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19592. // Chunk boundaries fall inside every \r\n and right before the first one
  19593. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19594. "\n\r", "\nevent: end\ndata: end\n\n"};
  19595. server_->Get("/split", [chunks](const Request &, Response &res) {
  19596. auto i = std::make_shared<size_t>(0);
  19597. res.set_chunked_content_provider(
  19598. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19599. if (*i == chunks.size()) {
  19600. sink.done();
  19601. } else {
  19602. sink.write(chunks[*i].data(), chunks[*i].size());
  19603. (*i)++;
  19604. }
  19605. return true;
  19606. });
  19607. });
  19608. auto msgs = collect("/split");
  19609. ASSERT_EQ(msgs.size(), 1u);
  19610. EXPECT_EQ(msgs[0].event, "update");
  19611. EXPECT_EQ(msgs[0].data, "hello");
  19612. }
  19613. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19614. // Only a BOM at the start of the stream is ignored
  19615. auto msgs = parse("\xEF\xBB\xBF"
  19616. "data: first\n\n"
  19617. "\xEF\xBB\xBF"
  19618. "data: second\n\n");
  19619. ASSERT_EQ(msgs.size(), 1u);
  19620. EXPECT_EQ(msgs[0].data, "first");
  19621. }
  19622. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19623. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19624. ASSERT_EQ(msgs.size(), 1u);
  19625. EXPECT_EQ(msgs[0].data, "hello");
  19626. EXPECT_EQ(msgs[0].event, "message");
  19627. }
  19628. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19629. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19630. ASSERT_EQ(msgs.size(), 2u);
  19631. EXPECT_EQ(msgs[0].data, "hello");
  19632. EXPECT_EQ(msgs[1].data, "hello");
  19633. }
  19634. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19635. // An event without data is not dispatched, and its type must not leak
  19636. // into the next event
  19637. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19638. ASSERT_EQ(msgs.size(), 1u);
  19639. EXPECT_EQ(msgs[0].event, "message");
  19640. EXPECT_EQ(msgs[0].data, "hello");
  19641. }
  19642. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19643. // The first connection sends only an id; the second echoes back the
  19644. // Last-Event-ID it was reconnected with
  19645. std::atomic<int> connection_count{0};
  19646. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19647. if (connection_count++ == 0) {
  19648. res.set_content("id: 42\n\n", "text/event-stream");
  19649. } else {
  19650. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19651. "\n\nevent: end\ndata: end\n\n",
  19652. "text/event-stream");
  19653. }
  19654. });
  19655. auto msgs = collect("/id-only");
  19656. ASSERT_EQ(msgs.size(), 1u);
  19657. EXPECT_EQ(msgs[0].data, "42");
  19658. }
  19659. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19660. // The first connection sets an id and then clears it with an empty one; the
  19661. // second reports whether it was reconnected with a Last-Event-ID
  19662. std::atomic<int> connection_count{0};
  19663. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19664. if (connection_count++ == 0) {
  19665. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19666. "text/event-stream");
  19667. } else {
  19668. res.set_content(
  19669. std::string("data: ") +
  19670. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19671. "\n\nevent: end\ndata: end\n\n",
  19672. "text/event-stream");
  19673. }
  19674. });
  19675. auto msgs = collect("/id-clear");
  19676. ASSERT_EQ(msgs.size(), 3u);
  19677. EXPECT_EQ(msgs[0].id, "1");
  19678. EXPECT_EQ(msgs[1].id, "");
  19679. EXPECT_EQ(msgs[2].data, "not sent");
  19680. }
  19681. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19682. // The first connection sets an id and then sends ids that cannot be carried
  19683. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19684. // with
  19685. std::atomic<int> connection_count{0};
  19686. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19687. if (connection_count++ == 0) {
  19688. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19689. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19690. "text/event-stream");
  19691. } else {
  19692. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19693. "\n\nevent: end\ndata: end\n\n",
  19694. "text/event-stream");
  19695. }
  19696. });
  19697. auto msgs = collect("/id-unsendable");
  19698. ASSERT_EQ(msgs.size(), 1u);
  19699. EXPECT_EQ(msgs[0].data, "42");
  19700. }
  19701. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19702. auto msgs = parse("event: notification\nid: evt-42\n"
  19703. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19704. ASSERT_EQ(msgs.size(), 1u);
  19705. EXPECT_EQ(msgs[0].event, "notification");
  19706. EXPECT_EQ(msgs[0].id, "evt-42");
  19707. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19708. }
  19709. TEST(SSEMessageTest, Clear) {
  19710. sse::SSEMessage msg;
  19711. msg.event = "custom";
  19712. msg.data = "some data";
  19713. msg.id = "123";
  19714. msg.clear();
  19715. EXPECT_EQ(msg.event, "message");
  19716. EXPECT_EQ(msg.data, "");
  19717. EXPECT_EQ(msg.id, "");
  19718. }
  19719. //==============================================================================
  19720. // SSE Integration Tests
  19721. //==============================================================================
  19722. // Test: Successful connection and on_open callback
  19723. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19724. // Add a simple endpoint that sends one event and closes
  19725. server_->Get("/simple-event", [](const Request &, Response &res) {
  19726. res.set_chunked_content_provider(
  19727. "text/event-stream", [](size_t offset, DataSink &sink) {
  19728. if (offset == 0) {
  19729. std::string event = "data: hello\n\n";
  19730. sink.write(event.data(), event.size());
  19731. }
  19732. return false; // Close stream after sending
  19733. });
  19734. });
  19735. Client client("localhost", get_port());
  19736. sse::SSEClient sse(client, "/simple-event");
  19737. std::atomic<bool> open_called{false};
  19738. std::atomic<bool> message_received{false};
  19739. sse.on_open([&open_called]() { open_called.store(true); });
  19740. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19741. if (msg.data == "hello") { message_received.store(true); }
  19742. });
  19743. sse.set_reconnect_interval(100);
  19744. sse.set_max_reconnect_attempts(1);
  19745. // Start async
  19746. sse.start_async();
  19747. // Wait for message to be processed
  19748. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19749. sse.stop();
  19750. EXPECT_TRUE(open_called.load());
  19751. EXPECT_TRUE(message_received.load());
  19752. }
  19753. // Test: on_message callback
  19754. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19755. // Endpoint that sends multiple events then closes
  19756. server_->Get("/multi-event", [](const Request &, Response &res) {
  19757. res.set_chunked_content_provider(
  19758. "text/event-stream", [](size_t offset, DataSink &sink) {
  19759. if (offset == 0) {
  19760. std::string events = "data: message1\n\ndata: message2\n\n";
  19761. sink.write(events.data(), events.size());
  19762. }
  19763. return false;
  19764. });
  19765. });
  19766. Client client("localhost", get_port());
  19767. sse::SSEClient sse(client, "/multi-event");
  19768. std::vector<std::string> received_messages;
  19769. std::mutex messages_mutex;
  19770. sse.on_message([&](const sse::SSEMessage &msg) {
  19771. std::lock_guard<std::mutex> lock(messages_mutex);
  19772. received_messages.push_back(msg.data);
  19773. });
  19774. sse.set_reconnect_interval(100);
  19775. sse.set_max_reconnect_attempts(1);
  19776. sse.start_async();
  19777. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19778. sse.stop();
  19779. std::lock_guard<std::mutex> lock(messages_mutex);
  19780. EXPECT_GE(received_messages.size(), 2u);
  19781. if (received_messages.size() >= 2) {
  19782. EXPECT_EQ(received_messages[0], "message1");
  19783. EXPECT_EQ(received_messages[1], "message2");
  19784. }
  19785. }
  19786. // Test: on_event for specific types
  19787. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19788. Client client("localhost", get_port());
  19789. sse::SSEClient sse(client, "/custom-events");
  19790. std::atomic<bool> update_received{false};
  19791. std::atomic<bool> delete_received{false};
  19792. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19793. if (msg.data == "updated") { update_received.store(true); }
  19794. });
  19795. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19796. if (msg.data == "deleted") { delete_received.store(true); }
  19797. });
  19798. sse.set_max_reconnect_attempts(1);
  19799. sse.start_async();
  19800. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19801. sse.stop();
  19802. EXPECT_TRUE(update_received.load());
  19803. EXPECT_TRUE(delete_received.load());
  19804. }
  19805. // Test: on_error callback on connection failure
  19806. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19807. // Connect to a non-existent port
  19808. Client client("localhost", 59999);
  19809. sse::SSEClient sse(client, "/events");
  19810. std::atomic<bool> error_called{false};
  19811. Error received_error = Error::Success;
  19812. sse.on_error([&](Error err) {
  19813. error_called.store(true);
  19814. received_error = err;
  19815. });
  19816. sse.set_reconnect_interval(50);
  19817. sse.set_max_reconnect_attempts(1);
  19818. sse.start_async();
  19819. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19820. sse.stop();
  19821. EXPECT_TRUE(error_called.load());
  19822. EXPECT_NE(received_error, Error::Success);
  19823. }
  19824. // Test: Last-Event-ID header sent on reconnect
  19825. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19826. // Endpoint that sends event with ID
  19827. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19828. res.set_chunked_content_provider(
  19829. "text/event-stream", [](size_t offset, DataSink &sink) {
  19830. if (offset == 0) {
  19831. std::string event = "id: evt-123\ndata: test\n\n";
  19832. sink.write(event.data(), event.size());
  19833. }
  19834. return false;
  19835. });
  19836. });
  19837. Client client("localhost", get_port());
  19838. sse::SSEClient sse(client, "/event-with-id");
  19839. std::atomic<bool> id_received{false};
  19840. sse.on_message([&](const sse::SSEMessage &msg) {
  19841. if (!msg.id.empty()) { id_received.store(true); }
  19842. });
  19843. sse.set_reconnect_interval(100);
  19844. sse.set_max_reconnect_attempts(1);
  19845. sse.start_async();
  19846. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19847. sse.stop();
  19848. EXPECT_TRUE(id_received.load());
  19849. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19850. }
  19851. // Test: Manual stop
  19852. TEST_F(SSEIntegrationTest, ManualStop) {
  19853. // Endpoint that sends one event and stays open briefly
  19854. std::atomic<bool> handler_running{true};
  19855. server_->Get("/stay-open", [&handler_running](const Request &,
  19856. Response &res) {
  19857. res.set_chunked_content_provider(
  19858. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19859. if (offset == 0) {
  19860. std::string event = "data: connected\n\n";
  19861. sink.write(event.data(), event.size());
  19862. }
  19863. // Keep connection open while handler_running is true
  19864. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19865. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19866. }
  19867. return false;
  19868. });
  19869. });
  19870. Client client("localhost", get_port());
  19871. sse::SSEClient sse(client, "/stay-open");
  19872. std::atomic<bool> connected{false};
  19873. sse.on_open([&connected]() { connected.store(true); });
  19874. sse.set_reconnect_interval(100);
  19875. sse.set_max_reconnect_attempts(1);
  19876. sse.start_async();
  19877. // Wait for connection to establish
  19878. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19879. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19880. }
  19881. EXPECT_TRUE(connected.load());
  19882. EXPECT_TRUE(sse.is_connected());
  19883. // Signal handler to stop
  19884. handler_running.store(false);
  19885. // Stop SSE client
  19886. sse.stop();
  19887. EXPECT_FALSE(sse.is_connected());
  19888. }
  19889. // Test: SSEClient with custom headers
  19890. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19891. // Setup a server endpoint that checks for custom header
  19892. std::atomic<bool> header_received{false};
  19893. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19894. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19895. header_received.store(true);
  19896. }
  19897. res.set_chunked_content_provider("text/event-stream",
  19898. [](size_t, DataSink &) { return false; });
  19899. });
  19900. Client client("localhost", get_port());
  19901. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19902. sse::SSEClient sse(client, "/header-check", headers);
  19903. sse.set_max_reconnect_attempts(1);
  19904. sse.start_async();
  19905. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19906. sse.stop();
  19907. EXPECT_TRUE(header_received.load());
  19908. }
  19909. // Test: Reconnect interval configuration
  19910. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19911. Client client("localhost", get_port());
  19912. sse::SSEClient sse(client, "/events");
  19913. auto &result = sse.set_reconnect_interval(500);
  19914. // Builder pattern should return reference to self
  19915. EXPECT_EQ(&result, &sse);
  19916. }
  19917. // Test: Max reconnect attempts
  19918. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19919. // Connect to non-existent port to force reconnects
  19920. Client client("localhost", 59998);
  19921. sse::SSEClient sse(client, "/events");
  19922. std::atomic<int> error_count{0};
  19923. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19924. sse.set_reconnect_interval(50);
  19925. sse.set_max_reconnect_attempts(2);
  19926. auto start = std::chrono::steady_clock::now();
  19927. sse.start(); // Blocking call
  19928. auto end = std::chrono::steady_clock::now();
  19929. // Should have stopped after 2 failed attempts
  19930. EXPECT_GE(error_count.load(), 2);
  19931. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19932. auto duration =
  19933. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19934. #ifdef _WIN32
  19935. // Windows is much slower for socket connection failures
  19936. EXPECT_LT(duration.count(), 7000);
  19937. #else
  19938. EXPECT_LT(duration.count(), 1000);
  19939. #endif
  19940. }
  19941. // Test: Multi-line data in integration
  19942. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19943. // Endpoint with multi-line data
  19944. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19945. res.set_chunked_content_provider(
  19946. "text/event-stream", [](size_t offset, DataSink &sink) {
  19947. if (offset == 0) {
  19948. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19949. sink.write(event.data(), event.size());
  19950. }
  19951. return false;
  19952. });
  19953. });
  19954. Client client("localhost", get_port());
  19955. sse::SSEClient sse(client, "/multiline-data");
  19956. std::string received_data;
  19957. std::mutex data_mutex;
  19958. sse.on_message([&](const sse::SSEMessage &msg) {
  19959. std::lock_guard<std::mutex> lock(data_mutex);
  19960. received_data = msg.data;
  19961. });
  19962. sse.set_reconnect_interval(100);
  19963. sse.set_max_reconnect_attempts(1);
  19964. sse.start_async();
  19965. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19966. sse.stop();
  19967. std::lock_guard<std::mutex> lock(data_mutex);
  19968. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19969. }
  19970. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19971. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19972. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19973. DataSink &sink) {
  19974. if (offset == 0) {
  19975. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19976. sink.write(events.data(), events.size());
  19977. }
  19978. return false;
  19979. });
  19980. });
  19981. Client client("localhost", get_port());
  19982. sse::SSEClient sse(client, "/empty-data-lines");
  19983. std::mutex mutex;
  19984. std::condition_variable cv;
  19985. std::vector<std::string> received;
  19986. sse.on_message([&](const sse::SSEMessage &msg) {
  19987. std::lock_guard<std::mutex> lock(mutex);
  19988. received.push_back(msg.data);
  19989. cv.notify_all();
  19990. });
  19991. sse.set_max_reconnect_attempts(1);
  19992. sse.start_async();
  19993. {
  19994. std::unique_lock<std::mutex> lock(mutex);
  19995. cv.wait_for(lock, std::chrono::seconds(2),
  19996. [&] { return received.size() >= 3; });
  19997. }
  19998. sse.stop();
  19999. ASSERT_GE(received.size(), 3u);
  20000. EXPECT_EQ(received[0], "");
  20001. EXPECT_EQ(received[1], "\nhello");
  20002. EXPECT_EQ(received[2], "");
  20003. }
  20004. // Test: Auto-reconnect after server disconnection
  20005. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20006. std::atomic<int> connection_count{0};
  20007. std::atomic<int> message_count{0};
  20008. // Endpoint that sends one event and closes, forcing reconnect
  20009. server_->Get("/reconnect-test",
  20010. [&connection_count](const Request &, Response &res) {
  20011. connection_count.fetch_add(1);
  20012. res.set_chunked_content_provider(
  20013. "text/event-stream", [](size_t offset, DataSink &sink) {
  20014. if (offset == 0) {
  20015. std::string event = "data: hello\n\n";
  20016. sink.write(event.data(), event.size());
  20017. }
  20018. return false; // Close connection after sending
  20019. });
  20020. });
  20021. Client client("localhost", get_port());
  20022. sse::SSEClient sse(client, "/reconnect-test");
  20023. sse.on_message([&message_count](const sse::SSEMessage &) {
  20024. message_count.fetch_add(1);
  20025. });
  20026. sse.set_reconnect_interval(100);
  20027. sse.set_max_reconnect_attempts(3);
  20028. sse.start_async();
  20029. // Wait long enough for multiple reconnects
  20030. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20031. sse.stop();
  20032. // Should have connected multiple times (initial + reconnects)
  20033. EXPECT_GE(connection_count.load(), 2);
  20034. // Should have received messages from multiple connections
  20035. EXPECT_GE(message_count.load(), 2);
  20036. }
  20037. // Test: A retry field that is not all ASCII digits is ignored
  20038. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20039. std::atomic<int> connection_count{0};
  20040. server_->Get("/bad-retry",
  20041. [&connection_count](const Request &, Response &res) {
  20042. connection_count.fetch_add(1);
  20043. res.set_chunked_content_provider(
  20044. "text/event-stream", [](size_t offset, DataSink &sink) {
  20045. if (offset == 0) {
  20046. std::string event = "retry: -1\ndata: hello\n\n";
  20047. sink.write(event.data(), event.size());
  20048. }
  20049. return false;
  20050. });
  20051. });
  20052. Client client("localhost", get_port());
  20053. sse::SSEClient sse(client, "/bad-retry");
  20054. sse.set_reconnect_interval(10000);
  20055. sse.start_async();
  20056. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20057. sse.stop();
  20058. EXPECT_EQ(connection_count.load(), 1);
  20059. }
  20060. // Test: A retry field of all ASCII digits sets the reconnection time
  20061. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20062. std::mutex mutex;
  20063. std::condition_variable cv;
  20064. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20065. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20066. {
  20067. std::lock_guard<std::mutex> lock(mutex);
  20068. connected_at.push_back(std::chrono::steady_clock::now());
  20069. cv.notify_all();
  20070. }
  20071. res.set_chunked_content_provider(
  20072. "text/event-stream", [](size_t offset, DataSink &sink) {
  20073. if (offset == 0) {
  20074. std::string event = "retry: 0\ndata: hello\n\n";
  20075. sink.write(event.data(), event.size());
  20076. }
  20077. return false;
  20078. });
  20079. });
  20080. Client client("localhost", get_port());
  20081. sse::SSEClient sse(client, "/zero-retry");
  20082. sse.set_reconnect_interval(10000);
  20083. sse.start_async();
  20084. {
  20085. std::unique_lock<std::mutex> lock(mutex);
  20086. cv.wait_for(lock, std::chrono::seconds(5),
  20087. [&] { return connected_at.size() >= 2; });
  20088. }
  20089. sse.stop();
  20090. // The server-supplied interval is applied, but never below 100ms, so
  20091. // "retry: 0" does not cause a busy reconnect loop
  20092. std::lock_guard<std::mutex> lock(mutex);
  20093. ASSERT_GE(connected_at.size(), 2u);
  20094. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20095. connected_at[1] - connected_at[0])
  20096. .count();
  20097. EXPECT_GE(interval_ms, 100);
  20098. }
  20099. // Test: Last-Event-ID sent on reconnect
  20100. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20101. std::atomic<int> connection_count{0};
  20102. std::vector<std::string> received_last_event_ids;
  20103. std::mutex id_mutex;
  20104. // Endpoint that checks Last-Event-ID header and sends event with ID
  20105. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20106. int conn = connection_count.fetch_add(1);
  20107. // Capture the Last-Event-ID header from each connection
  20108. {
  20109. std::lock_guard<std::mutex> lock(id_mutex);
  20110. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20111. }
  20112. res.set_chunked_content_provider(
  20113. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20114. if (offset == 0) {
  20115. std::string event =
  20116. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20117. sink.write(event.data(), event.size());
  20118. }
  20119. return false;
  20120. });
  20121. });
  20122. Client client("localhost", get_port());
  20123. sse::SSEClient sse(client, "/reconnect-with-id");
  20124. sse.set_reconnect_interval(100);
  20125. sse.set_max_reconnect_attempts(3);
  20126. sse.start_async();
  20127. // Wait for at least 2 connections
  20128. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20129. sse.stop();
  20130. // Verify behavior
  20131. std::lock_guard<std::mutex> lock(id_mutex);
  20132. EXPECT_GE(received_last_event_ids.size(), 2u);
  20133. // First connection should have no Last-Event-ID
  20134. if (!received_last_event_ids.empty()) {
  20135. EXPECT_EQ(received_last_event_ids[0], "");
  20136. }
  20137. // Second connection should have Last-Event-ID from first connection
  20138. if (received_last_event_ids.size() >= 2) {
  20139. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20140. }
  20141. }
  20142. // Test: set_headers updates headers used on reconnect
  20143. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20144. std::vector<std::string> received_tokens;
  20145. std::mutex token_mutex;
  20146. // Endpoint that captures Authorization header
  20147. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20148. {
  20149. std::lock_guard<std::mutex> lock(token_mutex);
  20150. received_tokens.push_back(req.get_header_value("Authorization"));
  20151. }
  20152. res.set_chunked_content_provider(
  20153. "text/event-stream", [](size_t offset, DataSink &sink) {
  20154. if (offset == 0) {
  20155. std::string event = "data: hello\n\n";
  20156. sink.write(event.data(), event.size());
  20157. }
  20158. return false; // Close connection to trigger reconnect
  20159. });
  20160. });
  20161. Client client("localhost", get_port());
  20162. Headers headers = {{"Authorization", "Bearer old-token"}};
  20163. sse::SSEClient sse(client, "/auth-check", headers);
  20164. // Update headers on each successful connection
  20165. sse.on_open(
  20166. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20167. sse.set_reconnect_interval(100);
  20168. sse.set_max_reconnect_attempts(3);
  20169. sse.start_async();
  20170. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20171. sse.stop();
  20172. std::lock_guard<std::mutex> lock(token_mutex);
  20173. ASSERT_GE(received_tokens.size(), 2u);
  20174. // First connection uses original header
  20175. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20176. // Second connection uses updated header from set_headers
  20177. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20178. }
  20179. // Test: 401 allows reconnection (so on_error can refresh headers)
  20180. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20181. std::atomic<int> connection_count{0};
  20182. // Endpoint: returns 401 on first attempt, 200 on second
  20183. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20184. int conn = connection_count.fetch_add(1);
  20185. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20186. res.status = StatusCode::Unauthorized_401;
  20187. res.set_content("Unauthorized", "text/plain");
  20188. return;
  20189. }
  20190. res.set_chunked_content_provider(
  20191. "text/event-stream", [](size_t offset, DataSink &sink) {
  20192. if (offset == 0) {
  20193. std::string event = "data: authenticated\n\n";
  20194. sink.write(event.data(), event.size());
  20195. }
  20196. return false;
  20197. });
  20198. });
  20199. Client client("localhost", get_port());
  20200. Headers headers = {{"Authorization", "Bearer expired"}};
  20201. sse::SSEClient sse(client, "/auth-retry", headers);
  20202. std::atomic<bool> message_received{false};
  20203. // Refresh token on error
  20204. sse.on_error(
  20205. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20206. sse.on_message([&](const sse::SSEMessage &msg) {
  20207. if (msg.data == "authenticated") { message_received.store(true); }
  20208. });
  20209. sse.set_reconnect_interval(100);
  20210. sse.set_max_reconnect_attempts(3);
  20211. sse.start_async();
  20212. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20213. sse.stop();
  20214. // Should have reconnected after 401 and succeeded with new token
  20215. EXPECT_GE(connection_count.load(), 2);
  20216. EXPECT_TRUE(message_received.load());
  20217. }
  20218. TEST(Issue2318Test, EmptyHostString) {
  20219. {
  20220. httplib::Client cli_empty("", PORT);
  20221. auto res = cli_empty.Get("/");
  20222. ASSERT_FALSE(res);
  20223. EXPECT_EQ(httplib::Error::Connection, res.error());
  20224. }
  20225. {
  20226. httplib::Client cli(" ", PORT);
  20227. auto res = cli.Get("/");
  20228. ASSERT_FALSE(res);
  20229. EXPECT_EQ(httplib::Error::Connection, res.error());
  20230. }
  20231. }
  20232. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20233. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20234. Server svr;
  20235. // Set a small payload limit (1KB)
  20236. svr.set_payload_max_length(1024);
  20237. svr.Post("/test", [&](const Request &req, Response &res) {
  20238. res.set_content("Body size: " + std::to_string(req.body.size()),
  20239. "text/plain");
  20240. });
  20241. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20242. auto se = detail::scope_exit([&] {
  20243. svr.stop();
  20244. listen_thread.join();
  20245. });
  20246. svr.wait_until_ready();
  20247. // Create data that compresses well but exceeds limit when decompressed
  20248. // 8KB of repeated null bytes compresses to a very small size
  20249. std::string original_data(8 * 1024, '\0');
  20250. // Compress the data using gzip
  20251. std::string compressed_data;
  20252. detail::gzip_compressor compressor;
  20253. compressor.compress(original_data.data(), original_data.size(), true,
  20254. [&](const char *data, size_t size) {
  20255. compressed_data.append(data, size);
  20256. return true;
  20257. });
  20258. // Verify compression worked (compressed should be much smaller)
  20259. ASSERT_LT(compressed_data.size(), original_data.size());
  20260. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20261. // Send compressed data with Content-Encoding: gzip
  20262. Client cli(HOST, PORT);
  20263. Headers headers = {{"Content-Encoding", "gzip"}};
  20264. auto res =
  20265. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20266. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20268. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20269. }
  20270. #endif
  20271. // ============================================================================
  20272. // OpenSSL-Specific Tests
  20273. // ============================================================================
  20274. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20275. X509 *readCertificate(const std::string &strFileName) {
  20276. std::ifstream inStream(strFileName);
  20277. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20278. std::istreambuf_iterator<char>());
  20279. if (strCertPEM.empty()) return (nullptr);
  20280. BIO *pbCert = BIO_new(BIO_s_mem());
  20281. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20282. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20283. BIO_free(pbCert);
  20284. return (pCert);
  20285. }
  20286. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20287. std::ifstream inStream(strFileName);
  20288. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20289. std::istreambuf_iterator<char>());
  20290. if (strPrivateKeyPEM.empty()) return (nullptr);
  20291. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20292. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20293. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20294. BIO_free(pbPrivKey);
  20295. return (pPrivateKey);
  20296. }
  20297. TEST(BindServerTest, UpdateCerts) {
  20298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20299. int port = svr.bind_to_any_port("0.0.0.0");
  20300. ASSERT_TRUE(svr.is_valid());
  20301. ASSERT_TRUE(port > 0);
  20302. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20303. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20304. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20305. ASSERT_TRUE(cert != nullptr);
  20306. ASSERT_TRUE(ca_cert != nullptr);
  20307. ASSERT_TRUE(key != nullptr);
  20308. X509_STORE *cert_store = X509_STORE_new();
  20309. X509_STORE_add_cert(cert_store, ca_cert);
  20310. // svr.update_certs(cert, key, cert_store); // deprecated
  20311. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20312. CLIENT_CA_CERT_FILE);
  20313. ASSERT_TRUE(svr.is_valid());
  20314. svr.stop();
  20315. X509_STORE_free(cert_store);
  20316. X509_free(cert);
  20317. X509_free(ca_cert);
  20318. EVP_PKEY_free(key);
  20319. }
  20320. // Test that update_certs() updates client CA list correctly
  20321. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20322. // Start with file-based constructor
  20323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20324. ASSERT_TRUE(svr.is_valid());
  20325. // Initially no client CA list should be set
  20326. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20327. ASSERT_TRUE(ssl_ctx != nullptr);
  20328. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20329. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20330. EXPECT_EQ(0, count_before);
  20331. // Now update with client CA (PEM string)
  20332. std::string cert_pem, key_pem, ca_pem;
  20333. read_file(SERVER_CERT_FILE, cert_pem);
  20334. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20335. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20336. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20337. ASSERT_TRUE(svr.is_valid());
  20338. // Now client CA list should be set
  20339. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20340. ASSERT_TRUE(ca_list_after != nullptr);
  20341. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20342. }
  20343. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20344. // Test that the file-path SSLServer constructor properly sets the client CA
  20345. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20346. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20347. ASSERT_TRUE(svr.is_valid());
  20348. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20349. ASSERT_TRUE(ssl_ctx != nullptr);
  20350. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20351. ASSERT_TRUE(ca_list != nullptr);
  20352. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20353. }
  20354. #endif
  20355. // ============================================================================
  20356. // MbedTLS-Specific Tests
  20357. // ============================================================================
  20358. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20359. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20360. using namespace httplib::tls;
  20361. // Track if callback was invoked
  20362. bool callback_invoked = false;
  20363. // The callback receives void* ctx which is actually MbedTlsContext*
  20364. // We can access the mbedtls_ssl_config via the context
  20365. auto setup_callback = [&callback_invoked](void *ctx) {
  20366. callback_invoked = true;
  20367. // Cast to MbedTlsContext* to access the ssl config
  20368. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20369. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20370. // Use static variables to hold certificate data (simplified for test)
  20371. static mbedtls_x509_crt own_cert;
  20372. static mbedtls_pk_context own_key;
  20373. static mbedtls_x509_crt ca_chain;
  20374. static bool initialized = false;
  20375. if (!initialized) {
  20376. mbedtls_x509_crt_init(&own_cert);
  20377. mbedtls_pk_init(&own_key);
  20378. mbedtls_x509_crt_init(&ca_chain);
  20379. // Load server certificate
  20380. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20381. return false;
  20382. }
  20383. // Load server private key.
  20384. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20385. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20386. #if MBEDTLS_VERSION_MAJOR == 3
  20387. ,
  20388. mbedtls_ctr_drbg_random, nullptr
  20389. #endif
  20390. ) != 0) {
  20391. return false;
  20392. }
  20393. // Load CA chain for client verification
  20394. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20395. return false;
  20396. }
  20397. initialized = true;
  20398. }
  20399. // Configure the SSL config
  20400. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20401. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20402. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20403. // Set minimum TLS version using mbedTLS native API
  20404. #if MBEDTLS_VERSION_MAJOR >= 3
  20405. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20406. #else
  20407. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20408. MBEDTLS_SSL_MINOR_VERSION_3);
  20409. #endif
  20410. return true;
  20411. };
  20412. SSLServer svr(setup_callback);
  20413. ASSERT_TRUE(svr.is_valid());
  20414. ASSERT_TRUE(callback_invoked);
  20415. svr.Get("/test", [&](const Request &req, Response &res) {
  20416. res.set_content("test", "text/plain");
  20417. auto cert = req.peer_cert();
  20418. ASSERT_TRUE(static_cast<bool>(cert));
  20419. auto common_name = cert.subject_cn();
  20420. EXPECT_EQ("Common Name", common_name);
  20421. });
  20422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20423. auto se = detail::scope_exit([&] {
  20424. svr.stop();
  20425. t.join();
  20426. ASSERT_FALSE(svr.is_running());
  20427. });
  20428. svr.wait_until_ready();
  20429. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20430. cli.enable_server_certificate_verification(false);
  20431. cli.set_connection_timeout(30);
  20432. auto res = cli.Get("/test");
  20433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20434. ASSERT_EQ(StatusCode::OK_200, res->status);
  20435. }
  20436. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20437. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20438. // keep-alive SSL session, which reads through that config in
  20439. // mbedtls_ssl_close_notify.
  20440. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20442. ASSERT_TRUE(svr.is_valid());
  20443. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20444. res.set_content("test", "text/plain");
  20445. });
  20446. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20447. auto se = detail::scope_exit([&] {
  20448. svr.stop();
  20449. t.join();
  20450. ASSERT_FALSE(svr.is_running());
  20451. });
  20452. svr.wait_until_ready();
  20453. {
  20454. SSLClient cli(HOST, PORT);
  20455. cli.enable_server_certificate_verification(false);
  20456. cli.set_keep_alive(true);
  20457. auto res = cli.Get("/test");
  20458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20459. ASSERT_EQ(StatusCode::OK_200, res->status);
  20460. // cli is destructed here with the keep-alive SSL session still open.
  20461. }
  20462. }
  20463. #endif
  20464. // WebSocket Tests
  20465. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20466. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20467. // defining the meaning of these bits has been negotiated.
  20468. auto make_frame = [](uint8_t first_byte) {
  20469. std::string frame;
  20470. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20471. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20472. frame += "Hello";
  20473. return frame;
  20474. };
  20475. // RSV1 set (0x40)
  20476. {
  20477. detail::BufferStream strm;
  20478. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20479. ws::Opcode opcode;
  20480. std::string payload;
  20481. bool fin;
  20482. EXPECT_EQ(
  20483. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20484. ws::impl::FrameRead::Fail);
  20485. }
  20486. // RSV2 set (0x20)
  20487. {
  20488. detail::BufferStream strm;
  20489. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20490. ws::Opcode opcode;
  20491. std::string payload;
  20492. bool fin;
  20493. EXPECT_EQ(
  20494. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20495. ws::impl::FrameRead::Fail);
  20496. }
  20497. // RSV3 set (0x10)
  20498. {
  20499. detail::BufferStream strm;
  20500. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20501. ws::Opcode opcode;
  20502. std::string payload;
  20503. bool fin;
  20504. EXPECT_EQ(
  20505. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20506. ws::impl::FrameRead::Fail);
  20507. }
  20508. // No RSV bits set - should succeed
  20509. {
  20510. detail::BufferStream strm;
  20511. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20512. ws::Opcode opcode;
  20513. std::string payload;
  20514. bool fin;
  20515. EXPECT_EQ(
  20516. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20517. ws::impl::FrameRead::Ok);
  20518. EXPECT_EQ(ws::Opcode::Text, opcode);
  20519. EXPECT_EQ("Hello", payload);
  20520. EXPECT_TRUE(fin);
  20521. }
  20522. }
  20523. TEST(WebSocketTest, ControlFrameValidation) {
  20524. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20525. // payload length <= 125.
  20526. // Ping with FIN=0 - must be rejected
  20527. {
  20528. detail::BufferStream strm;
  20529. std::string frame;
  20530. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20531. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20532. strm.write(frame.data(), frame.size());
  20533. ws::Opcode opcode;
  20534. std::string payload;
  20535. bool fin;
  20536. EXPECT_EQ(
  20537. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20538. ws::impl::FrameRead::Fail);
  20539. }
  20540. // Close with FIN=0 - must be rejected
  20541. {
  20542. detail::BufferStream strm;
  20543. std::string frame;
  20544. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20545. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20546. strm.write(frame.data(), frame.size());
  20547. ws::Opcode opcode;
  20548. std::string payload;
  20549. bool fin;
  20550. EXPECT_EQ(
  20551. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20552. ws::impl::FrameRead::Fail);
  20553. }
  20554. // Ping with payload_len=126 (extended length) - must be rejected
  20555. {
  20556. detail::BufferStream strm;
  20557. std::string frame;
  20558. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20559. frame += static_cast<char>(126); // payload_len=126 (>125)
  20560. frame += static_cast<char>(0x00); // extended length high byte
  20561. frame += static_cast<char>(126); // extended length low byte
  20562. frame += std::string(126, 'x');
  20563. strm.write(frame.data(), frame.size());
  20564. ws::Opcode opcode;
  20565. std::string payload;
  20566. bool fin;
  20567. EXPECT_EQ(
  20568. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20569. ws::impl::FrameRead::Fail);
  20570. }
  20571. // Ping with FIN=1 and payload_len=125 - should succeed
  20572. {
  20573. detail::BufferStream strm;
  20574. std::string frame;
  20575. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20576. frame += static_cast<char>(125); // payload_len=125
  20577. frame += std::string(125, 'x');
  20578. strm.write(frame.data(), frame.size());
  20579. ws::Opcode opcode;
  20580. std::string payload;
  20581. bool fin;
  20582. EXPECT_EQ(
  20583. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20584. ws::impl::FrameRead::Ok);
  20585. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20586. EXPECT_EQ(125u, payload.size());
  20587. EXPECT_TRUE(fin);
  20588. }
  20589. }
  20590. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20591. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20592. // length MUST be 0.
  20593. // MSB set - must be rejected
  20594. {
  20595. detail::BufferStream strm;
  20596. std::string frame;
  20597. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20598. frame += static_cast<char>(127); // 64-bit extended length
  20599. frame += static_cast<char>(0x80); // MSB set (invalid)
  20600. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20601. strm.write(frame.data(), frame.size());
  20602. ws::Opcode opcode;
  20603. std::string payload;
  20604. bool fin;
  20605. EXPECT_EQ(
  20606. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20607. ws::impl::FrameRead::Fail);
  20608. }
  20609. // MSB clear - should pass length parsing (will be rejected by max_len,
  20610. // but that's a different check; use a small length to verify)
  20611. {
  20612. detail::BufferStream strm;
  20613. std::string frame;
  20614. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20615. frame += static_cast<char>(127); // 64-bit extended length
  20616. frame += std::string(7, '\0'); // high bytes = 0
  20617. frame += static_cast<char>(0x03); // length = 3
  20618. frame += "abc";
  20619. strm.write(frame.data(), frame.size());
  20620. ws::Opcode opcode;
  20621. std::string payload;
  20622. bool fin;
  20623. EXPECT_EQ(
  20624. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20625. ws::impl::FrameRead::Ok);
  20626. EXPECT_EQ(ws::Opcode::Text, opcode);
  20627. EXPECT_EQ("abc", payload);
  20628. }
  20629. }
  20630. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20631. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20632. // Valid UTF-8
  20633. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20634. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20635. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20636. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20637. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20638. // Invalid UTF-8
  20639. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20640. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20641. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20642. EXPECT_FALSE(
  20643. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20644. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20645. }
  20646. TEST(WebSocketTest, ConnectAndDisconnect) {
  20647. Server svr;
  20648. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20649. std::string msg;
  20650. while (ws.read(msg)) {}
  20651. });
  20652. auto port = svr.bind_to_any_port(HOST);
  20653. std::thread t([&]() { svr.listen_after_bind(); });
  20654. svr.wait_until_ready();
  20655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20656. auto res = client.connect();
  20657. ASSERT_TRUE(res);
  20658. EXPECT_EQ(Error::Success, res.error());
  20659. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20660. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20661. EXPECT_TRUE(client.is_open());
  20662. client.close();
  20663. EXPECT_FALSE(client.is_open());
  20664. svr.stop();
  20665. t.join();
  20666. }
  20667. TEST(WebSocketTest, ValidURL) {
  20668. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20669. EXPECT_TRUE(ws1.is_valid());
  20670. ws::WebSocketClient ws2("ws://example.com/path");
  20671. EXPECT_TRUE(ws2.is_valid());
  20672. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20673. EXPECT_TRUE(ws3.is_valid());
  20674. #ifdef CPPHTTPLIB_SSL_ENABLED
  20675. ws::WebSocketClient wss1("wss://example.com/path");
  20676. EXPECT_TRUE(wss1.is_valid());
  20677. ws::WebSocketClient wss2("wss://example.com:443/path");
  20678. EXPECT_TRUE(wss2.is_valid());
  20679. #endif
  20680. }
  20681. TEST(WebSocketTest, InvalidURL) {
  20682. // No scheme
  20683. ws::WebSocketClient ws1("localhost:8080/path");
  20684. EXPECT_FALSE(ws1.is_valid());
  20685. // No path
  20686. ws::WebSocketClient ws2("ws://localhost:8080");
  20687. EXPECT_FALSE(ws2.is_valid());
  20688. // Empty string
  20689. ws::WebSocketClient ws3("");
  20690. EXPECT_FALSE(ws3.is_valid());
  20691. // Missing host
  20692. ws::WebSocketClient ws4("ws://:8080/path");
  20693. EXPECT_FALSE(ws4.is_valid());
  20694. // Port number overflow — should not crash
  20695. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20696. EXPECT_FALSE(ws5.is_valid());
  20697. // Port out of range
  20698. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20699. EXPECT_FALSE(ws6.is_valid());
  20700. }
  20701. TEST(WebSocketTest, UnsupportedScheme) {
  20702. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20703. ws::WebSocketClient ws1("http://localhost:8080/path");
  20704. EXPECT_FALSE(ws1.is_valid());
  20705. ws::WebSocketClient ws2("https://localhost:8080/path");
  20706. EXPECT_FALSE(ws2.is_valid());
  20707. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20708. EXPECT_FALSE(ws3.is_valid());
  20709. #else
  20710. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20711. std::invalid_argument);
  20712. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20713. std::invalid_argument);
  20714. #endif
  20715. }
  20716. TEST(WebSocketTest, ConnectWhenInvalid) {
  20717. ws::WebSocketClient ws("not a valid url");
  20718. EXPECT_FALSE(ws.is_valid());
  20719. auto res = ws.connect();
  20720. EXPECT_FALSE(res);
  20721. EXPECT_EQ(Error::Connection, res.error());
  20722. EXPECT_EQ(-1, res.status());
  20723. }
  20724. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20725. // Grab a port that is free, then close it again so nothing listens there
  20726. Server svr;
  20727. auto port = svr.bind_to_any_port(HOST);
  20728. svr.stop();
  20729. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20730. auto res = client.connect();
  20731. ASSERT_FALSE(res);
  20732. EXPECT_EQ(Error::Connection, res.error());
  20733. EXPECT_EQ(-1, res.status());
  20734. }
  20735. TEST(WebSocketTest, DefaultPort) {
  20736. ws::WebSocketClient ws1("ws://example.com/path");
  20737. EXPECT_TRUE(ws1.is_valid());
  20738. // ws:// defaults to port 80 (verified by successful parse)
  20739. #ifdef CPPHTTPLIB_SSL_ENABLED
  20740. ws::WebSocketClient ws2("wss://example.com/path");
  20741. EXPECT_TRUE(ws2.is_valid());
  20742. // wss:// defaults to port 443 (verified by successful parse)
  20743. #endif
  20744. }
  20745. TEST(WebSocketTest, IPv6LiteralAddress) {
  20746. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20747. EXPECT_TRUE(ws1.is_valid());
  20748. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20749. EXPECT_TRUE(ws2.is_valid());
  20750. }
  20751. TEST(WebSocketTest, ComplexPath) {
  20752. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20753. EXPECT_TRUE(ws1.is_valid());
  20754. ws::WebSocketClient ws2("ws://localhost:8080/");
  20755. EXPECT_TRUE(ws2.is_valid());
  20756. }
  20757. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20758. Server svr;
  20759. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20760. std::string msg;
  20761. while (ws.read(msg)) {}
  20762. });
  20763. auto port = svr.bind_to_any_port(HOST);
  20764. std::thread t([&]() { svr.listen_after_bind(); });
  20765. svr.wait_until_ready();
  20766. auto another_host = "example.com";
  20767. auto wrong_ip = "192.0.2.1";
  20768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20769. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20770. ASSERT_TRUE(client.connect());
  20771. EXPECT_TRUE(client.is_open());
  20772. client.close();
  20773. svr.stop();
  20774. t.join();
  20775. }
  20776. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20777. Server svr;
  20778. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20779. std::string msg;
  20780. while (ws.read(msg)) {}
  20781. });
  20782. auto port = svr.bind_to_any_port(HOST);
  20783. std::thread t([&]() { svr.listen_after_bind(); });
  20784. svr.wait_until_ready();
  20785. auto wrong_ip = "192.0.2.1";
  20786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20787. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20788. client.set_connection_timeout(1);
  20789. client.set_read_timeout(1);
  20790. client.set_write_timeout(1);
  20791. EXPECT_FALSE(client.connect());
  20792. EXPECT_FALSE(client.is_open());
  20793. svr.stop();
  20794. t.join();
  20795. }
  20796. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20797. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20798. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20799. // (RFC 6761) is only a map key and the Host header value.
  20800. auto host = "target.invalid";
  20801. Server svr;
  20802. std::string received_host;
  20803. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20804. received_host = req.get_header_value("Host");
  20805. std::string msg;
  20806. while (ws.read(msg)) {}
  20807. });
  20808. auto port = svr.bind_to_any_port(HOST);
  20809. std::thread t([&]() { svr.listen_after_bind(); });
  20810. // ASSERT_* below returns from the test body, which would leave t joinable
  20811. // and make ~thread call std::terminate.
  20812. auto se = detail::scope_exit([&] {
  20813. svr.stop();
  20814. if (t.joinable()) { t.join(); }
  20815. });
  20816. svr.wait_until_ready();
  20817. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20818. std::to_string(port) + "/ws");
  20819. client.set_hostname_addr_map({{host, HOST}});
  20820. ASSERT_TRUE(client.connect());
  20821. EXPECT_TRUE(client.is_open());
  20822. client.close();
  20823. svr.stop();
  20824. t.join();
  20825. // The mapping only redirects the connection; the identity stays host_.
  20826. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20827. }
  20828. class WebSocketIntegrationTest : public ::testing::Test {
  20829. protected:
  20830. void SetUp() override {
  20831. server_ = httplib::detail::make_unique<Server>();
  20832. setup_server();
  20833. start_server();
  20834. }
  20835. void TearDown() override {
  20836. server_->stop();
  20837. if (server_thread_.joinable()) { server_thread_.join(); }
  20838. }
  20839. void setup_server() {
  20840. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20841. std::string msg;
  20842. ws::ReadResult ret;
  20843. while ((ret = ws.read(msg))) {
  20844. if (ret == ws::Binary) {
  20845. ws.send(msg.data(), msg.size());
  20846. } else {
  20847. ws.send(msg);
  20848. }
  20849. }
  20850. });
  20851. server_->WebSocket("/ws-echo-string",
  20852. [](const Request &, ws::WebSocket &ws) {
  20853. std::string msg;
  20854. while (ws.read(msg)) {
  20855. ws.send("echo: " + msg);
  20856. }
  20857. });
  20858. server_->WebSocket(
  20859. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20860. // Echo back request metadata
  20861. ws.send("path:" + req.path);
  20862. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20863. std::string msg;
  20864. while (ws.read(msg)) {}
  20865. });
  20866. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20867. std::string msg;
  20868. ws.read(msg); // wait for a message
  20869. ws.close();
  20870. });
  20871. server_->WebSocket("/ws-close-status",
  20872. [](const Request &, ws::WebSocket &ws) {
  20873. std::string msg;
  20874. ws.read(msg); // wait for a message
  20875. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20876. });
  20877. server_->WebSocket(
  20878. "/ws-subprotocol",
  20879. [](const Request &, ws::WebSocket &ws) {
  20880. std::string msg;
  20881. while (ws.read(msg)) {
  20882. ws.send(msg);
  20883. }
  20884. },
  20885. [](const std::vector<std::string> &protocols) -> std::string {
  20886. for (const auto &p : protocols) {
  20887. if (p == "graphql-ws") { return p; }
  20888. }
  20889. return "";
  20890. });
  20891. server_->WebSocket(
  20892. "/ws-subprotocol-unoffered",
  20893. [](const Request &, ws::WebSocket &ws) {
  20894. std::string msg;
  20895. while (ws.read(msg)) {
  20896. ws.send(msg);
  20897. }
  20898. },
  20899. [](const std::vector<std::string> &) -> std::string {
  20900. return "admin";
  20901. });
  20902. }
  20903. void start_server() {
  20904. port_ = server_->bind_to_any_port(HOST);
  20905. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20906. server_->wait_until_ready();
  20907. }
  20908. std::unique_ptr<Server> server_;
  20909. std::thread server_thread_;
  20910. int port_ = 0;
  20911. };
  20912. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20914. "/ws-echo");
  20915. ASSERT_TRUE(client.connect());
  20916. ASSERT_TRUE(client.is_open());
  20917. ASSERT_TRUE(client.send("Hello WebSocket"));
  20918. std::string msg;
  20919. EXPECT_EQ(ws::Text, client.read(msg));
  20920. EXPECT_EQ("Hello WebSocket", msg);
  20921. client.close();
  20922. }
  20923. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20925. "/ws-echo");
  20926. ASSERT_TRUE(client.connect());
  20927. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20928. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20929. std::string msg;
  20930. EXPECT_EQ(ws::Binary, client.read(msg));
  20931. EXPECT_EQ(binary_data, msg);
  20932. client.close();
  20933. }
  20934. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20935. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20936. "/ws-echo");
  20937. ASSERT_TRUE(client.connect());
  20938. for (int i = 0; i < 10; i++) {
  20939. auto text = "message " + std::to_string(i);
  20940. ASSERT_TRUE(client.send(text));
  20941. std::string msg;
  20942. ASSERT_TRUE(client.read(msg));
  20943. EXPECT_EQ(text, msg);
  20944. }
  20945. client.close();
  20946. }
  20947. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20948. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20949. "/ws-close");
  20950. ASSERT_TRUE(client.connect());
  20951. // Send a message to trigger the server to close
  20952. ASSERT_TRUE(client.send("trigger close"));
  20953. // The server will close, so read should return false
  20954. std::string msg;
  20955. EXPECT_FALSE(client.read(msg));
  20956. EXPECT_FALSE(client.is_open());
  20957. }
  20958. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20959. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20960. "/ws-echo");
  20961. ASSERT_TRUE(client.connect());
  20962. // 128KB message
  20963. std::string large_data(128 * 1024, 'X');
  20964. ASSERT_TRUE(client.send(large_data));
  20965. std::string msg;
  20966. ASSERT_TRUE(client.read(msg));
  20967. EXPECT_EQ(large_data, msg);
  20968. client.close();
  20969. }
  20970. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20972. "/ws-echo");
  20973. ASSERT_TRUE(client.connect());
  20974. const int num_threads = 4;
  20975. std::vector<std::thread> threads;
  20976. std::atomic<int> send_count{0};
  20977. for (int t = 0; t < num_threads; t++) {
  20978. threads.emplace_back([&client, &send_count, t]() {
  20979. for (int i = 0; i < 5; i++) {
  20980. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20981. if (client.send(text)) { send_count++; }
  20982. }
  20983. });
  20984. }
  20985. for (auto &th : threads) {
  20986. th.join();
  20987. }
  20988. int received = 0;
  20989. std::string msg;
  20990. while (received < send_count.load()) {
  20991. if (!client.read(msg)) { break; }
  20992. received++;
  20993. }
  20994. EXPECT_EQ(send_count.load(), received);
  20995. client.close();
  20996. }
  20997. TEST_F(WebSocketIntegrationTest, ReadString) {
  20998. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20999. "/ws-echo-string");
  21000. ASSERT_TRUE(client.connect());
  21001. ASSERT_TRUE(client.send("hello"));
  21002. std::string msg;
  21003. ASSERT_TRUE(client.read(msg));
  21004. EXPECT_EQ("echo: hello", msg);
  21005. ASSERT_TRUE(client.send("world"));
  21006. ASSERT_TRUE(client.read(msg));
  21007. EXPECT_EQ("echo: world", msg);
  21008. client.close();
  21009. }
  21010. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21011. Headers headers = {{"X-Test-Header", "test-value"}};
  21012. ws::WebSocketClient client(
  21013. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21014. ASSERT_TRUE(client.connect());
  21015. std::string msg;
  21016. ASSERT_TRUE(client.read(msg));
  21017. EXPECT_EQ("path:/ws-request-info", msg);
  21018. ASSERT_TRUE(client.read(msg));
  21019. EXPECT_EQ("header:test-value", msg);
  21020. client.close();
  21021. }
  21022. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21024. "/ws-echo");
  21025. client.set_read_timeout(1, 0); // 1 second
  21026. ASSERT_TRUE(client.connect());
  21027. // Don't send anything — server echo handler waits for a message, so read()
  21028. // should time out. The connection survives it: nothing was consumed.
  21029. std::string msg;
  21030. EXPECT_EQ(client.read(msg), ws::Timeout);
  21031. EXPECT_TRUE(client.is_open());
  21032. // And it is still usable afterwards.
  21033. EXPECT_TRUE(client.send("after timeout"));
  21034. EXPECT_EQ(client.read(msg), ws::Text);
  21035. EXPECT_EQ(msg, "after timeout");
  21036. }
  21037. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21039. "/ws-echo");
  21040. client.set_read_timeout(1, 0);
  21041. ASSERT_TRUE(client.connect());
  21042. ASSERT_TRUE(client.send("first"));
  21043. std::string msg;
  21044. ASSERT_EQ(client.read(msg), ws::Text);
  21045. ASSERT_EQ(msg, "first");
  21046. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21047. // not be used with a read timeout: it would reprocess the previous message.
  21048. EXPECT_EQ(client.read(msg), ws::Timeout);
  21049. EXPECT_EQ(msg, "first");
  21050. }
  21051. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21052. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21053. "/ws-echo");
  21054. ASSERT_TRUE(client.connect());
  21055. // Setting it once the connection is open reaches the live stream, not just
  21056. // the seed for the next connect().
  21057. client.set_read_timeout(1, 0);
  21058. std::string msg;
  21059. EXPECT_EQ(client.read(msg), ws::Timeout);
  21060. EXPECT_TRUE(client.is_open());
  21061. }
  21062. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21064. "/ws-echo");
  21065. client.set_read_timeout(5, 0);
  21066. ASSERT_TRUE(client.connect());
  21067. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21068. // The server should reject it and close the connection.
  21069. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21070. client.send(oversized);
  21071. // The server's read() should have failed due to payload limit,
  21072. // so our read() should return false (connection closed).
  21073. std::string msg;
  21074. EXPECT_FALSE(client.read(msg));
  21075. }
  21076. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21078. "/ws-echo");
  21079. client.set_read_timeout(10, 0);
  21080. ASSERT_TRUE(client.connect());
  21081. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21082. // This should succeed.
  21083. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21084. ASSERT_TRUE(client.send(at_limit));
  21085. std::string msg;
  21086. ASSERT_TRUE(client.read(msg));
  21087. EXPECT_EQ(at_limit.size(), msg.size());
  21088. client.close();
  21089. }
  21090. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21092. "/nonexistent");
  21093. auto res = client.connect();
  21094. EXPECT_FALSE(res);
  21095. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21096. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21097. EXPECT_FALSE(client.is_open());
  21098. }
  21099. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21100. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21101. "/ws-echo");
  21102. ASSERT_TRUE(client.connect());
  21103. ASSERT_TRUE(client.send(""));
  21104. std::string msg;
  21105. EXPECT_EQ(ws::Text, client.read(msg));
  21106. EXPECT_EQ("", msg);
  21107. client.close();
  21108. }
  21109. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21110. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21111. "/ws-echo");
  21112. // First connection
  21113. ASSERT_TRUE(client.connect());
  21114. ASSERT_TRUE(client.send("first"));
  21115. std::string msg;
  21116. ASSERT_TRUE(client.read(msg));
  21117. EXPECT_EQ("first", msg);
  21118. client.close();
  21119. EXPECT_FALSE(client.is_open());
  21120. // Reconnect using the same client object
  21121. ASSERT_TRUE(client.connect());
  21122. ASSERT_TRUE(client.is_open());
  21123. ASSERT_TRUE(client.send("second"));
  21124. ASSERT_TRUE(client.read(msg));
  21125. EXPECT_EQ("second", msg);
  21126. client.close();
  21127. }
  21128. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21130. "/ws-close-status");
  21131. ASSERT_TRUE(client.connect());
  21132. // Trigger the server to close with GoingAway status
  21133. ASSERT_TRUE(client.send("trigger"));
  21134. // read() should return false after receiving the close frame
  21135. std::string msg;
  21136. EXPECT_FALSE(client.read(msg));
  21137. EXPECT_FALSE(client.is_open());
  21138. }
  21139. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21141. "/ws-echo");
  21142. ASSERT_TRUE(client.connect());
  21143. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21144. EXPECT_FALSE(client.is_open());
  21145. }
  21146. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21147. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21148. ws::WebSocketClient client(
  21149. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21150. ASSERT_TRUE(client.connect());
  21151. // Server should have selected graphql-ws
  21152. EXPECT_EQ("graphql-ws", client.subprotocol());
  21153. client.close();
  21154. }
  21155. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21156. Headers headers;
  21157. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21158. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21159. ws::WebSocketClient client(
  21160. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21161. ASSERT_TRUE(client.connect());
  21162. // The offer on the second field line counts too, so graphql-ws is selected
  21163. EXPECT_EQ("graphql-ws", client.subprotocol());
  21164. client.close();
  21165. }
  21166. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21167. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21168. ws::WebSocketClient client(
  21169. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21170. ASSERT_TRUE(client.connect());
  21171. // Server should not have selected any subprotocol
  21172. EXPECT_TRUE(client.subprotocol().empty());
  21173. client.close();
  21174. }
  21175. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21176. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21177. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21178. "/ws-subprotocol-unoffered",
  21179. headers);
  21180. ASSERT_TRUE(client.connect());
  21181. EXPECT_TRUE(client.subprotocol().empty());
  21182. client.close();
  21183. }
  21184. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21185. // Connect without requesting any subprotocol
  21186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21187. "/ws-subprotocol");
  21188. ASSERT_TRUE(client.connect());
  21189. EXPECT_TRUE(client.subprotocol().empty());
  21190. client.close();
  21191. }
  21192. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21194. "/ws-echo");
  21195. client.set_tcp_nodelay(true);
  21196. client.set_connection_timeout(3, 0);
  21197. bool socket_options_called = false;
  21198. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21199. ASSERT_TRUE(client.connect());
  21200. ASSERT_TRUE(client.is_open());
  21201. EXPECT_TRUE(socket_options_called);
  21202. ASSERT_TRUE(client.send("hello"));
  21203. std::string msg;
  21204. auto result = client.read(msg);
  21205. EXPECT_EQ(result, ws::ReadResult::Text);
  21206. EXPECT_EQ(msg, "hello");
  21207. client.close();
  21208. }
  21209. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21211. "/ws-echo");
  21212. client.set_connection_timeout(std::chrono::seconds(3));
  21213. client.set_write_timeout(std::chrono::seconds(3));
  21214. // A sub-second remainder exercises the seconds/microseconds split.
  21215. client.set_read_timeout(std::chrono::milliseconds(1500));
  21216. ASSERT_TRUE(client.connect());
  21217. auto start = std::chrono::steady_clock::now();
  21218. std::string msg;
  21219. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21220. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21221. std::chrono::steady_clock::now() - start)
  21222. .count();
  21223. // Above 1s so that dropping the microseconds half of the split fails here.
  21224. // Ignoring the setter altogether would not reach this line at all: a client
  21225. // waits forever by default.
  21226. EXPECT_GE(elapsed, 1400);
  21227. EXPECT_LT(elapsed, 30000);
  21228. }
  21229. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21230. Server svr;
  21231. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21232. if (!req.has_header("Authorization")) {
  21233. res.status = StatusCode::Unauthorized_401;
  21234. res.set_content("Unauthorized", "text/plain");
  21235. return Server::HandlerResponse::Handled;
  21236. }
  21237. return Server::HandlerResponse::Unhandled;
  21238. });
  21239. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21240. std::string msg;
  21241. while (ws.read(msg)) {
  21242. ws.send(msg);
  21243. }
  21244. });
  21245. auto port = svr.bind_to_any_port("localhost");
  21246. std::thread t([&]() { svr.listen_after_bind(); });
  21247. svr.wait_until_ready();
  21248. // Without Authorization header - should be rejected before upgrade
  21249. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21250. EXPECT_FALSE(client1.connect());
  21251. // The rejection is framed like any other HTTP response
  21252. {
  21253. Client cli("localhost", port);
  21254. Headers headers = {{"Upgrade", "websocket"},
  21255. {"Connection", "Upgrade"},
  21256. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21257. {"Sec-WebSocket-Version", "13"}};
  21258. auto res = cli.Get("/ws", headers);
  21259. ASSERT_TRUE(res);
  21260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21261. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21262. EXPECT_EQ("Unauthorized", res->body);
  21263. }
  21264. // With Authorization header - should succeed
  21265. Headers headers = {{"Authorization", "Bearer token123"}};
  21266. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21267. headers);
  21268. ASSERT_TRUE(client2.connect());
  21269. ASSERT_TRUE(client2.send("hello"));
  21270. std::string msg;
  21271. ASSERT_TRUE(client2.read(msg));
  21272. EXPECT_EQ("hello", msg);
  21273. client2.close();
  21274. svr.stop();
  21275. t.join();
  21276. }
  21277. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21278. Server svr;
  21279. std::atomic<int> pre_request_calls{0};
  21280. std::atomic<bool> route_matched{false};
  21281. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21282. pre_request_calls++;
  21283. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21284. if (req.get_header_value("Authorization") != "Bearer token123") {
  21285. res.status = StatusCode::Unauthorized_401;
  21286. res.set_content("Unauthorized", "text/plain");
  21287. return Server::HandlerResponse::Handled;
  21288. }
  21289. return Server::HandlerResponse::Unhandled;
  21290. });
  21291. std::atomic<bool> handler_called{false};
  21292. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21293. handler_called = true;
  21294. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21295. });
  21296. auto port = svr.bind_to_any_port("localhost");
  21297. std::thread t([&]() { svr.listen_after_bind(); });
  21298. svr.wait_until_ready();
  21299. // Without Authorization header - should be rejected before upgrade
  21300. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21301. "/ws/1");
  21302. EXPECT_FALSE(client1.connect());
  21303. EXPECT_FALSE(handler_called);
  21304. EXPECT_EQ(1, pre_request_calls);
  21305. EXPECT_TRUE(route_matched);
  21306. // The rejection is an ordinary HTTP response, not a protocol switch
  21307. {
  21308. Client cli("localhost", port);
  21309. Headers headers = {{"Upgrade", "websocket"},
  21310. {"Connection", "Upgrade"},
  21311. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21312. {"Sec-WebSocket-Version", "13"}};
  21313. auto res = cli.Get("/ws/1", headers);
  21314. ASSERT_TRUE(res);
  21315. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21316. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21317. EXPECT_EQ("Unauthorized", res->body);
  21318. }
  21319. EXPECT_FALSE(handler_called);
  21320. // With Authorization header - should succeed
  21321. Headers headers = {{"Authorization", "Bearer token123"}};
  21322. ws::WebSocketClient client2(
  21323. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21324. ASSERT_TRUE(client2.connect());
  21325. std::string msg;
  21326. ASSERT_TRUE(client2.read(msg));
  21327. EXPECT_EQ("/ws/:id 2", msg);
  21328. EXPECT_TRUE(handler_called);
  21329. client2.close();
  21330. svr.stop();
  21331. t.join();
  21332. }
  21333. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21334. Server svr;
  21335. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21336. // A read timeout is how a handler gets control back. Without it, a handler
  21337. // parked in read() can never write on the connection it is reading.
  21338. ws.set_read_timeout(std::chrono::milliseconds(100));
  21339. std::string msg;
  21340. while (ws.is_open()) {
  21341. auto r = ws.read(msg);
  21342. if (r == httplib::ws::Timeout) {
  21343. ws.send("tick");
  21344. continue;
  21345. }
  21346. if (r == httplib::ws::Fail) { break; }
  21347. ws.send(msg);
  21348. }
  21349. });
  21350. auto port = svr.bind_to_any_port("localhost");
  21351. std::thread t([&]() { svr.listen_after_bind(); });
  21352. svr.wait_until_ready();
  21353. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21354. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21355. ASSERT_TRUE(client.connect());
  21356. // The client sends nothing, so anything it receives came out of the
  21357. // handler's timeout path.
  21358. std::string msg;
  21359. ASSERT_EQ(client.read(msg), ws::Text);
  21360. EXPECT_EQ("tick", msg);
  21361. client.close();
  21362. svr.stop();
  21363. t.join();
  21364. }
  21365. // Stream::read may return fewer bytes than asked for. This is that contract at
  21366. // its worst -- one byte per call -- which is what a frame header straddling a
  21367. // read buffer's boundary looks like to the frame parser.
  21368. class WsByteAtATimeStream : public Stream {
  21369. public:
  21370. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21371. bool is_readable() const override { return true; }
  21372. bool wait_readable() const override { return true; }
  21373. bool wait_writable() const override { return true; }
  21374. ssize_t read(char *ptr, size_t size) override {
  21375. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21376. *ptr = data_[pos_++];
  21377. return 1;
  21378. }
  21379. ssize_t write(const char *, size_t size) override {
  21380. return static_cast<ssize_t>(size);
  21381. }
  21382. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21383. ip = "127.0.0.1";
  21384. port = 0;
  21385. }
  21386. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21387. ip = "127.0.0.1";
  21388. port = 0;
  21389. }
  21390. socket_t socket() const override { return INVALID_SOCKET; }
  21391. time_t duration() const override { return 0; }
  21392. private:
  21393. std::string data_;
  21394. size_t pos_ = 0;
  21395. };
  21396. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21397. // The payload uses the 16-bit extended length, so the header, the length
  21398. // and the mask key are all multi-byte fields here. Each used to be read
  21399. // with a single read() call, which fails as soon as one is split. The
  21400. // payload is also a little over one read chunk, so it is read in two.
  21401. std::string body;
  21402. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21403. body += static_cast<char>(i % 251);
  21404. }
  21405. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21406. std::string frame;
  21407. frame += static_cast<char>(0x81); // FIN + Text
  21408. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21409. frame += static_cast<char>(body.size() >> 8);
  21410. frame += static_cast<char>(body.size() & 0xff);
  21411. for (size_t i = 0; i < 4; i++) {
  21412. frame += static_cast<char>(mask[i]);
  21413. }
  21414. for (size_t i = 0; i < body.size(); i++) {
  21415. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21416. }
  21417. WsByteAtATimeStream strm(frame);
  21418. ws::Opcode opcode;
  21419. std::string payload;
  21420. bool fin = false;
  21421. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21422. /*expect_masked=*/true, body.size()),
  21423. ws::impl::FrameRead::Ok);
  21424. EXPECT_TRUE(fin);
  21425. EXPECT_EQ(opcode, ws::Opcode::Text);
  21426. EXPECT_EQ(payload, body);
  21427. }
  21428. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21429. // The header announces the largest payload allowed, and only 3 bytes of it
  21430. // ever arrive.
  21431. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21432. std::string frame;
  21433. frame += static_cast<char>(0x82); // FIN + Binary
  21434. frame += static_cast<char>(127); // 64-bit length follows
  21435. for (int shift = 56; shift >= 0; shift -= 8) {
  21436. frame += static_cast<char>((len >> shift) & 0xff);
  21437. }
  21438. frame += "abc";
  21439. detail::BufferStream strm;
  21440. strm.write(frame.data(), frame.size());
  21441. ws::Opcode opcode;
  21442. std::string payload;
  21443. bool fin;
  21444. EXPECT_EQ(
  21445. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21446. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21447. ws::impl::FrameRead::Fail);
  21448. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21449. }
  21450. TEST(WebSocketTest, QueryStringInHandshake) {
  21451. Server svr;
  21452. std::mutex mtx;
  21453. std::string received_target;
  21454. std::string received_token;
  21455. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21456. {
  21457. std::lock_guard<std::mutex> lock(mtx);
  21458. received_target = req.target;
  21459. if (req.has_param("token")) {
  21460. received_token = req.get_param_value("token");
  21461. }
  21462. }
  21463. std::string msg;
  21464. while (ws.read(msg)) {
  21465. ws.send(msg);
  21466. }
  21467. });
  21468. auto port = svr.bind_to_any_port("localhost");
  21469. std::thread t([&]() { svr.listen_after_bind(); });
  21470. svr.wait_until_ready();
  21471. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21472. "/ws?token=ABC&session=123");
  21473. ASSERT_TRUE(client.connect());
  21474. // Round-trip ensures the handler has run and captured the request.
  21475. ASSERT_TRUE(client.send("hello"));
  21476. std::string msg;
  21477. ASSERT_TRUE(client.read(msg));
  21478. EXPECT_EQ("hello", msg);
  21479. client.close();
  21480. {
  21481. std::lock_guard<std::mutex> lock(mtx);
  21482. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21483. EXPECT_EQ("ABC", received_token);
  21484. }
  21485. svr.stop();
  21486. t.join();
  21487. }
  21488. // Run a handshake against a throwaway server and hand the request the server
  21489. // received back to the caller, so tests can assert on the headers the client
  21490. // actually put on the wire.
  21491. static void capture_websocket_handshake_request(
  21492. const Headers &client_headers,
  21493. std::function<void(const Request &, int port)> verify) {
  21494. Server svr;
  21495. std::mutex mtx;
  21496. Request received;
  21497. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21498. {
  21499. std::lock_guard<std::mutex> lock(mtx);
  21500. received = req;
  21501. }
  21502. std::string msg;
  21503. while (ws.read(msg)) {
  21504. ws.send(msg);
  21505. }
  21506. });
  21507. auto port = svr.bind_to_any_port("localhost");
  21508. std::thread t([&]() { svr.listen_after_bind(); });
  21509. auto se = detail::scope_exit([&] {
  21510. svr.stop();
  21511. t.join();
  21512. });
  21513. svr.wait_until_ready();
  21514. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21515. client_headers);
  21516. ASSERT_TRUE(client.connect());
  21517. ASSERT_TRUE(client.send("hello"));
  21518. std::string msg;
  21519. ASSERT_TRUE(client.read(msg));
  21520. client.close();
  21521. {
  21522. std::lock_guard<std::mutex> lock(mtx);
  21523. verify(received, port);
  21524. }
  21525. }
  21526. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21527. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21528. // Non-default port must be present in the Host header. Default ports
  21529. // (80/443) are omitted; that logic is covered by
  21530. // MakeHostAndPortStringTest.
  21531. EXPECT_EQ("localhost:" + std::to_string(port),
  21532. req.get_header_value("Host"));
  21533. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21534. req.get_header_value("User-Agent"));
  21535. EXPECT_FALSE(req.has_header("Accept"));
  21536. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21537. EXPECT_FALSE(req.has_header("Content-Length"));
  21538. });
  21539. }
  21540. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21541. capture_websocket_handshake_request(
  21542. {{"Host", "example.com"},
  21543. {"User-Agent", "custom-agent"},
  21544. {"X-Custom", "value"}},
  21545. [](const Request &req, int) {
  21546. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21547. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21548. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21549. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21550. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21551. });
  21552. }
  21553. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21554. capture_websocket_handshake_request(
  21555. {{"Upgrade", "bogus"},
  21556. {"Connection", "close"},
  21557. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21558. {"Sec-WebSocket-Version", "8"}},
  21559. [](const Request &req, int) {
  21560. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21561. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21562. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21563. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21564. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21565. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21566. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21567. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21568. req.get_header_value("Sec-WebSocket-Key"));
  21569. });
  21570. }
  21571. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21572. // A header the client refuses to send must abort the handshake before any
  21573. // part of it reaches the wire; a lone request line would otherwise sit in
  21574. // the peer's buffer as a truncated request.
  21575. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21576. ASSERT_NE(INVALID_SOCKET, srv);
  21577. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21578. sockaddr_in addr{};
  21579. addr.sin_family = AF_INET;
  21580. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21581. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21582. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21583. ASSERT_EQ(0, ::listen(srv, 1));
  21584. sockaddr_in bound{};
  21585. socklen_t bound_len = sizeof(bound);
  21586. ASSERT_EQ(
  21587. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21588. auto port = ntohs(bound.sin_port);
  21589. ssize_t received = -1;
  21590. std::thread t([&] {
  21591. // Bound every blocking call so a regression fails the test with a bad
  21592. // value instead of hanging the suite.
  21593. fd_set rfds;
  21594. FD_ZERO(&rfds);
  21595. FD_SET(srv, &rfds);
  21596. timeval tv{5, 0};
  21597. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21598. 0) {
  21599. return;
  21600. }
  21601. sockaddr_in cli_addr{};
  21602. socklen_t cli_len = sizeof(cli_addr);
  21603. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21604. if (cli == INVALID_SOCKET) { return; }
  21605. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21606. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21607. char buf[4096];
  21608. received = ::recv(cli, buf, sizeof(buf), 0);
  21609. });
  21610. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21611. // connect() has already shut the socket down by the time it returns false,
  21612. // so the peer sees EOF without waiting for the client to be destroyed.
  21613. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21614. {{"X-Bad", "a\r\nInjected: 1"}});
  21615. EXPECT_FALSE(client.connect());
  21616. t.join();
  21617. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21618. EXPECT_EQ(0, received);
  21619. }
  21620. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21621. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21622. // contains "upgrade" as a substring is a different token and must not
  21623. // start a WebSocket handshake.
  21624. auto make_request = [](const std::vector<std::string> &connection_values) {
  21625. Request req;
  21626. req.method = "GET";
  21627. req.headers.emplace("Upgrade", "websocket");
  21628. for (const auto &value : connection_values) {
  21629. req.headers.emplace("Connection", value);
  21630. }
  21631. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21632. req.headers.emplace("Sec-WebSocket-Version", "13");
  21633. return req;
  21634. };
  21635. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21636. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21637. EXPECT_TRUE(
  21638. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21639. EXPECT_TRUE(
  21640. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21641. EXPECT_TRUE(
  21642. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21643. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21644. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21645. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21646. EXPECT_FALSE(
  21647. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21648. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21649. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21650. }
  21651. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21652. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21653. // asks recipients to match each protocol-name case-insensitively, and RFC
  21654. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21655. // client naming websocket alongside another protocol, or on a second field
  21656. // line, is offering websocket; a value that merely contains "websocket" as a
  21657. // substring is a different protocol name and is not.
  21658. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21659. Request req;
  21660. req.method = "GET";
  21661. for (const auto &value : upgrade_values) {
  21662. req.headers.emplace("Upgrade", value);
  21663. }
  21664. req.headers.emplace("Connection", "Upgrade");
  21665. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21666. req.headers.emplace("Sec-WebSocket-Version", "13");
  21667. return req;
  21668. };
  21669. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21670. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21671. EXPECT_TRUE(
  21672. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21673. EXPECT_TRUE(
  21674. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21675. EXPECT_TRUE(
  21676. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21677. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21678. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21679. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21680. EXPECT_FALSE(
  21681. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21682. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21683. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21684. }
  21685. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21686. Server svr;
  21687. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21688. auto port = svr.bind_to_any_port("localhost");
  21689. std::thread t([&]() { svr.listen_after_bind(); });
  21690. auto se = detail::scope_exit([&] {
  21691. svr.stop();
  21692. t.join();
  21693. });
  21694. svr.wait_until_ready();
  21695. Headers headers = {{"Upgrade", "websocket"},
  21696. {"Connection", "notupgrade"},
  21697. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21698. {"Sec-WebSocket-Version", "13"}};
  21699. Client cli("localhost", port);
  21700. auto res = cli.Get("/ws", headers);
  21701. // The route exists only as a WebSocket route, so a request that fails the
  21702. // handshake check falls through to ordinary routing.
  21703. ASSERT_TRUE(res);
  21704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21705. }
  21706. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21707. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21708. // Connection value is the only thing left for the client to reject.
  21709. Server svr;
  21710. svr.Get("/ws", [](const Request &req, Response &res) {
  21711. res.status = StatusCode::SwitchingProtocol_101;
  21712. res.set_header("Upgrade", "websocket");
  21713. res.set_header("Connection", "notupgrade");
  21714. res.set_header("Sec-WebSocket-Accept",
  21715. detail::websocket_accept_key(
  21716. req.get_header_value("Sec-WebSocket-Key")));
  21717. });
  21718. auto port = svr.bind_to_any_port("localhost");
  21719. std::thread t([&]() { svr.listen_after_bind(); });
  21720. auto se = detail::scope_exit([&] {
  21721. svr.stop();
  21722. t.join();
  21723. });
  21724. svr.wait_until_ready();
  21725. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21726. auto res = client.connect();
  21727. EXPECT_FALSE(res);
  21728. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21729. EXPECT_FALSE(client.is_open());
  21730. }
  21731. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21732. Server svr;
  21733. svr.Get("/ws", [](const Request &req, Response &res) {
  21734. res.status = StatusCode::SwitchingProtocol_101;
  21735. res.set_header("Upgrade", "websocket");
  21736. res.set_header("Connection", "Upgrade");
  21737. res.set_header("Sec-WebSocket-Accept",
  21738. detail::websocket_accept_key(
  21739. req.get_header_value("Sec-WebSocket-Key")));
  21740. res.set_header("Sec-WebSocket-Protocol", "admin");
  21741. });
  21742. auto port = svr.bind_to_any_port("localhost");
  21743. std::thread t([&]() { svr.listen_after_bind(); });
  21744. auto se = detail::scope_exit([&] {
  21745. svr.stop();
  21746. t.join();
  21747. });
  21748. svr.wait_until_ready();
  21749. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21750. // Server selects a subprotocol the client never offered
  21751. {
  21752. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21753. ws::WebSocketClient client(url, headers);
  21754. auto res = client.connect();
  21755. EXPECT_FALSE(res);
  21756. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21757. EXPECT_FALSE(client.is_open());
  21758. EXPECT_TRUE(client.subprotocol().empty());
  21759. }
  21760. // Client offered none but the server named one anyway
  21761. {
  21762. ws::WebSocketClient client(url);
  21763. auto res = client.connect();
  21764. EXPECT_FALSE(res);
  21765. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21766. EXPECT_FALSE(client.is_open());
  21767. EXPECT_TRUE(client.subprotocol().empty());
  21768. }
  21769. }
  21770. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21771. // The socket path doubles as the URL host, so it must not contain '/'.
  21772. const char *shard = getenv("GTEST_SHARD_INDEX");
  21773. const std::string sock_path =
  21774. shard ? std::string("httplib-ws-") + shard + ".sock"
  21775. : std::string("httplib-ws.sock");
  21776. std::remove(sock_path.c_str());
  21777. Server svr;
  21778. std::mutex mtx;
  21779. std::string received_host;
  21780. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21781. {
  21782. std::lock_guard<std::mutex> lock(mtx);
  21783. received_host = req.get_header_value("Host");
  21784. }
  21785. std::string msg;
  21786. while (ws.read(msg)) {
  21787. ws.send(msg);
  21788. }
  21789. });
  21790. svr.set_address_family(AF_UNIX);
  21791. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21792. auto se = detail::scope_exit([&] {
  21793. svr.stop();
  21794. t.join();
  21795. std::remove(sock_path.c_str());
  21796. });
  21797. svr.wait_until_ready();
  21798. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21799. client.set_address_family(AF_UNIX);
  21800. ASSERT_TRUE(client.connect());
  21801. ASSERT_TRUE(client.send("hello"));
  21802. std::string msg;
  21803. ASSERT_TRUE(client.read(msg));
  21804. client.close();
  21805. {
  21806. std::lock_guard<std::mutex> lock(mtx);
  21807. // There is no host:port for a Unix socket, so the same "localhost"
  21808. // placeholder the HTTP client uses is expected.
  21809. EXPECT_EQ("localhost", received_host);
  21810. }
  21811. }
  21812. // Two threads must never parse WebSocket frames from the same stream.
  21813. // close() used to read the peer's Close reply with its own frame read, so it
  21814. // raced a reader thread that was in the middle of a payload: the payload loop
  21815. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21816. // so bytes taken by close() were replaced with bytes from further along the
  21817. // stream. The message kept its length and silently changed content.
  21818. //
  21819. // The raw peer below sends a frame header plus part of the payload, waits for
  21820. // the handler to call close(), and only then sends the rest. Whichever thread
  21821. // would win the race for those bytes, the message must arrive intact, because
  21822. // close() must not touch the stream while read() owns it.
  21823. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21824. #ifndef _WIN32
  21825. signal(SIGPIPE, SIG_IGN);
  21826. #endif
  21827. const size_t payload_len = 120; // fits the 7-bit length field
  21828. const size_t prefix_len = 8;
  21829. const int attempts = 8;
  21830. std::string expected(payload_len, '\0');
  21831. for (size_t i = 0; i < payload_len; i++) {
  21832. expected[i] = static_cast<char>('a' + i % 26);
  21833. }
  21834. std::atomic<bool> peer_stalled{false};
  21835. std::atomic<bool> handler_done{false};
  21836. std::mutex received_mutex;
  21837. std::vector<std::string> received;
  21838. // Bound every wait, so a regression fails the test instead of hanging the
  21839. // suite.
  21840. auto wait_for = [](const std::atomic<bool> &flag) {
  21841. for (int i = 0; i < 500 && !flag; i++) {
  21842. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21843. }
  21844. };
  21845. Server svr;
  21846. svr.set_websocket_ping_interval(0);
  21847. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21848. std::thread reader([&]() {
  21849. std::string msg;
  21850. while (ws.read(msg)) {
  21851. std::lock_guard<std::mutex> guard(received_mutex);
  21852. received.push_back(msg);
  21853. }
  21854. });
  21855. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21856. // inside read_websocket_frame() when close() runs.
  21857. wait_for(peer_stalled);
  21858. ws.close();
  21859. reader.join();
  21860. handler_done = true;
  21861. });
  21862. auto port = svr.bind_to_any_port("127.0.0.1");
  21863. std::thread t([&]() { svr.listen_after_bind(); });
  21864. auto se = detail::scope_exit([&] {
  21865. svr.stop();
  21866. t.join();
  21867. });
  21868. svr.wait_until_ready();
  21869. auto send_bytes = [](socket_t s, const std::string &data) {
  21870. #ifdef _WIN32
  21871. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21872. #else
  21873. auto n = ::send(s, data.data(), data.size(), 0);
  21874. #endif
  21875. return n == static_cast<decltype(n)>(data.size());
  21876. };
  21877. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21878. // Every length used here fits the 7-bit length field.
  21879. auto masked_header = [](uint8_t first_byte, size_t len) {
  21880. std::string h;
  21881. h += static_cast<char>(first_byte);
  21882. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21883. h.append(4, '\0'); // mask key
  21884. return h;
  21885. };
  21886. for (int attempt = 0; attempt < attempts; attempt++) {
  21887. peer_stalled = false;
  21888. handler_done = false;
  21889. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21890. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21891. auto se_sock = detail::scope_exit([&] {
  21892. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21893. });
  21894. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21895. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21896. sockaddr_in addr{};
  21897. addr.sin_family = AF_INET;
  21898. addr.sin_port = htons(static_cast<uint16_t>(port));
  21899. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21900. ASSERT_EQ(
  21901. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21902. << "attempt " << attempt;
  21903. ASSERT_TRUE(send_bytes(sock,
  21904. "GET /ws HTTP/1.1\r\n"
  21905. "Host: 127.0.0.1\r\n"
  21906. "Upgrade: websocket\r\n"
  21907. "Connection: Upgrade\r\n"
  21908. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21909. "Sec-WebSocket-Version: 13\r\n"
  21910. "\r\n"))
  21911. << "attempt " << attempt;
  21912. std::string response;
  21913. while (response.find("\r\n\r\n") == std::string::npos) {
  21914. char buf[512];
  21915. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21916. if (n <= 0) { break; }
  21917. response.append(buf, static_cast<size_t>(n));
  21918. }
  21919. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21920. << "attempt " << attempt;
  21921. // Send the header of a Binary message but only the first prefix_len bytes
  21922. // of its payload, leaving the reader thread stalled inside the payload.
  21923. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21924. expected.substr(0, prefix_len)))
  21925. << "attempt " << attempt;
  21926. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21927. peer_stalled = true;
  21928. // Let close() send its Close frame and park in its own read before the
  21929. // rest of the payload arrives, so both threads are waiting for it.
  21930. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21931. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21932. close_frame += static_cast<char>(0x03); // status 1000
  21933. close_frame += static_cast<char>(0xE8);
  21934. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21935. << "attempt " << attempt;
  21936. // Closing the peer releases the reader thread even on the buggy path,
  21937. // where it waits for bytes another thread already consumed.
  21938. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21939. detail::close_socket(sock);
  21940. sock = INVALID_SOCKET;
  21941. wait_for(handler_done);
  21942. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21943. }
  21944. std::lock_guard<std::mutex> guard(received_mutex);
  21945. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21946. << "a message in flight when close() ran was dropped";
  21947. for (size_t i = 0; i < received.size(); i++) {
  21948. EXPECT_EQ(expected, received[i]) << "message " << i;
  21949. }
  21950. }
  21951. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21952. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21953. protected:
  21954. void SetUp() override {
  21955. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21956. SERVER_PRIVATE_KEY_FILE);
  21957. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21958. std::string msg;
  21959. ws::ReadResult ret;
  21960. while ((ret = ws.read(msg))) {
  21961. if (ret == ws::Binary) {
  21962. ws.send(msg.data(), msg.size());
  21963. } else {
  21964. ws.send(msg);
  21965. }
  21966. }
  21967. });
  21968. port_ = server_->bind_to_any_port(HOST);
  21969. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21970. server_->wait_until_ready();
  21971. }
  21972. void TearDown() override {
  21973. server_->stop();
  21974. if (server_thread_.joinable()) { server_thread_.join(); }
  21975. }
  21976. std::unique_ptr<SSLServer> server_;
  21977. std::thread server_thread_;
  21978. int port_ = 0;
  21979. };
  21980. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21981. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21982. "/ws-echo");
  21983. client.enable_server_certificate_verification(false);
  21984. ASSERT_TRUE(client.connect());
  21985. ASSERT_TRUE(client.is_open());
  21986. ASSERT_TRUE(client.send("Hello WSS"));
  21987. std::string msg;
  21988. EXPECT_EQ(ws::Text, client.read(msg));
  21989. EXPECT_EQ("Hello WSS", msg);
  21990. client.close();
  21991. }
  21992. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21993. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21994. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21995. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21996. // client (without calling close() first) is the only path that runs
  21997. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21998. // bug exactly.
  21999. //
  22000. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22001. // when linked against an instrumented libssl; run under Valgrind to catch it
  22002. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22003. // suite (the freed session otherwise stalls on the close handshake) — this test
  22004. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22005. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22006. {
  22007. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22008. "/ws-echo");
  22009. client.enable_server_certificate_verification(false);
  22010. client.set_read_timeout(2, 0);
  22011. client.set_write_timeout(2, 0);
  22012. ASSERT_TRUE(client.connect());
  22013. ASSERT_TRUE(client.is_open());
  22014. ASSERT_TRUE(client.send("still open"));
  22015. // Intentionally do NOT call client.close(): leaving scope runs
  22016. // shutdown_and_close() with the WebSocket still open, which must send the
  22017. // close frame while the TLS session is still alive.
  22018. }
  22019. }
  22020. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22021. // shutdown_and_close() at the start of connect(), reproducing the same
  22022. // use-after-free within the test body rather than at scope exit. The second
  22023. // connect must succeed and echo, proving the close handshake ran over a live
  22024. // session. See the note above about memory-tool requirements.
  22025. TEST_F(WebSocketSSLIntegrationTest,
  22026. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22027. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22028. "/ws-echo");
  22029. client.enable_server_certificate_verification(false);
  22030. client.set_read_timeout(2, 0);
  22031. client.set_write_timeout(2, 0);
  22032. ASSERT_TRUE(client.connect());
  22033. ASSERT_TRUE(client.is_open());
  22034. ASSERT_TRUE(client.send("still open"));
  22035. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22036. // the still-open connection, which must not touch a freed TLS session.
  22037. ASSERT_TRUE(client.connect());
  22038. ASSERT_TRUE(client.is_open());
  22039. ASSERT_TRUE(client.send("after reconnect"));
  22040. std::string msg;
  22041. EXPECT_EQ(ws::Text, client.read(msg));
  22042. EXPECT_EQ("after reconnect", msg);
  22043. client.close();
  22044. }
  22045. #endif
  22046. #ifdef CPPHTTPLIB_SSL_ENABLED
  22047. class WebSocketSSLCATest : public ::testing::Test {
  22048. protected:
  22049. void SetUp() override {
  22050. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22051. SERVER_PRIVATE_KEY_FILE);
  22052. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22053. std::string msg;
  22054. while (ws.read(msg)) {
  22055. ws.send(msg);
  22056. }
  22057. });
  22058. port_ = server_->bind_to_any_port("127.0.0.1");
  22059. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22060. server_->wait_until_ready();
  22061. }
  22062. void TearDown() override {
  22063. server_->stop();
  22064. if (server_thread_.joinable()) { server_thread_.join(); }
  22065. }
  22066. std::string url() const {
  22067. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22068. }
  22069. std::unique_ptr<SSLServer> server_;
  22070. std::thread server_thread_;
  22071. int port_ = 0;
  22072. };
  22073. // A custom CA loaded as PEM verifies the server with full certificate
  22074. // verification enabled
  22075. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22076. ws::WebSocketClient client(url());
  22077. std::string cert;
  22078. read_file(SERVER_CERT2_FILE, cert);
  22079. client.load_ca_cert_store(cert.c_str(), cert.size());
  22080. ASSERT_TRUE(client.connect());
  22081. ASSERT_TRUE(client.send("hello"));
  22082. std::string msg;
  22083. EXPECT_EQ(ws::Text, client.read(msg));
  22084. EXPECT_EQ("hello", msg);
  22085. client.close();
  22086. }
  22087. // A custom CA that does not cover the server must fail verification (the
  22088. // custom CA is exclusive; system certs are not loaded alongside it)
  22089. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22090. ws::WebSocketClient client(url());
  22091. std::string cert;
  22092. read_file(CLIENT_CA_CERT_FILE, cert);
  22093. client.load_ca_cert_store(cert.c_str(), cert.size());
  22094. auto res = client.connect();
  22095. ASSERT_FALSE(res);
  22096. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22097. EXPECT_EQ(-1, res.status());
  22098. EXPECT_NE(0u, res.ssl_backend_error());
  22099. }
  22100. // The same CA as a file path rather than PEM in memory
  22101. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22102. ws::WebSocketClient client(url());
  22103. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22104. ASSERT_TRUE(client.connect());
  22105. ASSERT_TRUE(client.send("hello"));
  22106. std::string msg;
  22107. EXPECT_EQ(ws::Text, client.read(msg));
  22108. EXPECT_EQ("hello", msg);
  22109. client.close();
  22110. }
  22111. // ...and a CA file that does not cover the server still fails, so it is the
  22112. // path above that decides the outcome
  22113. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22114. ws::WebSocketClient client(url());
  22115. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22116. ASSERT_FALSE(client.connect());
  22117. }
  22118. // Regression test: reconnecting with a native custom CA store used to reuse
  22119. // a store handle the previous TLS context had already freed (use-after-free
  22120. // under the OpenSSL backend). The context now lives as long as the client.
  22121. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22122. ws::WebSocketClient client(url());
  22123. std::string cert;
  22124. read_file(SERVER_CERT2_FILE, cert);
  22125. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22126. ASSERT_TRUE(client.connect());
  22127. client.close();
  22128. ASSERT_TRUE(client.connect());
  22129. ASSERT_TRUE(client.send("again"));
  22130. std::string msg;
  22131. EXPECT_EQ(ws::Text, client.read(msg));
  22132. EXPECT_EQ("again", msg);
  22133. client.close();
  22134. }
  22135. // Regression test: a certificate with a trusted chain but no identity match
  22136. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22137. // verification entirely for IP hosts, so this connection succeeded there.
  22138. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22139. // chain verification while the identity check must still fail.
  22140. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22142. ASSERT_TRUE(svr.is_valid());
  22143. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22144. std::string msg;
  22145. while (ws.read(msg)) {
  22146. ws.send(msg);
  22147. }
  22148. });
  22149. auto port = svr.bind_to_any_port("127.0.0.1");
  22150. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22151. auto se = detail::scope_exit([&] {
  22152. svr.stop();
  22153. t.join();
  22154. });
  22155. svr.wait_until_ready();
  22156. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22157. "/echo");
  22158. std::string cert;
  22159. read_file(SERVER_CERT_FILE, cert);
  22160. client.load_ca_cert_store(cert.c_str(), cert.size());
  22161. ASSERT_FALSE(client.connect());
  22162. }
  22163. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22164. // SNI, so nothing binds the host name to the TLS session. These bind the
  22165. // server to "localhost" instead, the only shape that exercises the SNI and
  22166. // hostname-verification path with certificate verification left enabled.
  22167. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22168. protected:
  22169. void Start(const char *cert_file) {
  22170. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22171. SERVER_PRIVATE_KEY_FILE);
  22172. ASSERT_TRUE(server_->is_valid());
  22173. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22174. std::string msg;
  22175. while (ws.read(msg)) {
  22176. ws.send(msg);
  22177. }
  22178. });
  22179. port_ = server_->bind_to_any_port("localhost");
  22180. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22181. server_->wait_until_ready();
  22182. }
  22183. void TearDown() override {
  22184. if (server_) { server_->stop(); }
  22185. if (server_thread_.joinable()) { server_thread_.join(); }
  22186. }
  22187. std::string url() const {
  22188. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22189. }
  22190. std::unique_ptr<SSLServer> server_;
  22191. std::thread server_thread_;
  22192. int port_ = 0;
  22193. };
  22194. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22195. // out and the connection is usable
  22196. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22197. Start(SERVER_CERT2_FILE);
  22198. ws::WebSocketClient client(url());
  22199. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22200. ASSERT_TRUE(client.connect());
  22201. ASSERT_TRUE(client.send("hello"));
  22202. std::string msg;
  22203. EXPECT_EQ(ws::Text, client.read(msg));
  22204. EXPECT_EQ("hello", msg);
  22205. client.close();
  22206. }
  22207. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22208. // while the identity check must still reject "localhost"
  22209. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22210. Start(SERVER_CERT_FILE);
  22211. ws::WebSocketClient client(url());
  22212. client.set_ca_cert_path(SERVER_CERT_FILE);
  22213. auto res = client.connect();
  22214. ASSERT_FALSE(res);
  22215. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22216. EXPECT_EQ(-1, res.status());
  22217. }
  22218. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22219. // disabled: the chain is still checked, only the identity check is skipped
  22220. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22221. Start(SERVER_CERT_FILE);
  22222. ws::WebSocketClient client(url());
  22223. client.set_ca_cert_path(SERVER_CERT_FILE);
  22224. client.enable_server_hostname_verification(false);
  22225. ASSERT_TRUE(client.connect());
  22226. ASSERT_TRUE(client.send("hello"));
  22227. std::string msg;
  22228. EXPECT_EQ(ws::Text, client.read(msg));
  22229. EXPECT_EQ("hello", msg);
  22230. client.close();
  22231. }
  22232. // A CA that did not sign the server certificate fails the chain, even though
  22233. // the name would match
  22234. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22235. Start(SERVER_CERT2_FILE);
  22236. ws::WebSocketClient client(url());
  22237. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22238. ASSERT_FALSE(client.connect());
  22239. }
  22240. // With verification disabled, neither the chain nor the name is checked
  22241. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22242. Start(SERVER_CERT_FILE);
  22243. ws::WebSocketClient client(url());
  22244. client.enable_server_certificate_verification(false);
  22245. ASSERT_TRUE(client.connect());
  22246. ASSERT_TRUE(client.send("hello"));
  22247. std::string msg;
  22248. EXPECT_EQ(ws::Text, client.read(msg));
  22249. EXPECT_EQ("hello", msg);
  22250. client.close();
  22251. }
  22252. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22253. protected:
  22254. void SetUp() override {
  22255. server_ = httplib::detail::make_unique<SSLServer>(
  22256. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22257. ASSERT_TRUE(server_->is_valid());
  22258. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22259. std::string msg;
  22260. while (ws.read(msg)) {
  22261. ws.send(msg);
  22262. }
  22263. });
  22264. port_ = server_->bind_to_any_port("localhost");
  22265. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22266. server_->wait_until_ready();
  22267. }
  22268. void TearDown() override {
  22269. server_->stop();
  22270. if (server_thread_.joinable()) { server_thread_.join(); }
  22271. }
  22272. std::string url() const {
  22273. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22274. }
  22275. void ConnectWithClientCert(const std::string &client_cert_file,
  22276. const std::string &client_private_key_file,
  22277. const char *private_key_password) {
  22278. std::string cert_pem, key_pem;
  22279. read_file(client_cert_file, cert_pem);
  22280. read_file(client_private_key_file, key_pem);
  22281. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22282. key_pem.c_str(), key_pem.size(),
  22283. private_key_password};
  22284. ws::WebSocketClient client(url(), pem);
  22285. ASSERT_TRUE(client.is_valid());
  22286. client.enable_server_certificate_verification(false);
  22287. ASSERT_TRUE(client.connect());
  22288. ASSERT_TRUE(client.send("hello"));
  22289. std::string msg;
  22290. EXPECT_EQ(ws::Text, client.read(msg));
  22291. EXPECT_EQ("hello", msg);
  22292. client.close();
  22293. }
  22294. std::unique_ptr<SSLServer> server_;
  22295. std::thread server_thread_;
  22296. int port_ = 0;
  22297. };
  22298. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22299. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22300. }
  22301. // Control for the tests above: the fixture's server really does require a
  22302. // client certificate, so it is the PEM the constructor installed that decides
  22303. // the outcome.
  22304. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22305. ws::WebSocketClient client(url());
  22306. ASSERT_TRUE(client.is_valid());
  22307. client.enable_server_certificate_verification(false);
  22308. EXPECT_FALSE(client.connect());
  22309. }
  22310. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22311. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22312. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22313. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22314. }
  22315. #endif
  22316. #if !defined(_WIN32)
  22317. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22318. auto secret_dir = std::string("./symlink_test_secret");
  22319. auto served_dir = std::string("./symlink_test_served");
  22320. auto secret_file = secret_dir + "/secret.txt";
  22321. auto symlink_path = served_dir + "/escape";
  22322. // Setup: create directories and files
  22323. mkdir(secret_dir.c_str(), 0755);
  22324. mkdir(served_dir.c_str(), 0755);
  22325. {
  22326. std::ofstream ofs(secret_file);
  22327. ofs << "SECRET_DATA";
  22328. }
  22329. // Create symlink using absolute path so it resolves correctly
  22330. #ifdef PATH_MAX
  22331. char abs_secret[PATH_MAX];
  22332. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22333. #else
  22334. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22335. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22336. ASSERT_NE(nullptr, abs_secret);
  22337. #endif
  22338. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22339. auto se = detail::scope_exit([&] {
  22340. unlink(symlink_path.c_str());
  22341. unlink(secret_file.c_str());
  22342. rmdir(served_dir.c_str());
  22343. rmdir(secret_dir.c_str());
  22344. });
  22345. Server svr;
  22346. svr.set_mount_point("/", served_dir);
  22347. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22348. auto se2 = detail::scope_exit([&] {
  22349. svr.stop();
  22350. listen_thread.join();
  22351. });
  22352. svr.wait_until_ready();
  22353. Client cli("localhost", PORT);
  22354. // Symlink pointing outside base dir should be blocked
  22355. auto res = cli.Get("/escape/secret.txt");
  22356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22357. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22358. }
  22359. #endif
  22360. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22361. // "GET /smuggled" request), reads the first response, and only then sends the
  22362. // embedded request as the body. Returns how many times /smuggled ran.
  22363. //
  22364. // The body is sent AFTER receiving the first response (as in the original
  22365. // PoC) so that the stream_line_reader cannot buffer it together with the
  22366. // headers of the first request.
  22367. static int count_smuggled_requests(const std::string &outer_head,
  22368. std::string &first_response) {
  22369. Server svr;
  22370. svr.set_mount_point("/", "./www");
  22371. std::atomic<int> smuggled_count(0);
  22372. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22373. smuggled_count++;
  22374. res.set_content("oops", "text/plain");
  22375. });
  22376. svr.Post("/post", [&](const Request &req, Response &res) {
  22377. res.set_content(req.body, "text/plain");
  22378. });
  22379. auto port = svr.bind_to_any_port("localhost");
  22380. thread t = thread([&] { svr.listen_after_bind(); });
  22381. auto se = detail::scope_exit([&] {
  22382. svr.stop();
  22383. t.join();
  22384. });
  22385. svr.wait_until_ready();
  22386. auto error = Error::Success;
  22387. auto sock = detail::create_client_socket(
  22388. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22389. /*connection_timeout_sec=*/2, 0,
  22390. /*read_timeout_sec=*/2, 0,
  22391. /*write_timeout_sec=*/2, 0, std::string(), error);
  22392. EXPECT_NE(INVALID_SOCKET, sock);
  22393. if (sock == INVALID_SOCKET) { return -1; }
  22394. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22395. // The "smuggled" request will be sent as the body of the outer request
  22396. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22397. "Host: localhost\r\n"
  22398. "Connection: close\r\n"
  22399. "\r\n";
  22400. auto head = outer_head;
  22401. auto len = std::to_string(smuggled.size());
  22402. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22403. pos = head.find("{len}", pos + len.size())) {
  22404. head.replace(pos, 5, len);
  22405. }
  22406. // Step 1: Send only the outer request headers (no body yet)
  22407. auto sent = send(sock, head.data(), head.size(), 0);
  22408. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22409. // Step 2: Read the first response
  22410. char buf[4096];
  22411. for (;;) {
  22412. auto n = recv(sock, buf, sizeof(buf), 0);
  22413. if (n <= 0) break;
  22414. first_response.append(buf, static_cast<size_t>(n));
  22415. // Stop once we have a complete response (headers + body)
  22416. auto hdr_end = first_response.find("\r\n\r\n");
  22417. if (hdr_end != std::string::npos) {
  22418. // Check for Content-Length to know when the body is complete
  22419. auto cl_pos = first_response.find("Content-Length:");
  22420. if (cl_pos != std::string::npos) {
  22421. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22422. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22423. auto cl = std::stoul(
  22424. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22425. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22426. } else {
  22427. break; // No Content-Length, assume headers-only response
  22428. }
  22429. }
  22430. }
  22431. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22432. // vulnerable server the keep-alive loop reads this as a second request. The
  22433. // server may already have closed the connection, so the result is ignored.
  22434. send(sock, smuggled.data(), smuggled.size(), 0);
  22435. // Half-close so that a server which drained the body sees EOF and closes,
  22436. // instead of the read below waiting for the read timeout.
  22437. #ifdef _WIN32
  22438. ::shutdown(sock, SD_SEND);
  22439. #else
  22440. ::shutdown(sock, SHUT_WR);
  22441. #endif
  22442. // Step 4: Read until the server closes the connection
  22443. for (;;) {
  22444. auto n = recv(sock, buf, sizeof(buf), 0);
  22445. if (n <= 0) break;
  22446. }
  22447. return smuggled_count.load();
  22448. }
  22449. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22450. // A GET request with Content-Length to a static file handler must have its
  22451. // body drained before the keep-alive connection is reused. Otherwise the
  22452. // unread body bytes are interpreted as the next HTTP request.
  22453. std::string first_response;
  22454. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22455. "Host: localhost\r\n"
  22456. "Content-Length: {len}\r\n"
  22457. "\r\n",
  22458. first_response));
  22459. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22460. }
  22461. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22462. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22463. // be answered with 400 and the connection closed. Treating it as "no body"
  22464. // leaves the body to be parsed as the next request.
  22465. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22466. const char *targets[] = {
  22467. "GET /file", // handler that never reads the body
  22468. "GET /not-found", // no handler matches (404)
  22469. "POST /post", // handler that reads the body
  22470. };
  22471. for (auto target : targets) {
  22472. for (auto value : values) {
  22473. std::string first_response;
  22474. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22475. " HTTP/1.1\r\n"
  22476. "Host: localhost\r\n"
  22477. "Content-Length: " +
  22478. value + "\r\n\r\n",
  22479. first_response))
  22480. << target << " with Content-Length: " << value;
  22481. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22482. << target << " with Content-Length: " << value;
  22483. }
  22484. }
  22485. }
  22486. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22487. // A 400 for an unparseable request line leaves the rest of the message
  22488. // unread, so the connection must be closed rather than reused.
  22489. std::string first_response;
  22490. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22491. "Host: localhost\r\n"
  22492. "Content-Length: {len}\r\n"
  22493. "\r\n",
  22494. first_response));
  22495. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22496. }
  22497. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22498. // Same as above for a header block that fails to parse.
  22499. std::string first_response;
  22500. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22501. "Host: localhost\r\n"
  22502. "Bad Header\r\n"
  22503. "Content-Length: {len}\r\n"
  22504. "\r\n",
  22505. first_response));
  22506. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22507. }
  22508. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22509. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22510. // server must not read another request on that connection, even when the
  22511. // request had no body to drain.
  22512. std::string first_response;
  22513. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22514. "Host: localhost\r\n"
  22515. "\r\n",
  22516. first_response));
  22517. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22518. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22519. }
  22520. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22521. // A content reader that stops early leaves the stream inside the body.
  22522. // Draining the whole Content-Length from there, or reading the body again,
  22523. // reads into the next request, and whatever follows is parsed as a request
  22524. // of its own.
  22525. Server svr;
  22526. std::atomic<int> smuggled_count(0);
  22527. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22528. svr.Post("/upload", [](const Request &req, Response &res,
  22529. const ContentReader &content_reader) {
  22530. // Stop at the last chunk, so the whole body has been read however it
  22531. // arrives.
  22532. auto length = req.get_header_value_u64("Content-Length");
  22533. size_t total = 0;
  22534. auto consumed = content_reader([&](const char *, size_t n) {
  22535. total += n;
  22536. return total < length;
  22537. });
  22538. EXPECT_FALSE(consumed);
  22539. if (req.has_param("retry")) {
  22540. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22541. }
  22542. // Replace the 400 the aborted read set, which would close the connection.
  22543. res.set_redirect("/done");
  22544. });
  22545. auto port = svr.bind_to_any_port(HOST);
  22546. thread t = thread([&] { svr.listen_after_bind(); });
  22547. auto se = detail::scope_exit([&] {
  22548. svr.stop();
  22549. t.join();
  22550. });
  22551. svr.wait_until_ready();
  22552. // A front end sees the second request as a POST whose body is the GET. The
  22553. // first body is as long as the POST's headers, so draining it again reads
  22554. // exactly those and leaves the GET to be parsed next.
  22555. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22556. "Host: localhost\r\n"
  22557. "\r\n";
  22558. std::string second_head = "POST /post HTTP/1.1\r\n"
  22559. "Host: localhost\r\n"
  22560. "Content-Length: " +
  22561. std::to_string(inner.size()) +
  22562. "\r\n"
  22563. "\r\n";
  22564. for (auto target : {"/upload", "/upload?retry"}) {
  22565. smuggled_count = 0;
  22566. std::string request = "POST " + std::string(target) +
  22567. " HTTP/1.1\r\n"
  22568. "Host: localhost\r\n"
  22569. "Content-Length: " +
  22570. std::to_string(second_head.size()) +
  22571. "\r\n"
  22572. "\r\n" +
  22573. std::string(second_head.size(), 'A') + second_head +
  22574. inner;
  22575. std::string response;
  22576. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22577. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22578. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22579. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22580. EXPECT_EQ(0, smuggled_count.load()) << target;
  22581. }
  22582. }
  22583. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22584. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22585. // must be rejected with 400 Bad Request.
  22586. Server svr;
  22587. svr.Post("/test", [&](const Request &, Response &res) {
  22588. res.set_content("ok", "text/plain");
  22589. });
  22590. thread t = thread([&] { svr.listen(HOST, PORT); });
  22591. auto se = detail::scope_exit([&] {
  22592. svr.stop();
  22593. t.join();
  22594. ASSERT_FALSE(svr.is_running());
  22595. });
  22596. svr.wait_until_ready();
  22597. // Exact "chunked"
  22598. {
  22599. auto req = "POST /test HTTP/1.1\r\n"
  22600. "Host: localhost\r\n"
  22601. "Content-Length: 5\r\n"
  22602. "Transfer-Encoding: chunked\r\n"
  22603. "Connection: close\r\n"
  22604. "\r\n"
  22605. "hello";
  22606. std::string response;
  22607. ASSERT_TRUE(send_request(1, req, &response));
  22608. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22609. response.substr(0, response.find("\r\n")));
  22610. }
  22611. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22612. {
  22613. auto req = "POST /test HTTP/1.1\r\n"
  22614. "Host: localhost\r\n"
  22615. "Content-Length: 5\r\n"
  22616. "Transfer-Encoding: gzip, chunked\r\n"
  22617. "Connection: close\r\n"
  22618. "\r\n"
  22619. "hello";
  22620. std::string response;
  22621. ASSERT_TRUE(send_request(1, req, &response));
  22622. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22623. response.substr(0, response.find("\r\n")));
  22624. }
  22625. }
  22626. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22627. Server svr;
  22628. svr.Post("/test", [&](const Request &, Response &res) {
  22629. res.set_content("ok", "text/plain");
  22630. });
  22631. thread t = thread([&] { svr.listen(HOST, PORT); });
  22632. auto se = detail::scope_exit([&] {
  22633. svr.stop();
  22634. t.join();
  22635. ASSERT_FALSE(svr.is_running());
  22636. });
  22637. svr.wait_until_ready();
  22638. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22639. // length cannot be determined, so the server must answer 400 and close
  22640. // rather than treat the request as bodyless and leave the body in the
  22641. // socket for the next request to pick up.
  22642. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22643. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22644. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22645. std::string response;
  22646. ASSERT_TRUE(send_request(1, req, &response));
  22647. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22648. response.substr(0, response.find("\r\n")))
  22649. << transfer_encoding;
  22650. }
  22651. // RFC 9110 5.3: the codings may also be split across several
  22652. // Transfer-Encoding lines, which combine in the order they were received.
  22653. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22654. // just like the single-line "chunked, gzip" above.
  22655. {
  22656. auto req = "POST /test HTTP/1.1\r\n"
  22657. "Host: localhost\r\n"
  22658. "Transfer-Encoding: chunked\r\n"
  22659. "Transfer-Encoding: gzip\r\n"
  22660. "\r\n"
  22661. "0\r\n\r\n";
  22662. std::string response;
  22663. ASSERT_TRUE(send_request(1, req, &response));
  22664. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22665. response.substr(0, response.find("\r\n")));
  22666. }
  22667. // A sequence ending in chunked stays valid.
  22668. auto req = "POST /test HTTP/1.1\r\n"
  22669. "Host: localhost\r\n"
  22670. "Transfer-Encoding: gzip, chunked\r\n"
  22671. "Connection: close\r\n"
  22672. "\r\n"
  22673. "0\r\n\r\n";
  22674. std::string response;
  22675. ASSERT_TRUE(send_request(1, req, &response));
  22676. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22677. // ...including when it is spread over several lines.
  22678. auto split_req = "POST /test HTTP/1.1\r\n"
  22679. "Host: localhost\r\n"
  22680. "Transfer-Encoding: gzip\r\n"
  22681. "Transfer-Encoding: chunked\r\n"
  22682. "Connection: close\r\n"
  22683. "\r\n"
  22684. "0\r\n\r\n";
  22685. std::string split_response;
  22686. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22687. EXPECT_EQ("HTTP/1.1 200 OK",
  22688. split_response.substr(0, split_response.find("\r\n")));
  22689. }
  22690. // Regression for issue #2450: a DELETE without Content-Length on a
  22691. // keep-alive connection must not let the post-response drain consume the
  22692. // next request's bytes.
  22693. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22694. Server svr;
  22695. std::atomic<int> delete_count(0);
  22696. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22697. delete_count++;
  22698. res.status = StatusCode::NoContent_204;
  22699. });
  22700. auto port = svr.bind_to_any_port(HOST);
  22701. thread t = thread([&] { svr.listen_after_bind(); });
  22702. auto se = detail::scope_exit([&] {
  22703. svr.stop();
  22704. t.join();
  22705. });
  22706. svr.wait_until_ready();
  22707. auto error = Error::Success;
  22708. auto sock = detail::create_client_socket(
  22709. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22710. /*connection_timeout_sec=*/2, 0,
  22711. /*read_timeout_sec=*/2, 0,
  22712. /*write_timeout_sec=*/2, 0, std::string(), error);
  22713. ASSERT_NE(INVALID_SOCKET, sock);
  22714. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22715. auto send_request_and_read_response = [&](const std::string &req,
  22716. std::string &out) -> bool {
  22717. auto sent = send(sock, req.data(), req.size(), 0);
  22718. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22719. char buf[4096];
  22720. for (;;) {
  22721. auto n = recv(sock, buf, sizeof(buf), 0);
  22722. if (n <= 0) { return !out.empty(); }
  22723. out.append(buf, static_cast<size_t>(n));
  22724. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22725. }
  22726. };
  22727. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22728. "Host: localhost\r\n"
  22729. "\r\n";
  22730. std::string resp1;
  22731. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22732. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22733. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22734. "Host: localhost\r\n"
  22735. "Connection: close\r\n"
  22736. "\r\n";
  22737. std::string resp2;
  22738. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22739. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22740. EXPECT_EQ(2, delete_count.load());
  22741. }
  22742. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22743. Server svr;
  22744. svr.Post("/ingest", [&](const Request &, Response &res,
  22745. const ContentReader &content_reader) {
  22746. auto consumed = content_reader([](const char *, size_t) { return false; });
  22747. EXPECT_FALSE(consumed);
  22748. res.status = StatusCode::Conflict_409;
  22749. res.set_header("Connection", "close");
  22750. });
  22751. auto port = svr.bind_to_any_port(HOST);
  22752. thread t = thread([&] { svr.listen_after_bind(); });
  22753. auto se = detail::scope_exit([&] {
  22754. svr.stop();
  22755. t.join();
  22756. });
  22757. svr.wait_until_ready();
  22758. auto error = Error::Success;
  22759. auto sock = detail::create_client_socket(
  22760. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22761. /*connection_timeout_sec=*/2, 0,
  22762. /*read_timeout_sec=*/1, 0,
  22763. /*write_timeout_sec=*/2, 0, std::string(), error);
  22764. ASSERT_NE(INVALID_SOCKET, sock);
  22765. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22766. std::string request = "POST /ingest HTTP/1.1\r\n"
  22767. "Host: localhost\r\n"
  22768. "Transfer-Encoding: chunked\r\n"
  22769. "\r\n"
  22770. "4\r\n"
  22771. "data\r\n";
  22772. auto sent = send(sock, request.data(), request.size(), 0);
  22773. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22774. std::string response;
  22775. ssize_t received = 0;
  22776. do {
  22777. char buf[4096];
  22778. received = recv(sock, buf, sizeof(buf), 0);
  22779. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22780. } while (received > 0);
  22781. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22782. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22783. EXPECT_EQ(0, received);
  22784. }
  22785. namespace no_proxy_test {
  22786. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22787. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22788. // calling listen().
  22789. class ScopedServer {
  22790. public:
  22791. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22792. ~ScopedServer() {
  22793. svr_.stop();
  22794. if (th_.joinable()) { th_.join(); }
  22795. }
  22796. Server &svr() { return svr_; }
  22797. int port() const { return port_; }
  22798. void listen() {
  22799. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22800. svr_.wait_until_ready();
  22801. }
  22802. private:
  22803. Server svr_;
  22804. std::thread th_;
  22805. int port_ = 0;
  22806. };
  22807. class ProxyAndTargetServers {
  22808. public:
  22809. ProxyAndTargetServers() {
  22810. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22811. proxy_hits_++;
  22812. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22813. res.set_content("via-proxy", "text/plain");
  22814. });
  22815. target_.Get(".*", [this](const Request &req, Response &res) {
  22816. target_hits_++;
  22817. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22818. res.set_content("direct", "text/plain");
  22819. });
  22820. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22821. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22822. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22823. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22824. proxy_mock_.wait_until_ready();
  22825. target_.wait_until_ready();
  22826. }
  22827. ~ProxyAndTargetServers() {
  22828. proxy_mock_.stop();
  22829. target_.stop();
  22830. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22831. if (target_thread_.joinable()) { target_thread_.join(); }
  22832. }
  22833. Server &proxy_mock() { return proxy_mock_; }
  22834. Server &target() { return target_; }
  22835. int proxy_port() const { return proxy_port_; }
  22836. int target_port() const { return target_port_; }
  22837. int proxy_hits() const { return proxy_hits_.load(); }
  22838. int target_hits() const { return target_hits_.load(); }
  22839. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22840. void reset_counters() {
  22841. proxy_hits_ = 0;
  22842. target_hits_ = 0;
  22843. last_had_proxy_authz_ = false;
  22844. }
  22845. private:
  22846. Server proxy_mock_;
  22847. Server target_;
  22848. std::thread proxy_thread_;
  22849. std::thread target_thread_;
  22850. int proxy_port_ = 0;
  22851. int target_port_ = 0;
  22852. std::atomic<int> proxy_hits_{0};
  22853. std::atomic<int> target_hits_{0};
  22854. std::atomic<bool> last_had_proxy_authz_{false};
  22855. };
  22856. inline std::unique_ptr<Client> make_client(const std::string &host,
  22857. ProxyAndTargetServers &s) {
  22858. auto cli = detail::make_unique<Client>(host, s.target_port());
  22859. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22860. cli->set_proxy("127.0.0.1", s.proxy_port());
  22861. return cli;
  22862. }
  22863. } // namespace no_proxy_test
  22864. using no_proxy_test::make_client;
  22865. using no_proxy_test::ProxyAndTargetServers;
  22866. TEST(NoProxyTest, ExactHostnameBypasses) {
  22867. ProxyAndTargetServers s;
  22868. auto cli = make_client("example.com", s);
  22869. cli->set_no_proxy({"example.com"});
  22870. auto res = cli->Get("/");
  22871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22872. EXPECT_EQ(0, s.proxy_hits());
  22873. EXPECT_EQ(1, s.target_hits());
  22874. }
  22875. TEST(NoProxyTest, SubdomainBypasses) {
  22876. ProxyAndTargetServers s;
  22877. auto cli = make_client("foo.example.com", s);
  22878. cli->set_no_proxy({"example.com"});
  22879. auto res = cli->Get("/");
  22880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22881. EXPECT_EQ(0, s.proxy_hits());
  22882. EXPECT_EQ(1, s.target_hits());
  22883. }
  22884. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22885. // Regression guard: "evilexample.com" must not be considered a subdomain
  22886. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22887. // check would let traffic bypass the proxy and leak credentials direct
  22888. // to the attacker host.
  22889. ProxyAndTargetServers s;
  22890. auto cli = make_client("evilexample.com", s);
  22891. cli->set_no_proxy({"example.com"});
  22892. auto res = cli->Get("/");
  22893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22894. EXPECT_GE(s.proxy_hits(), 1);
  22895. EXPECT_EQ(0, s.target_hits());
  22896. }
  22897. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22898. ProxyAndTargetServers s;
  22899. auto cli = make_client("example.com.evil.com", s);
  22900. cli->set_no_proxy({"example.com"});
  22901. auto res = cli->Get("/");
  22902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22903. EXPECT_GE(s.proxy_hits(), 1);
  22904. EXPECT_EQ(0, s.target_hits());
  22905. }
  22906. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22907. ProxyAndTargetServers s;
  22908. auto cli = make_client("example.com", s);
  22909. cli->set_no_proxy({".example.com"});
  22910. auto res = cli->Get("/");
  22911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22912. EXPECT_EQ(0, s.proxy_hits());
  22913. EXPECT_EQ(1, s.target_hits());
  22914. }
  22915. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22916. ProxyAndTargetServers s;
  22917. auto cli = make_client("Example.COM", s);
  22918. cli->set_no_proxy({"EXAMPLE.com"});
  22919. auto res = cli->Get("/");
  22920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22921. EXPECT_EQ(0, s.proxy_hits());
  22922. EXPECT_EQ(1, s.target_hits());
  22923. }
  22924. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22925. ProxyAndTargetServers s;
  22926. auto cli = make_client("example.com.", s);
  22927. cli->set_no_proxy({"example.com"});
  22928. auto res = cli->Get("/");
  22929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22930. EXPECT_EQ(0, s.proxy_hits());
  22931. EXPECT_EQ(1, s.target_hits());
  22932. }
  22933. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22934. // Trailing dots must be normalized on BOTH sides — host and entry.
  22935. // An implementation that only strips the host-side trailing dot would
  22936. // fail to match host "example.com" against entry "example.com." because
  22937. // a literal substring search would compare 11 chars against 12.
  22938. ProxyAndTargetServers s;
  22939. auto cli = make_client("example.com", s);
  22940. cli->set_no_proxy({"example.com."});
  22941. auto res = cli->Get("/");
  22942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22943. EXPECT_EQ(0, s.proxy_hits());
  22944. EXPECT_EQ(1, s.target_hits());
  22945. }
  22946. TEST(NoProxyTest, WildcardBypassesEverything) {
  22947. ProxyAndTargetServers s;
  22948. auto cli = make_client("anything.invalid.test", s);
  22949. cli->set_no_proxy({"*"});
  22950. auto res = cli->Get("/");
  22951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22952. EXPECT_EQ(0, s.proxy_hits());
  22953. EXPECT_EQ(1, s.target_hits());
  22954. }
  22955. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22956. ProxyAndTargetServers s;
  22957. Client cli("127.0.0.1", s.target_port());
  22958. cli.set_proxy("127.0.0.1", s.proxy_port());
  22959. cli.set_no_proxy({"127.0.0.1"});
  22960. auto res = cli.Get("/");
  22961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22962. EXPECT_EQ(0, s.proxy_hits());
  22963. EXPECT_EQ(1, s.target_hits());
  22964. }
  22965. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22966. ProxyAndTargetServers s;
  22967. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22968. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22969. cli.set_proxy("127.0.0.1", s.proxy_port());
  22970. cli.set_no_proxy({"::1"});
  22971. auto res = cli.Get("/");
  22972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22973. EXPECT_EQ(0, s.proxy_hits());
  22974. EXPECT_EQ(1, s.target_hits());
  22975. }
  22976. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22977. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22978. // must still be recognized as IPv6 for CIDR matching. Implementations
  22979. // that detect IPv6 only when the host begins with '[' would parse the
  22980. // host as a hostname and miss the match.
  22981. ProxyAndTargetServers s;
  22982. Client cli("fe80::1", s.target_port());
  22983. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22984. cli.set_proxy("127.0.0.1", s.proxy_port());
  22985. cli.set_no_proxy({"fe80::/10"});
  22986. auto res = cli.Get("/");
  22987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22988. EXPECT_EQ(0, s.proxy_hits());
  22989. EXPECT_EQ(1, s.target_hits());
  22990. }
  22991. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22992. ProxyAndTargetServers s;
  22993. Client cli("::1", s.target_port());
  22994. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22995. cli.set_proxy("127.0.0.1", s.proxy_port());
  22996. cli.set_no_proxy({"[::1]"});
  22997. auto res = cli.Get("/");
  22998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22999. EXPECT_EQ(0, s.proxy_hits());
  23000. EXPECT_EQ(1, s.target_hits());
  23001. }
  23002. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23003. ProxyAndTargetServers s;
  23004. Client cli("fe80::1", s.target_port());
  23005. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23006. cli.set_proxy("127.0.0.1", s.proxy_port());
  23007. cli.set_no_proxy({"[fe80::]/10"});
  23008. auto res = cli.Get("/");
  23009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23010. EXPECT_EQ(0, s.proxy_hits());
  23011. EXPECT_EQ(1, s.target_hits());
  23012. }
  23013. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23014. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23015. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23016. // tricks via address-family conversion.
  23017. ProxyAndTargetServers s;
  23018. Client cli("::ffff:127.0.0.1", s.target_port());
  23019. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23020. cli.set_proxy("127.0.0.1", s.proxy_port());
  23021. cli.set_no_proxy({"127.0.0.1"});
  23022. auto res = cli.Get("/");
  23023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23024. EXPECT_GE(s.proxy_hits(), 1);
  23025. EXPECT_EQ(0, s.target_hits());
  23026. }
  23027. TEST(NoProxyTest, IPv4CidrMatch) {
  23028. ProxyAndTargetServers s;
  23029. Client cli("127.0.0.1", s.target_port());
  23030. cli.set_proxy("127.0.0.1", s.proxy_port());
  23031. cli.set_no_proxy({"127.0.0.0/8"});
  23032. auto res = cli.Get("/");
  23033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23034. EXPECT_EQ(0, s.proxy_hits());
  23035. EXPECT_EQ(1, s.target_hits());
  23036. }
  23037. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23038. ProxyAndTargetServers s;
  23039. Client cli("127.0.0.1", s.target_port());
  23040. cli.set_proxy("127.0.0.1", s.proxy_port());
  23041. cli.set_no_proxy({"10.0.0.0/8"});
  23042. auto res = cli.Get("/");
  23043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23044. EXPECT_GE(s.proxy_hits(), 1);
  23045. EXPECT_EQ(0, s.target_hits());
  23046. }
  23047. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23048. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23049. // IPv4 target matches.
  23050. ProxyAndTargetServers s;
  23051. Client cli("127.0.0.1", s.target_port());
  23052. cli.set_proxy("127.0.0.1", s.proxy_port());
  23053. cli.set_no_proxy({"0.0.0.0/0"});
  23054. auto res = cli.Get("/");
  23055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23056. EXPECT_EQ(0, s.proxy_hits());
  23057. EXPECT_EQ(1, s.target_hits());
  23058. }
  23059. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23060. ProxyAndTargetServers s;
  23061. Client cli("127.0.0.1", s.target_port());
  23062. cli.set_proxy("127.0.0.1", s.proxy_port());
  23063. cli.set_no_proxy({"127.0.0.1"});
  23064. auto res = cli.Get("/");
  23065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23066. EXPECT_EQ(0, s.proxy_hits());
  23067. EXPECT_EQ(1, s.target_hits());
  23068. }
  23069. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23070. ProxyAndTargetServers s;
  23071. Client cli("127.0.0.1", s.target_port());
  23072. cli.set_proxy("127.0.0.1", s.proxy_port());
  23073. cli.set_no_proxy({"127.0.0.0/33"});
  23074. auto res = cli.Get("/");
  23075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23076. EXPECT_GE(s.proxy_hits(), 1);
  23077. EXPECT_EQ(0, s.target_hits());
  23078. }
  23079. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23080. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23081. ProxyAndTargetServers s;
  23082. Client cli("127.0.0.1", s.target_port());
  23083. cli.set_proxy("127.0.0.1", s.proxy_port());
  23084. cli.set_no_proxy({"127.0.0.1/"});
  23085. auto res = cli.Get("/");
  23086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23087. EXPECT_GE(s.proxy_hits(), 1);
  23088. EXPECT_EQ(0, s.target_hits());
  23089. }
  23090. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23091. ProxyAndTargetServers s;
  23092. auto cli = make_client("internal.corp", s);
  23093. cli->set_proxy_basic_auth("u", "p");
  23094. cli->set_no_proxy({"internal.corp"});
  23095. auto res = cli->Get("/");
  23096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23097. EXPECT_EQ(1, s.target_hits());
  23098. EXPECT_EQ(0, s.proxy_hits());
  23099. EXPECT_FALSE(s.last_had_proxy_authz())
  23100. << "Proxy-Authorization must not be sent direct to the target";
  23101. }
  23102. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23103. ProxyAndTargetServers s;
  23104. auto cli = make_client("public.example", s);
  23105. cli->set_proxy_basic_auth("u", "p");
  23106. cli->set_no_proxy({"internal.corp"}); // does not match
  23107. auto res = cli->Get("/");
  23108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23109. EXPECT_GE(s.proxy_hits(), 1);
  23110. EXPECT_TRUE(s.last_had_proxy_authz());
  23111. }
  23112. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23113. std::atomic<int> hits{0};
  23114. std::atomic<int> hits_with_authz{0};
  23115. no_proxy_test::ScopedServer proxy_mock;
  23116. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23117. hits++;
  23118. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23119. if (req.target.find("/redir") != std::string::npos) {
  23120. res.set_redirect("http://other.example/landed");
  23121. } else {
  23122. res.set_content("via-proxy", "text/plain");
  23123. }
  23124. });
  23125. proxy_mock.listen();
  23126. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23127. hits = 0;
  23128. hits_with_authz = 0;
  23129. Client cli("public.example", 80);
  23130. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23131. cli.set_proxy_basic_auth(c.first, c.second);
  23132. cli.set_follow_location(true);
  23133. // The redirect to another host goes through the proxy as well
  23134. auto res = cli.Get("/redir");
  23135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23136. EXPECT_EQ(2, hits.load());
  23137. EXPECT_EQ(2, hits_with_authz.load());
  23138. }
  23139. }
  23140. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23141. ProxyAndTargetServers s;
  23142. auto cli = make_client("anything.test", s);
  23143. auto res = cli->Get("/");
  23144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23145. EXPECT_GE(s.proxy_hits(), 1);
  23146. EXPECT_EQ(0, s.target_hits());
  23147. }
  23148. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23149. ProxyAndTargetServers s;
  23150. auto cli = make_client("example.com", s);
  23151. cli->set_no_proxy({"example.com:8080"});
  23152. auto res = cli->Get("/");
  23153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23154. EXPECT_GE(s.proxy_hits(), 1);
  23155. EXPECT_EQ(0, s.target_hits());
  23156. }
  23157. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23158. ProxyAndTargetServers s;
  23159. auto cli = make_client("anything.test", s);
  23160. cli->set_no_proxy({"", " ", "\t"});
  23161. auto res = cli->Get("/");
  23162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23163. EXPECT_GE(s.proxy_hits(), 1);
  23164. EXPECT_EQ(0, s.target_hits());
  23165. }
  23166. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23167. // An entry with leading/trailing whitespace must still match — env-style
  23168. // values are commonly pasted with stray spaces and an implementation
  23169. // that feeds the raw token directly to inet_pton would fail to match
  23170. // valid CIDRs because of the spaces.
  23171. ProxyAndTargetServers s;
  23172. Client cli("127.0.0.1", s.target_port());
  23173. cli.set_proxy("127.0.0.1", s.proxy_port());
  23174. cli.set_no_proxy({" 127.0.0.0/8 "});
  23175. auto res = cli.Get("/");
  23176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23177. EXPECT_EQ(0, s.proxy_hits());
  23178. EXPECT_EQ(1, s.target_hits());
  23179. }
  23180. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23181. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23182. // go direct and must NOT carry Proxy-Authorization.
  23183. std::atomic<int> proxy_hits{0};
  23184. std::atomic<int> target_hits{0};
  23185. std::atomic<bool> target_saw_authz{false};
  23186. no_proxy_test::ScopedServer proxy_mock, target;
  23187. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23188. proxy_hits++;
  23189. res.status = 302;
  23190. res.set_header("Location", "http://127.0.0.1:" +
  23191. std::to_string(target.port()) + "/landed");
  23192. });
  23193. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23194. target_hits++;
  23195. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23196. res.set_content("direct", "text/plain");
  23197. });
  23198. proxy_mock.listen();
  23199. target.listen();
  23200. Client cli("public.example", target.port());
  23201. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23202. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23203. cli.set_proxy_basic_auth("u", "p");
  23204. cli.set_no_proxy({"127.0.0.1"});
  23205. cli.set_follow_location(true);
  23206. auto res = cli.Get("/redir");
  23207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23208. EXPECT_GE(proxy_hits.load(), 1);
  23209. EXPECT_GE(target_hits.load(), 1);
  23210. EXPECT_FALSE(target_saw_authz.load());
  23211. }
  23212. #ifdef CPPHTTPLIB_SSL_ENABLED
  23213. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23214. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23215. // proxy creds would be sent to the (possibly hostile) origin.
  23216. std::atomic<int> target_hits{0};
  23217. std::atomic<bool> target_saw_proxy_authz{false};
  23218. no_proxy_test::ScopedServer target;
  23219. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23220. target_hits++;
  23221. if (req.has_header("Proxy-Authorization")) {
  23222. target_saw_proxy_authz = true;
  23223. }
  23224. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23225. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23226. "nonce=\"abc\", algorithm=MD5");
  23227. });
  23228. target.listen();
  23229. // The proxy address is set to the target's port: the bypass MUST kick in;
  23230. // if it doesn't, the test still routes "via proxy" to the same server and
  23231. // the Proxy-Authorization assertion below catches the leak.
  23232. Client cli("evil.example", target.port());
  23233. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23234. cli.set_proxy("127.0.0.1", target.port());
  23235. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23236. cli.set_no_proxy({"evil.example"});
  23237. auto res = cli.Get("/x");
  23238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23239. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23240. EXPECT_EQ(1, target_hits.load());
  23241. EXPECT_FALSE(target_saw_proxy_authz.load());
  23242. }
  23243. #endif
  23244. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23245. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23246. std::atomic<int> proxy_hits{0};
  23247. std::atomic<int> bypass_hits{0};
  23248. std::atomic<bool> proxy_saw_c_url{false};
  23249. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23250. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23251. proxy_hits++;
  23252. if (req.path.find("/start") != std::string::npos) {
  23253. res.status = 302;
  23254. res.set_header("Location", "http://127.0.0.1:" +
  23255. std::to_string(bypass_server.port()) +
  23256. "/middle");
  23257. return;
  23258. }
  23259. if (req.path.find("/end") != std::string::npos) {
  23260. proxy_saw_c_url = true;
  23261. res.set_content("c-via-proxy", "text/plain");
  23262. return;
  23263. }
  23264. res.set_content("unexpected", "text/plain");
  23265. });
  23266. // public.example's "advertised" port is arbitrary (the request never lands
  23267. // there — it goes through the proxy), but use a dynamic value to stay
  23268. // friendly with sharded parallel runs.
  23269. int public_port = bypass_server.port();
  23270. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23271. bypass_hits++;
  23272. res.status = 302;
  23273. res.set_header("Location", "http://public.example:" +
  23274. std::to_string(public_port) + "/end");
  23275. });
  23276. proxy_mock.listen();
  23277. bypass_server.listen();
  23278. Client cli("public.example", public_port);
  23279. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23280. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23281. cli.set_no_proxy({"127.0.0.1"});
  23282. cli.set_follow_location(true);
  23283. auto res = cli.Get("/start");
  23284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23285. EXPECT_EQ(StatusCode::OK_200, res->status);
  23286. EXPECT_EQ("c-via-proxy", res->body);
  23287. EXPECT_GE(proxy_hits.load(), 2);
  23288. EXPECT_GE(bypass_hits.load(), 1);
  23289. EXPECT_TRUE(proxy_saw_c_url.load());
  23290. }
  23291. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23292. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23293. // request reconnects to the correct endpoint.
  23294. std::atomic<int> proxy_hits{0};
  23295. std::atomic<int> target_hits{0};
  23296. no_proxy_test::ScopedServer proxy_mock, target;
  23297. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23298. proxy_hits++;
  23299. res.set_content("via-proxy", "text/plain");
  23300. });
  23301. target.svr().Get(".*", [&](const Request &, Response &res) {
  23302. target_hits++;
  23303. res.set_content("direct", "text/plain");
  23304. });
  23305. proxy_mock.listen();
  23306. target.listen();
  23307. Client cli("public.example", target.port());
  23308. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23309. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23310. cli.set_keep_alive(true);
  23311. auto res1 = cli.Get("/a");
  23312. ASSERT_TRUE(res1);
  23313. EXPECT_EQ("via-proxy", res1->body);
  23314. EXPECT_EQ(1, proxy_hits.load());
  23315. EXPECT_EQ(0, target_hits.load());
  23316. cli.set_no_proxy({"public.example"});
  23317. auto res2 = cli.Get("/b");
  23318. ASSERT_TRUE(res2);
  23319. EXPECT_EQ("direct", res2->body);
  23320. EXPECT_EQ(1, proxy_hits.load());
  23321. EXPECT_EQ(1, target_hits.load());
  23322. }
  23323. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23324. namespace proxy_tunnel_test {
  23325. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23326. class ScopedSSLServer {
  23327. public:
  23328. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23329. port_ = svr_.bind_to_any_port("127.0.0.1");
  23330. }
  23331. ~ScopedSSLServer() {
  23332. svr_.stop();
  23333. if (th_.joinable()) { th_.join(); }
  23334. }
  23335. SSLServer &svr() { return svr_; }
  23336. int port() const { return port_; }
  23337. void listen() {
  23338. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23339. svr_.wait_until_ready();
  23340. }
  23341. private:
  23342. SSLServer svr_;
  23343. std::thread th_;
  23344. int port_ = 0;
  23345. };
  23346. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23347. class ScopedConnectProxy {
  23348. public:
  23349. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23350. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23351. if (listen_fd_ < 0) { return; }
  23352. int yes = 1;
  23353. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23354. sockaddr_in a{};
  23355. a.sin_family = AF_INET;
  23356. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23357. a.sin_port = 0;
  23358. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23359. return;
  23360. }
  23361. socklen_t alen = sizeof(a);
  23362. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23363. 0) {
  23364. return;
  23365. }
  23366. port_ = ntohs(a.sin_port);
  23367. if (::listen(listen_fd_, 1) != 0) { return; }
  23368. th_ = std::thread([this] { run(); });
  23369. }
  23370. ~ScopedConnectProxy() {
  23371. stop_ = true;
  23372. if (listen_fd_ >= 0) {
  23373. ::shutdown(listen_fd_, SHUT_RDWR);
  23374. ::close(listen_fd_);
  23375. }
  23376. if (th_.joinable()) { th_.join(); }
  23377. }
  23378. int port() const { return port_; }
  23379. int connect_hits() const { return connect_hits_.load(); }
  23380. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23381. std::string connect_request() const {
  23382. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23383. return connect_request_;
  23384. }
  23385. private:
  23386. void run() {
  23387. while (!stop_.load()) {
  23388. fd_set rfds;
  23389. FD_ZERO(&rfds);
  23390. FD_SET(listen_fd_, &rfds);
  23391. timeval tv{0, 100 * 1000};
  23392. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23393. if (sel <= 0) { continue; }
  23394. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23395. if (client_fd < 0) { continue; }
  23396. std::string req;
  23397. char buf[2048];
  23398. while (req.find("\r\n\r\n") == std::string::npos) {
  23399. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23400. if (n <= 0) { break; }
  23401. req.append(buf, static_cast<size_t>(n));
  23402. }
  23403. if (req.compare(0, 7, "CONNECT") != 0) {
  23404. ::close(client_fd);
  23405. continue;
  23406. }
  23407. connect_hits_++;
  23408. {
  23409. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23410. connect_request_ = req;
  23411. }
  23412. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23413. ::send(client_fd, ok, std::strlen(ok), 0);
  23414. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23415. sockaddr_in o{};
  23416. o.sin_family = AF_INET;
  23417. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23418. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23419. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23420. 0) {
  23421. ::close(client_fd);
  23422. ::close(origin_fd);
  23423. continue;
  23424. }
  23425. auto forward = [](int from, int to) {
  23426. char b[8192];
  23427. for (;;) {
  23428. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23429. if (n <= 0) { break; }
  23430. ssize_t off = 0;
  23431. while (off < n) {
  23432. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23433. if (s <= 0) {
  23434. off = n;
  23435. break;
  23436. }
  23437. off += s;
  23438. }
  23439. }
  23440. ::shutdown(to, SHUT_WR);
  23441. };
  23442. std::thread t1([&] { forward(client_fd, origin_fd); });
  23443. std::thread t2([&] { forward(origin_fd, client_fd); });
  23444. t1.join();
  23445. t2.join();
  23446. ::close(client_fd);
  23447. ::close(origin_fd);
  23448. }
  23449. }
  23450. int forward_port_ = -1;
  23451. int listen_fd_ = -1;
  23452. int port_ = 0;
  23453. std::thread th_;
  23454. std::atomic<bool> stop_{false};
  23455. std::atomic<int> connect_hits_{0};
  23456. mutable std::mutex connect_request_mutex_;
  23457. std::string connect_request_;
  23458. };
  23459. // Sends one request through the CONNECT proxy to the TLS origin with a
  23460. // credential configured for each hop, and checks that each credential reaches
  23461. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23462. // origin's (every header in origin_headers) on the tunnelled request.
  23463. void CredentialsStayWithTheirHop(
  23464. const std::function<void(SSLClient &)> &set_credentials,
  23465. const std::string &scheme,
  23466. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23467. std::atomic<int> origin_hits{0};
  23468. std::atomic<bool> origin_saw_proxy_authz{false};
  23469. std::atomic<bool> origin_saw_headers{false};
  23470. ScopedSSLServer origin;
  23471. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23472. origin_hits++;
  23473. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23474. origin_saw_headers =
  23475. std::all_of(origin_headers.begin(), origin_headers.end(),
  23476. [&](const std::string &h) { return req.has_header(h); });
  23477. res.set_content("ok", "text/plain");
  23478. });
  23479. origin.listen();
  23480. ScopedConnectProxy proxy(origin.port());
  23481. ASSERT_NE(0, proxy.port());
  23482. // Pinned to 127.0.0.1 for the same reason as the test below.
  23483. SSLClient cli("127.0.0.1", origin.port());
  23484. cli.enable_server_certificate_verification(false);
  23485. cli.set_proxy("127.0.0.1", proxy.port());
  23486. set_credentials(cli);
  23487. auto res = cli.Get("/x");
  23488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23489. EXPECT_EQ(StatusCode::OK_200, res->status);
  23490. EXPECT_EQ(1, origin_hits.load());
  23491. EXPECT_EQ(1, proxy.connect_hits());
  23492. EXPECT_TRUE(origin_saw_headers.load());
  23493. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23494. << "Proxy-Authorization must not be sent inside the tunnel";
  23495. auto connect_req = proxy.connect_request();
  23496. EXPECT_NE(std::string::npos,
  23497. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23498. for (const auto &h : origin_headers) {
  23499. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23500. << h << " must not be sent to the proxy on CONNECT";
  23501. }
  23502. }
  23503. } // namespace proxy_tunnel_test
  23504. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23505. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23506. [](SSLClient &cli) {
  23507. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23508. cli.set_basic_auth("origin-user", "origin-pass");
  23509. },
  23510. "Basic");
  23511. }
  23512. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23513. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23514. [](SSLClient &cli) {
  23515. cli.set_proxy_bearer_token_auth("proxy-token");
  23516. cli.set_bearer_token_auth("origin-token");
  23517. },
  23518. "Bearer");
  23519. }
  23520. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23521. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23522. [](SSLClient &cli) {
  23523. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23524. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23525. {"Cookie", "sid=origin-session"},
  23526. {"X-Api-Key", "origin-key"}});
  23527. },
  23528. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23529. }
  23530. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23531. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23532. // retry; otherwise proxy creds would be sent to the origin.
  23533. std::atomic<int> origin_hits{0};
  23534. std::atomic<bool> origin_saw_proxy_authz{false};
  23535. proxy_tunnel_test::ScopedSSLServer origin;
  23536. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23537. origin_hits++;
  23538. if (req.has_header("Proxy-Authorization")) {
  23539. origin_saw_proxy_authz = true;
  23540. }
  23541. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23542. res.set_header("Proxy-Authenticate",
  23543. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23544. "algorithm=MD5");
  23545. });
  23546. origin.listen();
  23547. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23548. ASSERT_NE(0, proxy.port());
  23549. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23550. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23551. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23552. // and answer with its own status, making this test flaky.
  23553. SSLClient cli("127.0.0.1", origin.port());
  23554. cli.enable_server_certificate_verification(false);
  23555. cli.set_proxy("127.0.0.1", proxy.port());
  23556. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23557. auto res = cli.Get("/x");
  23558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23559. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23560. EXPECT_EQ(1, origin_hits.load());
  23561. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23562. EXPECT_EQ(1, proxy.connect_hits());
  23563. }
  23564. #endif