test.cc 967 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794
  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 definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. }
  153. #if defined(__linux__) || \
  154. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  155. TEST_F(UnixSocketTest, PeerPid) {
  156. httplib::Server svr;
  157. std::string remote_port_val;
  158. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  159. res.set_content(content_, "text/plain");
  160. remote_port_val = std::to_string(req.remote_port);
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(pathname_);
  173. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  174. }
  175. #endif
  176. #ifdef __linux__
  177. TEST_F(UnixSocketTest, abstract) {
  178. constexpr char svr_path[]{"\x00httplib-server.sock"};
  179. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  180. httplib::Server svr;
  181. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  182. res.set_content(content_, "text/plain");
  183. });
  184. std::thread t{[&] {
  185. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  186. }};
  187. auto se = detail::scope_exit([&] {
  188. svr.stop();
  189. t.join();
  190. ASSERT_FALSE(svr.is_running());
  191. });
  192. svr.wait_until_ready();
  193. ASSERT_TRUE(svr.is_running());
  194. client_GET(abstract_addr);
  195. }
  196. #endif
  197. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  198. httplib::Server svr;
  199. std::string received_host_header;
  200. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  201. // Capture the Host header sent by the client
  202. auto host_iter = req.headers.find("Host");
  203. if (host_iter != req.headers.end()) {
  204. received_host_header = host_iter->second;
  205. }
  206. res.set_content(content_, "text/plain");
  207. });
  208. std::thread t{[&] {
  209. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  210. }};
  211. auto se = detail::scope_exit([&] {
  212. svr.stop();
  213. t.join();
  214. ASSERT_FALSE(svr.is_running());
  215. });
  216. svr.wait_until_ready();
  217. ASSERT_TRUE(svr.is_running());
  218. // Test that Host header is automatically set to "localhost" for Unix socket
  219. // connections
  220. httplib::Client cli{pathname_};
  221. cli.set_address_family(AF_UNIX);
  222. ASSERT_TRUE(cli.is_valid());
  223. const auto &result = cli.Get(pattern_);
  224. ASSERT_TRUE(result) << "error: " << result.error();
  225. const auto &resp = result.value();
  226. EXPECT_EQ(resp.status, StatusCode::OK_200);
  227. EXPECT_EQ(resp.body, content_);
  228. // Verify that Host header was automatically set to "localhost"
  229. EXPECT_EQ(received_host_header, "localhost");
  230. }
  231. #ifndef _WIN32
  232. TEST(SocketStream, wait_writable_UNIX) {
  233. int fds[2];
  234. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  235. const auto asSocketStream = [&](socket_t fd,
  236. std::function<bool(Stream &)> func) {
  237. return detail::process_client_socket(
  238. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  239. };
  240. asSocketStream(fds[0], [&](Stream &s0) {
  241. EXPECT_EQ(s0.socket(), fds[0]);
  242. EXPECT_TRUE(s0.wait_writable());
  243. EXPECT_TRUE(s0.is_peer_alive());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.is_peer_alive());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. // PORT + 1 is shared with the SSL redirect tests and with
  261. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  262. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  263. // because that happens on a worker thread the ASSERT does not stop the
  264. // test: it runs on and fails at the disconnected_svr_sock check instead.
  265. default_socket_options(s);
  266. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, listen(s, 1));
  268. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  269. ASSERT_EQ(0, close(s));
  270. }};
  271. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  272. std::thread cli{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, close(s));
  277. }};
  278. cli.join();
  279. svr.join();
  280. ASSERT_NE(disconnected_svr_sock, -1);
  281. const auto asSocketStream = [&](socket_t fd,
  282. std::function<bool(Stream &)> func) {
  283. return detail::process_client_socket(
  284. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  285. };
  286. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  287. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  288. // wait_writable() returns true because select_write() only checks if the
  289. // send buffer has space. Peer disconnection is detected later by send().
  290. EXPECT_TRUE(ss.wait_writable());
  291. return true;
  292. });
  293. ASSERT_EQ(0, close(disconnected_svr_sock));
  294. }
  295. #endif // #ifndef _WIN32
  296. TEST(SetSocketOptTest, TcpNoDelay) {
  297. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  298. ASSERT_NE(sock, INVALID_SOCKET);
  299. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  300. int val = 0;
  301. socklen_t len = sizeof(val);
  302. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  303. reinterpret_cast<char *>(&val), &len));
  304. EXPECT_NE(val, 0);
  305. detail::close_socket(sock);
  306. }
  307. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  308. // accept() reports failures through WSAGetLastError() on Windows and through
  309. // errno everywhere else. Asking the wrong one is what made the accept loop
  310. // treat every recoverable failure as fatal on Windows.
  311. struct Classification {
  312. bool resource;
  313. bool transient;
  314. };
  315. auto classify = [](int err) {
  316. #ifdef _WIN32
  317. WSASetLastError(err);
  318. #else
  319. errno = err;
  320. #endif
  321. // Read both before asserting: an assertion may clobber the error slot.
  322. Classification c;
  323. c.resource = detail::is_accept_resource_error();
  324. c.transient = detail::is_accept_transient_error();
  325. return c;
  326. };
  327. #ifdef _WIN32
  328. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  329. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  330. WSAECONNRESET, WSAECONNABORTED};
  331. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  332. #else
  333. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  334. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  335. ECONNABORTED};
  336. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  337. #endif
  338. for (auto err : resource_errors) {
  339. const auto c = classify(err);
  340. EXPECT_TRUE(c.resource) << "error " << err;
  341. EXPECT_FALSE(c.transient) << "error " << err;
  342. }
  343. for (auto err : transient_errors) {
  344. const auto c = classify(err);
  345. EXPECT_TRUE(c.transient) << "error " << err;
  346. EXPECT_FALSE(c.resource) << "error " << err;
  347. }
  348. for (auto err : fatal_errors) {
  349. const auto c = classify(err);
  350. EXPECT_FALSE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. #ifdef _WIN32
  354. WSASetLastError(0);
  355. #else
  356. errno = 0;
  357. #endif
  358. }
  359. TEST(ClientTest, MoveConstructible) {
  360. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  361. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  362. }
  363. TEST(ClientTest, MoveAssignable) {
  364. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  365. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  366. }
  367. #ifdef _WIN32
  368. TEST(StartupTest, WSAStartup) {
  369. WSADATA wsaData;
  370. int ret = WSAStartup(0x0002, &wsaData);
  371. ASSERT_EQ(0, ret);
  372. }
  373. #endif
  374. TEST(DecodePathTest, PercentCharacter) {
  375. EXPECT_EQ(
  376. decode_path_component(
  377. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  378. U8("descrip=Gastos áéíóúñÑ 6"));
  379. }
  380. TEST(DecodePathTest, PercentCharacterNUL) {
  381. string expected;
  382. expected.push_back('x');
  383. expected.push_back('\0');
  384. expected.push_back('x');
  385. EXPECT_EQ(decode_path_component("x%00x"), expected);
  386. }
  387. TEST(DecodePathTest, UnicodeEncoding) {
  388. // %u0041 = 'A' (1-byte UTF-8)
  389. EXPECT_EQ("A", decode_path_component("%u0041"));
  390. // %u00E9 = 'é' (2-byte UTF-8)
  391. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  392. // %u3042 = 'あ' (3-byte UTF-8)
  393. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  394. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  395. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  396. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  397. // neighbours)
  398. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  399. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  400. }
  401. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  402. // A sign or whitespace inside the two-character escape window must not be
  403. // accepted as a valid percent-encoding; the sequence is passed through
  404. // literally, matching decode_uri_component / decode_path_component.
  405. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  406. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  407. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  408. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  409. // Well-formed escapes still decode.
  410. EXPECT_EQ("-", decode_query_component("%2D", false));
  411. EXPECT_EQ("A", decode_query_component("%41", false));
  412. }
  413. TEST(SanitizeFilenameTest, VariousPatterns) {
  414. // Path traversal
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  416. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  417. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  418. // Normal and edge cases
  419. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  420. EXPECT_EQ("filename.txt",
  421. httplib::sanitize_filename("/path/to/filename.txt"));
  422. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  423. EXPECT_EQ("", httplib::sanitize_filename(".."));
  424. EXPECT_EQ("", httplib::sanitize_filename(""));
  425. // Null bytes stripped
  426. EXPECT_EQ("safe.txt",
  427. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  428. // Whitespace-only rejected
  429. EXPECT_EQ("", httplib::sanitize_filename(" "));
  430. }
  431. // Forward declaration (see the base64_encode note below): split builds move the
  432. // definition into httplib.cc, so re-declaring it here lets the test link.
  433. namespace httplib {
  434. namespace detail {
  435. bool is_chunked_transfer_encoding(const Headers &headers);
  436. } // namespace detail
  437. } // namespace httplib
  438. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  439. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  440. auto make = [](std::initializer_list<const char *> lines) {
  441. Headers h;
  442. for (auto te : lines) {
  443. if (te) { h.emplace("Transfer-Encoding", te); }
  444. }
  445. return h;
  446. };
  447. // Sole coding, matched case-insensitively.
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  451. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  455. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  460. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  461. // were received, into one list. Headers preserves that order, so the answer
  462. // is decided by the last coding of the last line and the order the lines
  463. // arrived in is significant.
  464. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  466. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  467. // The split can fall anywhere in the list.
  468. EXPECT_TRUE(
  469. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  470. EXPECT_FALSE(
  471. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  472. // A trailing line naming no coding leaves the list ending in nothing, so it
  473. // must not inherit the chunked from the line before it.
  474. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  475. }
  476. // Forward declarations (see the base64_encode note below).
  477. namespace httplib {
  478. namespace detail {
  479. bool parse_status_line(const char *line, std::string &version, int &status,
  480. std::string &reason);
  481. std::string file_extension(const std::string &path);
  482. std::string
  483. find_content_type(const std::string &path,
  484. const std::map<std::string, std::string> &user_data,
  485. const std::string &default_content_type);
  486. bool can_compress_content_type(const std::string &content_type);
  487. bool is_prohibited_header_name(const std::string &name);
  488. #ifdef CPPHTTPLIB_SSL_ENABLED
  489. bool match_hostname(const std::string &pattern, const std::string &hostname);
  490. #endif
  491. } // namespace detail
  492. } // namespace httplib
  493. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  494. struct {
  495. const char *line;
  496. const char *version;
  497. int status;
  498. const char *reason;
  499. } cases[] = {
  500. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  501. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  502. // The reason phrase may be empty, or left out along with its space.
  503. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  504. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  505. };
  506. for (const auto &c : cases) {
  507. std::string version;
  508. int status = 0;
  509. std::string reason = "unset";
  510. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  511. << c.line;
  512. EXPECT_EQ(c.version, version);
  513. EXPECT_EQ(c.status, status);
  514. EXPECT_EQ(c.reason, reason);
  515. }
  516. }
  517. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  518. const char *lines[] = {
  519. "HTTP/2 200 OK\r\n",
  520. "HTTP/1.2 200 OK\r\n",
  521. "HTTP/1.1 20 OK\r\n",
  522. "HTTP/1.1 2000 OK\r\n",
  523. "HTTP/1.1 2x0 OK\r\n",
  524. "HTTP/1.1 200 OK\r\n",
  525. "HTTP/1.1 200OK\r\n",
  526. "HTTP/1.1 200 O\rK\r\n",
  527. "HTTP/1.1 200 OK",
  528. "HTTP/1.1 200 OK\r\nX",
  529. "",
  530. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  531. "HTTP/1.1 200 OK\n",
  532. #endif
  533. };
  534. for (auto line : lines) {
  535. std::string version;
  536. int status = 0;
  537. std::string reason;
  538. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  539. << line;
  540. }
  541. }
  542. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  543. // Long enough to overflow the stack when matched with std::regex.
  544. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  545. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  546. std::string version;
  547. int status = 0;
  548. std::string reason;
  549. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  550. EXPECT_EQ(200, status);
  551. EXPECT_EQ(long_reason, reason);
  552. }
  553. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  554. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  555. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  556. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  557. EXPECT_EQ("", detail::file_extension("noext"));
  558. EXPECT_EQ("", detail::file_extension("a."));
  559. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  560. EXPECT_EQ("", detail::file_extension("a.b-c"));
  561. // Long enough to overflow the stack when matched with std::regex.
  562. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  563. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  564. }
  565. #ifdef CPPHTTPLIB_SSL_ENABLED
  566. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  567. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  569. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  570. // A wildcard needs two labels after it, in the leftmost label only
  571. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  572. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  573. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  574. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  575. EXPECT_FALSE(
  576. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  577. // No name may have an empty label
  578. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  579. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  580. }
  581. #endif
  582. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  583. detail::case_ignore::hash hash;
  584. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  585. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  586. // Long enough to overflow the stack if hashed one call per character.
  587. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  588. }
  589. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  590. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  591. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  592. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  593. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  594. // Same 26-bit hash as html, svg and js.
  595. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  597. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  598. }
  599. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  600. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  601. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  602. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  603. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  604. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  605. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  606. // Same 26-bit hash as application/json.
  607. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  608. }
  609. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  610. Request req;
  611. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  612. EXPECT_TRUE(req.is_multipart_form_data());
  613. std::string boundary;
  614. EXPECT_TRUE(detail::parse_multipart_boundary(
  615. req.get_header_value("Content-Type"), boundary));
  616. EXPECT_EQ("x", boundary);
  617. }
  618. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  619. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  620. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  621. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  623. // Same 26-bit hash as REMOTE_ADDR.
  624. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  625. }
  626. // Forward declaration: in split builds split.py strips `inline` and moves the
  627. // definition into httplib.cc, so detail::base64_encode is not visible from the
  628. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  629. // in both header-only and split builds.
  630. namespace httplib {
  631. namespace detail {
  632. std::string base64_encode(const std::string &in);
  633. } // namespace detail
  634. } // namespace httplib
  635. TEST(Base64EncodeTest, KnownAnswers) {
  636. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  637. // where the accumulator's top bit is already set before the next shift.
  638. EXPECT_EQ("", detail::base64_encode(""));
  639. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  640. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  641. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  642. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  643. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  644. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  645. // High bytes keep the top bit set across several rounds.
  646. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  647. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  648. }
  649. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  650. string unescapedCharacters = "-_.!~*'()";
  651. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  652. }
  653. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  654. string reservedCharacters = ";,/?:@&=+$";
  655. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  656. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  657. }
  658. TEST(ClientQueryOrder, PreserveOrder) {
  659. // This test reproduces Issue #2259: client may reorder query parameters
  660. // when sending a GET request. The expected behavior is that the client
  661. // preserves the original query string order when the caller supplied it
  662. // as part of the path.
  663. Server svr;
  664. svr.Get("/", [&](const Request &req, Response &res) {
  665. // Echo back the raw target so the test can assert ordering
  666. res.set_content(req.target, "text/plain");
  667. });
  668. std::thread t{[&] { svr.listen(HOST, PORT); }};
  669. auto se = detail::scope_exit([&] {
  670. svr.stop();
  671. t.join();
  672. ASSERT_FALSE(svr.is_running());
  673. });
  674. svr.wait_until_ready();
  675. Client cli(HOST, PORT);
  676. ASSERT_TRUE(cli.is_valid());
  677. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  678. auto res = cli.Get(original);
  679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  680. // Expect the echoed target to exactly match the original path (order
  681. // preserved)
  682. EXPECT_EQ(res->body, original);
  683. }
  684. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  685. string chineseCharacters = U8("中国語");
  686. string russianCharacters = U8("дом");
  687. string brazilianCharacters = U8("óculos");
  688. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  689. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  690. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  691. "%D0%B4%D0%BE%D0%BC");
  692. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  693. }
  694. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  695. string unescapedCharacters = "-_.!~*'()";
  696. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  697. }
  698. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  699. string reservedCharacters = ";,/?:@&=+$";
  700. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  701. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  702. }
  703. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  704. string chineseCharacters = U8("中国語");
  705. string russianCharacters = U8("дом");
  706. string brazilianCharacters = U8("óculos");
  707. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  708. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  709. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  710. "%D0%B4%D0%BE%D0%BC");
  711. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  712. }
  713. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  714. // Issue #2082 use case: encoding path component with ampersand
  715. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  716. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  717. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  718. }
  719. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  720. string unescapedCharacters = "-_.!~*'()";
  721. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  722. }
  723. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  724. string reservedCharacters = ";,/?:@&=+$#";
  725. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  726. }
  727. TEST(EncodeUriTest, TestUTF8Characters) {
  728. string chineseCharacters = U8("中国語");
  729. string russianCharacters = U8("дом");
  730. string brazilianCharacters = U8("óculos");
  731. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  732. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  733. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  734. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  735. }
  736. TEST(EncodeUriTest, TestCompleteUri) {
  737. string uri =
  738. "https://example.com/path/to/resource?query=value&param=test#fragment";
  739. EXPECT_EQ(
  740. httplib::encode_uri(uri),
  741. "https://example.com/path/to/resource?query=value&param=test#fragment");
  742. }
  743. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  744. string uri =
  745. "https://example.com/path with spaces/file name.html?q=hello world";
  746. EXPECT_EQ(httplib::encode_uri(uri),
  747. "https://example.com/path%20with%20spaces/"
  748. "file%20name.html?q=hello%20world");
  749. }
  750. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  751. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  752. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  753. }
  754. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  755. string unescapedCharacters = "-_.!~*'()";
  756. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  757. }
  758. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  759. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  760. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  761. string encodedBrazilian = "%C3%B3culos";
  762. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  764. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  765. }
  766. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  767. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  768. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  769. "Piri Tommy Villiers - on & on");
  770. }
  771. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  772. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  773. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  774. }
  775. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  776. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  777. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  778. }
  779. TEST(DecodeUriTest, TestUTF8Characters) {
  780. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  781. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  782. string encodedBrazilian = "%C3%B3culos";
  783. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  784. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  785. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  786. }
  787. TEST(DecodeUriTest, TestCompleteUri) {
  788. string encodedUri = "https://example.com/path%20with%20spaces/"
  789. "file%20name.html?q=hello%20world";
  790. EXPECT_EQ(
  791. httplib::decode_uri(encodedUri),
  792. "https://example.com/path with spaces/file name.html?q=hello world");
  793. }
  794. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  795. string original =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. string encoded = httplib::encode_uri(original);
  798. string decoded = httplib::decode_uri(encoded);
  799. EXPECT_EQ(decoded, original);
  800. }
  801. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  802. // decode_uri is the inverse of encode_uri: an escaped reserved character
  803. // stays encoded so it is not promoted into a real delimiter, while
  804. // non-reserved escapes still decode (like JS decodeURI).
  805. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  806. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  807. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  808. "%3F%3A%40%26%3D%2B%24%2C%3B");
  809. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  810. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  811. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  812. "http://example.com/a%2Fb");
  813. // decode_uri_component still decodes the reserved character.
  814. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  815. }
  816. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  817. string original = "Piri Tommy Villiers - on & on";
  818. string encoded = httplib::encode_uri_component(original);
  819. string decoded = httplib::decode_uri_component(encoded);
  820. EXPECT_EQ(decoded, original);
  821. }
  822. TEST(TrimTests, TrimStringTests) {
  823. EXPECT_EQ("abc", detail::trim_copy("abc"));
  824. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  825. EXPECT_TRUE(detail::trim_copy("").empty());
  826. }
  827. TEST(AsciiTest, LocaleIndependentClassification) {
  828. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  829. // which consult the global C locale: std::isalnum(0xC5) can return true
  830. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  831. // helpers must classify every byte by the ASCII grammar alone.
  832. for (int i = 0; i < 256; i++) {
  833. auto c = static_cast<char>(i);
  834. auto is_digit = i >= '0' && i <= '9';
  835. auto is_upper = i >= 'A' && i <= 'Z';
  836. auto is_lower = i >= 'a' && i <= 'z';
  837. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  838. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  839. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  840. << "byte " << i;
  841. }
  842. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  843. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  844. // Non-ASCII bytes must be percent-encoded, never passed through as
  845. // alphanumeric.
  846. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  847. }
  848. TEST(FromCharsTest, Double) {
  849. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  850. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  851. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  852. auto parse = [](const std::string &s, double &v) {
  853. return detail::from_chars(s.data(), s.data() + s.size(), v);
  854. };
  855. double v = -1.0;
  856. // Representative quality values.
  857. EXPECT_EQ(parse("0", v).ec, std::errc{});
  858. EXPECT_DOUBLE_EQ(v, 0.0);
  859. EXPECT_EQ(parse("1", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 1.0);
  861. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 0.8);
  863. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.001);
  865. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 1.0);
  867. // A missing integer or fractional part is tolerated.
  868. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 0.5);
  870. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 5.0);
  872. // Values outside [0, 1] still parse; the caller range-checks them.
  873. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 123.456);
  875. // Stops at the first byte that is not part of the number and reports where.
  876. std::string trailing = "0.9, text/html";
  877. auto r = parse(trailing, v);
  878. EXPECT_EQ(r.ec, std::errc{});
  879. EXPECT_DOUBLE_EQ(v, 0.9);
  880. EXPECT_EQ(*r.ptr, ',');
  881. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  882. // outright, and an 'e'/'E' simply ends the number.
  883. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  884. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  885. std::string exp_input = "1.5e3";
  886. r = parse(exp_input, v);
  887. EXPECT_EQ(r.ec, std::errc{});
  888. EXPECT_DOUBLE_EQ(v, 1.5);
  889. EXPECT_EQ(*r.ptr, 'e');
  890. // Invalid inputs.
  891. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  896. // Pathological but well-formed inputs must stay bounded (no overflow, no
  897. // out-of-bounds table access) and stay within [0, 1] for the caller.
  898. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  899. std::errc{});
  900. EXPECT_DOUBLE_EQ(v, 0.0);
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  902. std::errc{});
  903. EXPECT_GE(v, 0.0);
  904. EXPECT_LE(v, 1.0);
  905. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  906. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  907. }
  908. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  909. // Simple case without quality values
  910. std::vector<std::string> result1;
  911. EXPECT_TRUE(detail::parse_accept_header(
  912. "text/html,application/json,text/plain", result1));
  913. EXPECT_EQ(result1.size(), 3U);
  914. EXPECT_EQ(result1[0], "text/html");
  915. EXPECT_EQ(result1[1], "application/json");
  916. EXPECT_EQ(result1[2], "text/plain");
  917. // With quality values
  918. std::vector<std::string> result2;
  919. EXPECT_TRUE(detail::parse_accept_header(
  920. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  921. EXPECT_EQ(result2.size(), 3U);
  922. EXPECT_EQ(result2[0], "application/json"); // highest q value
  923. EXPECT_EQ(result2[1], "text/html");
  924. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  925. }
  926. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  927. // Mixed with and without quality values
  928. std::vector<std::string> result;
  929. EXPECT_TRUE(detail::parse_accept_header(
  930. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  931. EXPECT_EQ(result.size(), 3U);
  932. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  933. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  934. EXPECT_EQ(result[2], "application/json"); // q=0.5
  935. }
  936. TEST(ParseAcceptHeaderTest, EdgeCases) {
  937. // Empty header
  938. std::vector<std::string> empty_result;
  939. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  940. EXPECT_TRUE(empty_result.empty());
  941. // Single type
  942. std::vector<std::string> single_result;
  943. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  944. EXPECT_EQ(single_result.size(), 1U);
  945. EXPECT_EQ(single_result[0], "application/json");
  946. // Wildcard types
  947. std::vector<std::string> wildcard_result;
  948. EXPECT_TRUE(detail::parse_accept_header(
  949. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  950. EXPECT_EQ(wildcard_result.size(), 3U);
  951. EXPECT_EQ(wildcard_result[0], "application/json");
  952. EXPECT_EQ(wildcard_result[1], "text/*");
  953. EXPECT_EQ(wildcard_result[2], "*/*");
  954. }
  955. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  956. // Common browser Accept header
  957. std::vector<std::string> browser_result;
  958. EXPECT_TRUE(
  959. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  960. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  961. browser_result));
  962. EXPECT_EQ(browser_result.size(), 6U);
  963. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  968. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  969. // API client header
  970. std::vector<std::string> api_result;
  971. EXPECT_TRUE(detail::parse_accept_header(
  972. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  973. api_result));
  974. EXPECT_EQ(api_result.size(), 3U);
  975. EXPECT_EQ(api_result[0], "application/json");
  976. EXPECT_EQ(api_result[1], "application/xml");
  977. EXPECT_EQ(api_result[2], "text/plain");
  978. }
  979. TEST(ParseAcceptHeaderTest, SpecialCases) {
  980. // Quality value with 3 decimal places
  981. std::vector<std::string> decimal_result;
  982. EXPECT_TRUE(detail::parse_accept_header(
  983. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  984. EXPECT_EQ(decimal_result.size(), 2U);
  985. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  986. EXPECT_EQ(decimal_result[1], "text/html");
  987. // Zero quality (should still be included but with lowest priority)
  988. std::vector<std::string> zero_q_result;
  989. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  990. zero_q_result));
  991. EXPECT_EQ(zero_q_result.size(), 2U);
  992. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  993. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  994. // No spaces around commas
  995. std::vector<std::string> no_space_result;
  996. EXPECT_TRUE(detail::parse_accept_header(
  997. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  998. no_space_result));
  999. EXPECT_EQ(no_space_result.size(), 3U);
  1000. EXPECT_EQ(no_space_result[0], "text/html");
  1001. EXPECT_EQ(no_space_result[1], "application/json");
  1002. EXPECT_EQ(no_space_result[2], "text/plain");
  1003. }
  1004. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1005. // Quality values always use '.' as the decimal separator, so parsing must
  1006. // not depend on the process locale. An embedding application may have
  1007. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1008. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1009. std::string saved = cur ? cur : "C";
  1010. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1011. "fr_FR.UTF-8"};
  1012. bool switched = false;
  1013. for (const auto loc : comma_locales) {
  1014. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1015. std::localeconv()->decimal_point[0] == ',') {
  1016. switched = true;
  1017. break;
  1018. }
  1019. }
  1020. if (!switched) {
  1021. std::setlocale(LC_NUMERIC, saved.c_str());
  1022. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1023. }
  1024. // The higher-weighted type appears later in the list, so a correct parse
  1025. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1026. // sensitive parse reads both weights as 0 and leaves the original order.
  1027. std::vector<std::string> result;
  1028. EXPECT_TRUE(detail::parse_accept_header(
  1029. "application/json;q=0.1,text/html;q=0.9", result));
  1030. ASSERT_EQ(result.size(), 2U);
  1031. EXPECT_EQ(result[0], "text/html");
  1032. EXPECT_EQ(result[1], "application/json");
  1033. std::setlocale(LC_NUMERIC, saved.c_str());
  1034. }
  1035. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1036. std::vector<std::string> result;
  1037. // Invalid quality value (> 1.0)
  1038. EXPECT_FALSE(
  1039. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1040. // Invalid quality value (< 0.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1043. // Invalid quality value (not a number)
  1044. EXPECT_FALSE(detail::parse_accept_header(
  1045. "text/html;q=invalid,application/json", result));
  1046. // A valid numeric prefix does not make the entire quality value valid.
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=0.5junk,application/json", result));
  1049. // Empty quality value
  1050. EXPECT_FALSE(
  1051. detail::parse_accept_header("text/html;q=,application/json", result));
  1052. // Invalid media type format (no slash and not wildcard)
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("invalidtype,application/json", result));
  1055. // Valid cases should still work
  1056. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1057. EXPECT_EQ(result.size(), 1U);
  1058. EXPECT_EQ(result[0], "*/*");
  1059. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*");
  1062. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "text/*");
  1065. }
  1066. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1067. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1068. // and must not be answered with 400 Bad Request.
  1069. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1070. struct {
  1071. const char *value;
  1072. std::vector<std::string> expected;
  1073. } cases[] = {
  1074. {",application/json", {"application/json"}},
  1075. {"text/html,", {"text/html"}},
  1076. {"text/html,,*/*", {"text/html", "*/*"}},
  1077. // An empty element may be spelled with whitespace in it
  1078. {"text/html, , application/json", {"text/html", "application/json"}},
  1079. // Nothing but empty elements is an empty list, which means the same
  1080. // thing as no Accept header at all
  1081. {",,,", {}},
  1082. // Quality values still apply across ignored empty elements
  1083. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1084. };
  1085. for (const auto &c : cases) {
  1086. std::vector<std::string> result;
  1087. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1088. << "value: " << c.value;
  1089. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1090. }
  1091. // An invalid entry is still rejected when empty elements surround it
  1092. std::vector<std::string> result;
  1093. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1094. }
  1095. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1096. // or ';' inside one does not end the list element or the parameter. Section
  1097. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1098. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1099. struct {
  1100. const char *value;
  1101. std::vector<std::string> expected;
  1102. } cases[] = {
  1103. {"text/html;profile=\"a,b\",application/json",
  1104. {"text/html", "application/json"}},
  1105. // A "q=" inside a quoted value is not the weight
  1106. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1107. {"text/html", "application/json"}},
  1108. // The weight after a quoted value still applies
  1109. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1110. {"application/json", "text/html"}},
  1111. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\"b\",application/json",
  1114. {"text/html", "application/json"}},
  1115. // An escaped backslash does not escape the '"' after it
  1116. {"text/html;profile=\"a\\\\\",application/json",
  1117. {"text/html", "application/json"}},
  1118. };
  1119. for (const auto &c : cases) {
  1120. std::vector<std::string> result;
  1121. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1122. << "value: " << c.value;
  1123. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1124. }
  1125. }
  1126. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1127. Server svr;
  1128. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1129. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1130. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1131. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1132. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1133. res.set_content("ok", "text/plain");
  1134. });
  1135. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1136. EXPECT_TRUE(false);
  1137. res.set_content("bad request", "text/plain");
  1138. });
  1139. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. listen_thread.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. Client cli("localhost", PORT);
  1147. {
  1148. auto res = cli.Get(
  1149. "/accept_ok",
  1150. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. }
  1154. {
  1155. auto res = cli.Get("/accept_bad_request",
  1156. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1158. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1159. }
  1160. }
  1161. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1162. Server svr;
  1163. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1164. res.set_content("ok", "text/plain");
  1165. });
  1166. std::atomic<int> start_count{0};
  1167. std::atomic<bool> running_when_called{false};
  1168. svr.set_start_handler([&]() {
  1169. running_when_called = svr.is_running();
  1170. start_count++;
  1171. });
  1172. auto port = svr.bind_to_any_port(HOST);
  1173. std::thread t([&]() { svr.listen_after_bind(); });
  1174. auto se = detail::scope_exit([&] {
  1175. svr.stop();
  1176. t.join();
  1177. ASSERT_FALSE(svr.is_running());
  1178. });
  1179. svr.wait_until_ready();
  1180. // A successful request proves the accept loop is running, which the start
  1181. // handler precedes; so by now the handler must have run exactly once.
  1182. Client cli(HOST, port);
  1183. cli.set_connection_timeout(std::chrono::seconds(5));
  1184. auto res = cli.Get("/");
  1185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1186. EXPECT_EQ(StatusCode::OK_200, res->status);
  1187. EXPECT_EQ(1, start_count.load());
  1188. EXPECT_TRUE(running_when_called.load());
  1189. }
  1190. TEST(DivideTest, DivideStringTests) {
  1191. auto divide = [](const std::string &str, char d) {
  1192. std::string lhs;
  1193. std::string rhs;
  1194. detail::divide(str, d,
  1195. [&](const char *lhs_data, std::size_t lhs_size,
  1196. const char *rhs_data, std::size_t rhs_size) {
  1197. lhs.assign(lhs_data, lhs_size);
  1198. rhs.assign(rhs_data, rhs_size);
  1199. });
  1200. return std::make_pair(std::move(lhs), std::move(rhs));
  1201. };
  1202. {
  1203. const auto res = divide("", '=');
  1204. EXPECT_EQ(res.first, "");
  1205. EXPECT_EQ(res.second, "");
  1206. }
  1207. {
  1208. const auto res = divide("=", '=');
  1209. EXPECT_EQ(res.first, "");
  1210. EXPECT_EQ(res.second, "");
  1211. }
  1212. {
  1213. const auto res = divide(" ", '=');
  1214. EXPECT_EQ(res.first, " ");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("a", '=');
  1219. EXPECT_EQ(res.first, "a");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide("a=", '=');
  1224. EXPECT_EQ(res.first, "a");
  1225. EXPECT_EQ(res.second, "");
  1226. }
  1227. {
  1228. const auto res = divide("=b", '=');
  1229. EXPECT_EQ(res.first, "");
  1230. EXPECT_EQ(res.second, "b");
  1231. }
  1232. {
  1233. const auto res = divide("a=b", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "b");
  1236. }
  1237. {
  1238. const auto res = divide("a=b=", '=');
  1239. EXPECT_EQ(res.first, "a");
  1240. EXPECT_EQ(res.second, "b=");
  1241. }
  1242. {
  1243. const auto res = divide("a=b=c", '=');
  1244. EXPECT_EQ(res.first, "a");
  1245. EXPECT_EQ(res.second, "b=c");
  1246. }
  1247. }
  1248. TEST(SplitTest, ParseQueryString) {
  1249. string s = "key1=val1&key2=val2&key3=val3";
  1250. Params dic;
  1251. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1252. [&](const char *b, const char *e) {
  1253. string key, val;
  1254. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1255. if (key.empty()) {
  1256. key.assign(b2, e2);
  1257. } else {
  1258. val.assign(b2, e2);
  1259. }
  1260. });
  1261. dic.emplace(key, val);
  1262. });
  1263. EXPECT_EQ("val1", dic.find("key1")->second);
  1264. EXPECT_EQ("val2", dic.find("key2")->second);
  1265. EXPECT_EQ("val3", dic.find("key3")->second);
  1266. }
  1267. TEST(SplitTest, ParseInvalidQueryTests) {
  1268. {
  1269. string s = " ";
  1270. Params dict;
  1271. detail::parse_query_text(s, dict);
  1272. EXPECT_TRUE(dict.empty());
  1273. }
  1274. {
  1275. string s = " = =";
  1276. Params dict;
  1277. detail::parse_query_text(s, dict);
  1278. EXPECT_TRUE(dict.empty());
  1279. }
  1280. }
  1281. TEST(ParseQueryTest, ParseQueryString) {
  1282. {
  1283. std::string s = "key1=val1&key2=val2&key3=val3";
  1284. Params dic;
  1285. detail::parse_query_text(s, dic);
  1286. EXPECT_EQ("val1", dic.find("key1")->second);
  1287. EXPECT_EQ("val2", dic.find("key2")->second);
  1288. EXPECT_EQ("val3", dic.find("key3")->second);
  1289. }
  1290. {
  1291. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1292. Params dic;
  1293. detail::parse_query_text(s, dic);
  1294. EXPECT_EQ("", dic.find("key1")->second);
  1295. EXPECT_EQ("val1", dic.find("key2")->second);
  1296. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1297. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1298. }
  1299. }
  1300. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1301. Params dic;
  1302. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1303. dic.emplace("key1", "val1");
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1305. dic.emplace("key2", "val2");
  1306. dic.emplace("key3", "val3");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1308. }
  1309. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1310. Params params;
  1311. params.emplace("a", "1");
  1312. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1313. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1314. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1315. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1316. // Long enough to overflow the stack when matched with std::regex.
  1317. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1318. EXPECT_EQ("/p?" + long_query + "&a=1",
  1319. append_query_params("/p?" + long_query, params));
  1320. }
  1321. // Joins every entry of a Headers or Params into "key=value " so a whole
  1322. // traversal can be compared in one assertion. Both are instantiations of the
  1323. // same insertion-ordered container, so one helper serves both.
  1324. template <typename Map> static std::string entries_to_string(const Map &m) {
  1325. std::string s;
  1326. for (const auto &entry : m) {
  1327. s += entry.first + "=" + entry.second + " ";
  1328. }
  1329. return s;
  1330. }
  1331. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1332. // Params used to be a std::multimap, which sorted by name and handed the
  1333. // caller's query back alphabetised. A client signing its query string could
  1334. // not reproduce the order it asked for.
  1335. Params dic;
  1336. dic.emplace("zulu", "1");
  1337. dic.emplace("alpha", "2");
  1338. dic.emplace("mike", "3");
  1339. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1340. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1341. }
  1342. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1343. Params dic;
  1344. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1345. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1346. }
  1347. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1348. Request req;
  1349. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1350. req.params);
  1351. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag"));
  1353. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1354. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1355. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1356. EXPECT_EQ("", req.get_param_value("tag", 3));
  1357. }
  1358. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1359. // Params shares its container with Headers, which matches field names
  1360. // case-insensitively. Parameter names must not pick that up.
  1361. Params dic;
  1362. dic.emplace("Key", "upper");
  1363. dic.emplace("key", "lower");
  1364. EXPECT_EQ(2U, dic.size());
  1365. EXPECT_EQ(1U, dic.count("Key"));
  1366. EXPECT_EQ(1U, dic.count("key"));
  1367. EXPECT_EQ("upper", dic.find("Key")->second);
  1368. EXPECT_EQ("lower", dic.find("key")->second);
  1369. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1370. }
  1371. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1372. Server svr;
  1373. std::string order;
  1374. svr.Get("/order", [&](const Request &req, Response &res) {
  1375. order = entries_to_string(req.params);
  1376. res.set_content("ok", "text/plain");
  1377. });
  1378. auto port = svr.bind_to_any_port(HOST);
  1379. thread t = thread([&] { svr.listen_after_bind(); });
  1380. auto se = detail::scope_exit([&] {
  1381. svr.stop();
  1382. t.join();
  1383. ASSERT_FALSE(svr.is_running());
  1384. });
  1385. svr.wait_until_ready();
  1386. Client cli(HOST, port);
  1387. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1388. ASSERT_TRUE(res);
  1389. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1390. }
  1391. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1392. Server svr;
  1393. std::string field_order, file_order;
  1394. svr.Post("/order", [&](const Request &req, Response &res) {
  1395. for (const auto &field : req.form.fields) {
  1396. field_order += field.first + "=" + field.second.content + " ";
  1397. }
  1398. for (const auto &file : req.form.files) {
  1399. file_order += file.first + "=" + file.second.filename + " ";
  1400. }
  1401. res.set_content("ok", "text/plain");
  1402. });
  1403. auto port = svr.bind_to_any_port(HOST);
  1404. thread t = thread([&] { svr.listen_after_bind(); });
  1405. auto se = detail::scope_exit([&] {
  1406. svr.stop();
  1407. t.join();
  1408. ASSERT_FALSE(svr.is_running());
  1409. });
  1410. svr.wait_until_ready();
  1411. UploadFormDataItems items = {
  1412. {"zulu", "1", "", ""},
  1413. {"alpha", "2", "", ""},
  1414. {"mike", "3", "", ""},
  1415. {"zebra", "z", "z.txt", "text/plain"},
  1416. {"apple", "a", "a.txt", "text/plain"},
  1417. };
  1418. Client cli(HOST, port);
  1419. auto res = cli.Post("/order", items);
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1422. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1423. }
  1424. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1425. Server svr;
  1426. std::vector<std::string> values;
  1427. std::string first, second, out_of_range, order;
  1428. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1429. values = req.form.get_fields("tag");
  1430. first = req.form.get_field("tag", 0);
  1431. second = req.form.get_field("tag", 1);
  1432. out_of_range = req.form.get_field("tag", 2);
  1433. for (const auto &field : req.form.fields) {
  1434. order += field.first + "=" + field.second.content + " ";
  1435. }
  1436. res.set_content("ok", "text/plain");
  1437. });
  1438. auto port = svr.bind_to_any_port(HOST);
  1439. thread t = thread([&] { svr.listen_after_bind(); });
  1440. auto se = detail::scope_exit([&] {
  1441. svr.stop();
  1442. t.join();
  1443. ASSERT_FALSE(svr.is_running());
  1444. });
  1445. svr.wait_until_ready();
  1446. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1447. // not adjacent in the container.
  1448. UploadFormDataItems items = {
  1449. {"tag", "first", "", ""},
  1450. {"other", "x", "", ""},
  1451. {"tag", "second", "", ""},
  1452. };
  1453. Client cli(HOST, port);
  1454. auto res = cli.Post("/repeated", items);
  1455. ASSERT_TRUE(res);
  1456. ASSERT_EQ(2U, values.size());
  1457. EXPECT_EQ("first", values[0]);
  1458. EXPECT_EQ("second", values[1]);
  1459. EXPECT_EQ("first", first);
  1460. EXPECT_EQ("second", second);
  1461. // std::multimap already kept entries sharing a name in insertion order, so
  1462. // everything above passes without this change too. The whole traversal is
  1463. // what tells the two apart: sorting by name would hoist "other" to the front
  1464. // and the two "tag" parts would end up adjacent.
  1465. EXPECT_EQ("tag=first other=x tag=second ", order);
  1466. // Advancing past the last entry of a name used to run off the container;
  1467. // the container's saturating increment makes it return the default instead.
  1468. EXPECT_EQ("", out_of_range);
  1469. }
  1470. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1471. Server svr;
  1472. std::string file_names;
  1473. svr.Post("/upload", [&](const Request &req, Response &res) {
  1474. for (const auto &file : req.form.files) {
  1475. file_names += file.first + "|" + file.second.filename + " ";
  1476. }
  1477. res.set_content("ok", "text/plain");
  1478. });
  1479. auto port = svr.bind_to_any_port(HOST);
  1480. thread t = thread([&] { svr.listen_after_bind(); });
  1481. auto se = detail::scope_exit([&] {
  1482. svr.stop();
  1483. t.join();
  1484. ASSERT_FALSE(svr.is_running());
  1485. });
  1486. svr.wait_until_ready();
  1487. // A trailing backslash would otherwise escape the closing quote.
  1488. UploadFormDataItems items = {
  1489. {"dir\\", "x", "a.txt", "text/plain"},
  1490. {"b", "y", "a\\\\b.txt", "text/plain"},
  1491. };
  1492. Client cli(HOST, port);
  1493. auto res = cli.Post("/upload", items);
  1494. ASSERT_TRUE(res);
  1495. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1496. }
  1497. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1498. // Server::read_content() keeps a FormFields::iterator alive across the
  1499. // content callbacks that fill the part it points at. The container is
  1500. // vector-backed, so a later emplace can reallocate and invalidate an older
  1501. // iterator; 64 parts grow the vector through seven reallocations, which
  1502. // checks that every part's content still lands in its own entry.
  1503. const size_t part_count = 64;
  1504. // One formula for both the parts sent and the values expected back, so the
  1505. // two cannot drift apart.
  1506. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1507. auto content_of = [](size_t i) {
  1508. return std::string(64, static_cast<char>('a' + (i % 26)));
  1509. };
  1510. Server svr;
  1511. std::vector<std::pair<std::string, std::string>> received;
  1512. svr.Post("/many", [&](const Request &req, Response &res) {
  1513. for (const auto &field : req.form.fields) {
  1514. received.emplace_back(field.first, field.second.content);
  1515. }
  1516. res.set_content("ok", "text/plain");
  1517. });
  1518. auto port = svr.bind_to_any_port(HOST);
  1519. thread t = thread([&] { svr.listen_after_bind(); });
  1520. auto se = detail::scope_exit([&] {
  1521. svr.stop();
  1522. t.join();
  1523. ASSERT_FALSE(svr.is_running());
  1524. });
  1525. svr.wait_until_ready();
  1526. UploadFormDataItems items;
  1527. for (size_t i = 0; i < part_count; i++) {
  1528. items.push_back({name_of(i), content_of(i), "", ""});
  1529. }
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/many", items);
  1532. ASSERT_TRUE(res);
  1533. ASSERT_EQ(part_count, received.size());
  1534. for (size_t i = 0; i < part_count; i++) {
  1535. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1536. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1537. }
  1538. }
  1539. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1540. string content_type = "multipart/form-data; boundary=something";
  1541. string boundary;
  1542. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1543. EXPECT_TRUE(ret);
  1544. EXPECT_EQ(boundary, "something");
  1545. }
  1546. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1547. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1548. string boundary;
  1549. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1550. EXPECT_TRUE(ret);
  1551. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1552. }
  1553. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1554. string content_type =
  1555. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1556. string boundary;
  1557. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1558. EXPECT_TRUE(ret);
  1559. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1560. }
  1561. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1562. string content_type =
  1563. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1564. string boundary;
  1565. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1566. EXPECT_TRUE(ret);
  1567. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1568. }
  1569. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1570. const string boundary(70, 'a');
  1571. string content_type = "multipart/form-data; boundary=" + boundary;
  1572. string parsed;
  1573. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1574. EXPECT_TRUE(ret);
  1575. EXPECT_EQ(parsed, boundary);
  1576. }
  1577. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1578. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1579. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1580. string parsed;
  1581. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1582. EXPECT_FALSE(ret);
  1583. }
  1584. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1585. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1586. // is 72 characters on the wire and still valid.
  1587. const string boundary(70, 'a');
  1588. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1589. string parsed;
  1590. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1591. EXPECT_EQ(parsed, boundary);
  1592. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1593. parsed.clear();
  1594. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1595. }
  1596. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1597. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1598. // The parameter parser must not treat that '=' as the key/value separator.
  1599. string content_type =
  1600. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1601. "charset=UTF-8";
  1602. string parsed;
  1603. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1604. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1605. }
  1606. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1607. // A ';' inside the quoted-string is part of the value, not a parameter
  1608. // separator, so it must not truncate the boundary.
  1609. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1610. string parsed;
  1611. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1612. EXPECT_EQ(parsed, "a;b");
  1613. }
  1614. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1615. string parsed;
  1616. EXPECT_TRUE(detail::parse_multipart_boundary(
  1617. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1618. EXPECT_EQ("a\\b", parsed);
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1621. EXPECT_EQ("a\"b", parsed);
  1622. }
  1623. TEST(ParseDispositionParamsTest, QuotedValues) {
  1624. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1625. // ';' and '=' are ordinary characters inside one.
  1626. struct {
  1627. const char *value;
  1628. std::vector<std::pair<const char *, const char *>> expected;
  1629. } cases[] = {
  1630. {"name=\"file1\"; filename=\"a.txt\"",
  1631. {{"name", "file1"}, {"filename", "a.txt"}}},
  1632. // Whitespace around '=' and ';' is still trimmed
  1633. {"name=\"file2\" ;filename = \"a.html\"",
  1634. {{"name", "file2"}, {"filename", "a.html"}}},
  1635. // '=' inside the value used to leave only the text after the last one
  1636. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1637. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1638. {"name=\"x=y\"", {{"name", "x=y"}}},
  1639. // ';' inside the value used to truncate the pair and leave a bogus one
  1640. {"name=\"file3\"; filename=\"a;b.txt\"",
  1641. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1642. // An unquoted value keeps working, and so does filename*
  1643. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1644. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1645. // A parameter with no key is dropped rather than turned into one whose
  1646. // key is the value
  1647. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1648. // An escaped quote does not end the value
  1649. {"name=\"a\\\"; filename=evil.php\"",
  1650. {{"name", "a\"; filename=evil.php"}}},
  1651. // Other backslashes, as in a Windows path, are kept
  1652. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1653. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1654. };
  1655. for (const auto &c : cases) {
  1656. Params params;
  1657. detail::parse_disposition_params(c.value, params);
  1658. for (const auto &kv : c.expected) {
  1659. auto it = params.find(kv.first);
  1660. ASSERT_NE(it, params.end())
  1661. << "value: " << c.value << ", key: " << kv.first;
  1662. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1663. }
  1664. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1665. }
  1666. }
  1667. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1668. Server svr;
  1669. std::string filename;
  1670. std::string content;
  1671. svr.Post("/upload", [&](const Request &req, Response &) {
  1672. const auto &file = req.form.get_file("file");
  1673. filename = file.filename;
  1674. content = file.content;
  1675. });
  1676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1677. auto se = detail::scope_exit([&] {
  1678. svr.stop();
  1679. thread.join();
  1680. ASSERT_FALSE(svr.is_running());
  1681. });
  1682. svr.wait_until_ready();
  1683. std::string body = "--B\r\n"
  1684. "Content-Disposition: form-data; name=\"file\"; "
  1685. "filename=\"a.txt\"\r\n"
  1686. "Content-Type: text/plain\r\n"
  1687. "\r\n"
  1688. "hello\r\n"
  1689. "--B--\r\n";
  1690. Client cli(HOST, PORT);
  1691. auto res = cli.Post(
  1692. "/upload",
  1693. [&](size_t offset, DataSink &sink) {
  1694. if (offset < body.size()) {
  1695. sink.write(&body[offset], 1);
  1696. } else {
  1697. sink.done();
  1698. }
  1699. return true;
  1700. },
  1701. "multipart/form-data; boundary=B");
  1702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. EXPECT_EQ("a.txt", filename);
  1705. EXPECT_EQ("hello", content);
  1706. }
  1707. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1708. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1709. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1710. Server svr;
  1711. std::string field_value, file_name, file_filename;
  1712. bool has_field = false, has_file = false;
  1713. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1714. has_field = req.form.has_field("x=y");
  1715. field_value = req.form.get_field("x=y");
  1716. has_file = req.form.has_file("file1");
  1717. const auto &file = req.form.get_file("file1");
  1718. file_name = file.name;
  1719. file_filename = file.filename;
  1720. res.set_content("ok", "text/plain");
  1721. });
  1722. auto port = svr.bind_to_any_port(HOST);
  1723. thread t = thread([&] { svr.listen_after_bind(); });
  1724. auto se = detail::scope_exit([&] {
  1725. svr.stop();
  1726. t.join();
  1727. ASSERT_FALSE(svr.is_running());
  1728. });
  1729. svr.wait_until_ready();
  1730. UploadFormDataItems items = {
  1731. {"x=y", "field-value", "", ""},
  1732. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1733. };
  1734. Client cli(HOST, port);
  1735. auto res = cli.Post("/quoted", items);
  1736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1737. ASSERT_EQ(StatusCode::OK_200, res->status);
  1738. EXPECT_TRUE(has_field);
  1739. EXPECT_EQ("field-value", field_value);
  1740. EXPECT_TRUE(has_file);
  1741. EXPECT_EQ("file1", file_name);
  1742. EXPECT_EQ("a;b=report.pdf", file_filename);
  1743. }
  1744. TEST(GetHeaderValueTest, DefaultValue) {
  1745. Headers headers = {{"Dummy", "Dummy"}};
  1746. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1747. EXPECT_STREQ("text/plain", val);
  1748. }
  1749. TEST(GetHeaderValueTest, DefaultValueInt) {
  1750. Headers headers = {{"Dummy", "Dummy"}};
  1751. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1752. EXPECT_EQ(100ull, val);
  1753. }
  1754. TEST(GetHeaderValueTest, RegularValue) {
  1755. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1756. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1757. EXPECT_STREQ("text/html", val);
  1758. }
  1759. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1760. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1761. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1762. EXPECT_STREQ("text/html", val);
  1763. }
  1764. TEST(GetHeaderValueTest, SetContent) {
  1765. Response res;
  1766. res.set_content("html", "text/html");
  1767. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1768. res.set_content("text", "text/plain");
  1769. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1770. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1771. }
  1772. TEST(GetHeaderValueTest, RegularValueInt) {
  1773. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1774. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1775. EXPECT_EQ(100ull, val);
  1776. }
  1777. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1778. Headers headers = {{"Content-Length", "x"}};
  1779. auto is_invalid_value = false;
  1780. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1781. is_invalid_value);
  1782. EXPECT_EQ(0ull, val);
  1783. EXPECT_TRUE(is_invalid_value);
  1784. }
  1785. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1786. // An all-digit value that overflows size_t must be reported as invalid, not
  1787. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1788. // a large length to a small one on 32-bit builds, leaving the framing length
  1789. // wrong while is_invalid_value stayed false.
  1790. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1791. auto is_invalid_value = false;
  1792. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1793. is_invalid_value);
  1794. EXPECT_TRUE(is_invalid_value);
  1795. // A well-formed length is unaffected.
  1796. Headers ok = {{"Content-Length", "1234"}};
  1797. is_invalid_value = false;
  1798. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1799. is_invalid_value);
  1800. EXPECT_EQ(1234ull, val);
  1801. EXPECT_FALSE(is_invalid_value);
  1802. }
  1803. TEST(GetHeaderValueTest, Range) {
  1804. {
  1805. Headers headers = {make_range_header({{1, -1}})};
  1806. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1807. EXPECT_STREQ("bytes=1-", val);
  1808. }
  1809. {
  1810. Headers headers = {make_range_header({{-1, 1}})};
  1811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1812. EXPECT_STREQ("bytes=-1", val);
  1813. }
  1814. {
  1815. Headers headers = {make_range_header({{1, 10}})};
  1816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1817. EXPECT_STREQ("bytes=1-10", val);
  1818. }
  1819. {
  1820. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1822. EXPECT_STREQ("bytes=1-10, 100-", val);
  1823. }
  1824. {
  1825. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1827. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1828. }
  1829. {
  1830. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1832. EXPECT_STREQ("bytes=0-0, -1", val);
  1833. }
  1834. }
  1835. TEST(BearerTokenAuthTest, SchemeValidation) {
  1836. // A value shorter than "Bearer " must not throw from the fixed-length
  1837. // substr, and a non-Bearer scheme must not be reported as a token.
  1838. struct {
  1839. const char *value;
  1840. const char *expected;
  1841. } cases[] = {
  1842. {"x", ""},
  1843. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1844. {"Bearer abc123", "abc123"},
  1845. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1846. };
  1847. for (const auto &c : cases) {
  1848. Request req;
  1849. req.set_header("Authorization", c.value);
  1850. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1851. }
  1852. }
  1853. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1854. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1855. // to depend on the standard library (libstdc++ handed back duplicates in
  1856. // reverse insertion order, libc++ in insertion order).
  1857. Request req;
  1858. req.set_header("Accept-Encoding", "gzip");
  1859. req.set_header("Accept-Encoding", "deflate");
  1860. req.set_header("Accept-Encoding", "br");
  1861. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1863. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1864. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1865. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1866. }
  1867. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1868. Request req;
  1869. req.set_header("X-Test", "only");
  1870. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1872. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1873. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1874. }
  1875. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1876. Request req;
  1877. req.set_header("X-First", "1");
  1878. req.set_header("X-Test", "2");
  1879. req.params.emplace("first", "1");
  1880. req.params.emplace("test", "2");
  1881. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1882. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1883. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1884. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1885. // The second one is negative when read as a signed value
  1886. const auto max_id = (std::numeric_limits<size_t>::max)();
  1887. for (auto id : {max_id / 2, max_id}) {
  1888. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1889. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1890. EXPECT_EQ("", req.get_param_value("test", id));
  1891. EXPECT_EQ("", req.form.get_field("test", id));
  1892. EXPECT_EQ("", req.form.get_file("test", id).content);
  1893. }
  1894. }
  1895. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1896. Headers headers;
  1897. headers.emplace("Host", "example.com");
  1898. headers.emplace("Accept-Encoding", "gzip");
  1899. headers.emplace("User-Agent", "test");
  1900. headers.emplace("Accept-Encoding", "deflate");
  1901. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1902. "Accept-Encoding=deflate ",
  1903. entries_to_string(headers));
  1904. }
  1905. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1906. Headers headers = {{"Content-Type", "text/html"},
  1907. {"CONTENT-TYPE", "text/xml"}};
  1908. EXPECT_EQ(2U, headers.count("content-type"));
  1909. auto it = headers.find("content-type");
  1910. ASSERT_TRUE(it != headers.end());
  1911. EXPECT_EQ("text/html", it->second);
  1912. }
  1913. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1914. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1915. // drop only those fields and leave everything positioned between them.
  1916. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1917. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1918. auto rng = headers.equal_range("a");
  1919. headers.erase(rng.first, rng.second);
  1920. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1921. }
  1922. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1923. Headers headers = {
  1924. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1925. EXPECT_EQ(3U, headers.erase("A"));
  1926. EXPECT_EQ(0U, headers.count("A"));
  1927. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1928. }
  1929. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1930. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1931. headers.emplace_front("Host", "example.com");
  1932. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1933. entries_to_string(headers));
  1934. }
  1935. TEST(ParseHeaderValueTest, Range) {
  1936. {
  1937. Ranges ranges;
  1938. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1939. EXPECT_TRUE(ret);
  1940. EXPECT_EQ(1u, ranges.size());
  1941. EXPECT_EQ(1u, ranges[0].first);
  1942. EXPECT_EQ(-1, ranges[0].second);
  1943. }
  1944. {
  1945. Ranges ranges;
  1946. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1947. EXPECT_TRUE(ret);
  1948. EXPECT_EQ(1u, ranges.size());
  1949. EXPECT_EQ(-1, ranges[0].first);
  1950. EXPECT_EQ(1u, ranges[0].second);
  1951. }
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ(1u, ranges.size());
  1957. EXPECT_EQ(1u, ranges[0].first);
  1958. EXPECT_EQ(10u, ranges[0].second);
  1959. }
  1960. {
  1961. Ranges ranges;
  1962. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1963. EXPECT_FALSE(ret);
  1964. }
  1965. {
  1966. Ranges ranges;
  1967. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1968. EXPECT_TRUE(ret);
  1969. EXPECT_EQ(2u, ranges.size());
  1970. EXPECT_EQ(1u, ranges[0].first);
  1971. EXPECT_EQ(10u, ranges[0].second);
  1972. EXPECT_EQ(100u, ranges[1].first);
  1973. EXPECT_EQ(-1, ranges[1].second);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret =
  1978. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1979. EXPECT_TRUE(ret);
  1980. EXPECT_EQ(3u, ranges.size());
  1981. EXPECT_EQ(1u, ranges[0].first);
  1982. EXPECT_EQ(10u, ranges[0].second);
  1983. EXPECT_EQ(100u, ranges[1].first);
  1984. EXPECT_EQ(200u, ranges[1].second);
  1985. EXPECT_EQ(300u, ranges[2].first);
  1986. EXPECT_EQ(400u, ranges[2].second);
  1987. }
  1988. {
  1989. Ranges ranges;
  1990. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2003. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2004. EXPECT_FALSE(
  2005. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2006. EXPECT_TRUE(ranges.empty());
  2007. }
  2008. {
  2009. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2010. // remainder of the representation, so it stays accepted.
  2011. Ranges ranges;
  2012. auto ret =
  2013. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2014. EXPECT_TRUE(ret);
  2015. ASSERT_EQ(1u, ranges.size());
  2016. EXPECT_EQ(0, ranges[0].first);
  2017. EXPECT_EQ(-1, ranges[0].second);
  2018. }
  2019. // RFC 9110 14.1: range unit names are case-insensitive.
  2020. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2021. Ranges ranges;
  2022. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2023. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2024. }
  2025. }
  2026. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2027. Request req;
  2028. req.set_header("Accept-Encoding", "gzip");
  2029. Response res;
  2030. res.set_header("Content-Type", "text/plain");
  2031. auto ret = detail::encoding_type(req, res);
  2032. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #else
  2035. EXPECT_TRUE(ret == detail::EncodingType::None);
  2036. #endif
  2037. }
  2038. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2039. Request req;
  2040. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2041. Response res;
  2042. res.set_header("Content-Type", "text/plain");
  2043. auto ret = detail::encoding_type(req, res);
  2044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2046. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2048. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2050. #else
  2051. EXPECT_TRUE(ret == detail::EncodingType::None);
  2052. #endif
  2053. }
  2054. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2055. Request req;
  2056. req.set_header("Accept-Encoding",
  2057. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2058. Response res;
  2059. res.set_header("Content-Type", "text/plain");
  2060. auto ret = detail::encoding_type(req, res);
  2061. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2063. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2065. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2072. // All supported encodings rejected with q=0 should return None
  2073. Request req;
  2074. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2075. Response res;
  2076. res.set_header("Content-Type", "text/plain");
  2077. auto ret = detail::encoding_type(req, res);
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. }
  2080. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2081. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2082. Request req;
  2083. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2084. Response res;
  2085. res.set_header("Content-Type", "text/plain");
  2086. auto ret = detail::encoding_type(req, res);
  2087. EXPECT_TRUE(ret == detail::EncodingType::None);
  2088. }
  2089. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2092. Response res;
  2093. res.set_header("Content-Type", "text/plain");
  2094. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2095. }
  2096. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2097. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2098. Request req;
  2099. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2100. Response res;
  2101. res.set_header("Content-Type", "text/plain");
  2102. auto ret = detail::encoding_type(req, res);
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. }
  2105. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2106. // RFC 7231: Accept-Encoding values are case-insensitive
  2107. Request req;
  2108. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2109. Response res;
  2110. res.set_header("Content-Type", "text/plain");
  2111. auto ret = detail::encoding_type(req, res);
  2112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2113. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2114. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2116. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2118. #else
  2119. EXPECT_TRUE(ret == detail::EncodingType::None);
  2120. #endif
  2121. }
  2122. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2123. // q value should determine priority, not hardcoded order
  2124. Request req;
  2125. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2126. Response res;
  2127. res.set_header("Content-Type", "text/plain");
  2128. auto ret = detail::encoding_type(req, res);
  2129. // gzip has highest q=1.0, so it should be selected even though
  2130. // br and zstd are also supported
  2131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2132. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2133. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2135. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2137. #else
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. #endif
  2140. }
  2141. TEST(BufferStreamTest, read) {
  2142. detail::BufferStream strm1;
  2143. Stream &strm = strm1;
  2144. EXPECT_EQ(5, strm.write("hello"));
  2145. char buf[512];
  2146. EXPECT_EQ(2, strm.read(buf, 2));
  2147. EXPECT_EQ('h', buf[0]);
  2148. EXPECT_EQ('e', buf[1]);
  2149. EXPECT_EQ(2, strm.read(buf, 2));
  2150. EXPECT_EQ('l', buf[0]);
  2151. EXPECT_EQ('l', buf[1]);
  2152. EXPECT_EQ(1, strm.read(buf, 1));
  2153. EXPECT_EQ('o', buf[0]);
  2154. EXPECT_EQ(0, strm.read(buf, 1));
  2155. }
  2156. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2157. auto host = "www.httpwatch.com";
  2158. auto ip = hosted_at(host);
  2159. EXPECT_EQ("23.96.13.243", ip);
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(1u, addrs.size());
  2163. }
  2164. #if 0 // It depends on each test environment...
  2165. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2166. auto host = "www.youtube.com";
  2167. std::vector<std::string> addrs;
  2168. hosted_at(host, addrs);
  2169. EXPECT_EQ(20u, addrs.size());
  2170. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2171. EXPECT_TRUE(it != addrs.end());
  2172. }
  2173. #endif
  2174. class ChunkedEncodingTest : public ::testing::Test {
  2175. protected:
  2176. ChunkedEncodingTest()
  2177. : cli_(HOST, PORT)
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. ,
  2180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2181. #endif
  2182. {
  2183. cli_.set_connection_timeout(2);
  2184. #ifdef CPPHTTPLIB_SSL_ENABLED
  2185. cli_.enable_server_certificate_verification(false);
  2186. #endif
  2187. }
  2188. virtual void SetUp() {
  2189. read_file("./image.jpg", image_data_);
  2190. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2191. res.set_content("Hello World!", "text/plain");
  2192. });
  2193. svr_.Get(
  2194. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2195. res.set_chunked_content_provider(
  2196. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2197. size_t remaining = image_data_.size() - offset;
  2198. if (remaining == 0) {
  2199. sink.done();
  2200. } else {
  2201. constexpr size_t CHUNK_SIZE = 1024;
  2202. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2203. sink.write(&image_data_[offset], send_size);
  2204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2205. }
  2206. return true;
  2207. });
  2208. });
  2209. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2210. svr_.wait_until_ready();
  2211. }
  2212. virtual void TearDown() {
  2213. svr_.stop();
  2214. if (!request_threads_.empty()) {
  2215. std::this_thread::sleep_for(std::chrono::seconds(1));
  2216. for (auto &t : request_threads_) {
  2217. t.join();
  2218. }
  2219. }
  2220. t_.join();
  2221. }
  2222. #ifdef CPPHTTPLIB_SSL_ENABLED
  2223. SSLClient cli_;
  2224. SSLServer svr_;
  2225. #else
  2226. Client cli_;
  2227. Server svr_;
  2228. #endif
  2229. thread t_;
  2230. std::vector<thread> request_threads_;
  2231. std::string image_data_;
  2232. };
  2233. TEST_F(ChunkedEncodingTest, NormalGet) {
  2234. auto res = cli_.Get("/chunked");
  2235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2236. std::string out;
  2237. read_file("./image.jpg", out);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. EXPECT_EQ(out, res->body);
  2240. }
  2241. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2242. std::string body;
  2243. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2244. body.append(data, data_length);
  2245. return true;
  2246. });
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. std::string out;
  2249. read_file("./image.jpg", out);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ(out, body);
  2252. }
  2253. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2254. std::string body;
  2255. auto res = cli_.Get(
  2256. "/chunked",
  2257. [&](const Response &response) {
  2258. EXPECT_EQ(StatusCode::OK_200, response.status);
  2259. return true;
  2260. },
  2261. [&](const char *data, size_t data_length) {
  2262. body.append(data, data_length);
  2263. return true;
  2264. });
  2265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2266. std::string out;
  2267. read_file("./image.jpg", out);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ(out, body);
  2270. }
  2271. TEST(RangeTest, FromHTTPBin_Online) {
  2272. auto host = "httpbingo.org";
  2273. auto path = std::string{"/range/32"};
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 443;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 80;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(5);
  2282. {
  2283. auto res = cli.Get(path);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::OK_200, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, -1}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. {
  2296. Headers headers = {make_range_header({{1, 10}})};
  2297. auto res = cli.Get(path, headers);
  2298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2299. EXPECT_EQ("bcdefghijk", res->body);
  2300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2301. }
  2302. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2303. // entire resource, while the original httpbin returned 200. Both are
  2304. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2305. {
  2306. Headers headers = {make_range_header({{0, 31}})};
  2307. auto res = cli.Get(path, headers);
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2310. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2311. res->status == StatusCode::PartialContent_206);
  2312. }
  2313. {
  2314. Headers headers = {make_range_header({{0, -1}})};
  2315. auto res = cli.Get(path, headers);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2318. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2319. res->status == StatusCode::PartialContent_206);
  2320. }
  2321. // go-httpbin returns 206 with clamped range for over-range requests,
  2322. // while the original httpbin returned 416. Both behaviors are observed
  2323. // in real servers, so we only verify the request succeeds.
  2324. {
  2325. Headers headers = {make_range_header({{0, 32}})};
  2326. auto res = cli.Get(path, headers);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. }
  2329. }
  2330. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2331. auto host = "unresolvableaddress.local";
  2332. auto path = std::string{"/"};
  2333. #ifdef CPPHTTPLIB_SSL_ENABLED
  2334. auto port = 443;
  2335. SSLClient cli(host, port);
  2336. #else
  2337. auto port = 80;
  2338. Client cli(host, port);
  2339. #endif
  2340. cli.set_connection_timeout(1);
  2341. {
  2342. auto res = cli.Get(path);
  2343. ASSERT_FALSE(res);
  2344. }
  2345. std::this_thread::sleep_for(std::chrono::seconds(8));
  2346. }
  2347. #if defined(__linux__) && defined(__GLIBC__) && \
  2348. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2349. // Forward declaration: in split builds split.py strips `inline` and moves the
  2350. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2351. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2352. // against the symbol in both header-only and split builds.
  2353. namespace httplib {
  2354. namespace detail {
  2355. int getaddrinfo_with_timeout(const char *node, const char *service,
  2356. const struct addrinfo *hints,
  2357. struct addrinfo **res, time_t timeout_sec);
  2358. } // namespace detail
  2359. } // namespace httplib
  2360. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2361. //
  2362. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2363. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2364. // gai_suspend() call hits the connection timeout the function calls
  2365. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2366. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2367. // still alive and still references the now-destroyed stack frame.
  2368. //
  2369. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2370. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2371. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2372. // and runs them in a container.
  2373. namespace {
  2374. bool should_run_issue_2431_tests() {
  2375. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2376. return v && *v && std::string(v) != "0";
  2377. }
  2378. std::string unique_unresolvable_host(int n) {
  2379. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2380. // glibc still asks the configured nameserver — which is exactly the path
  2381. // we want to exercise. A unique label per call avoids the resolver cache.
  2382. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2383. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2384. std::to_string(n) + ".invalid";
  2385. }
  2386. } // namespace
  2387. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2388. if (!should_run_issue_2431_tests()) {
  2389. GTEST_SKIP()
  2390. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2391. }
  2392. for (int i = 0; i < 8; ++i) {
  2393. struct addrinfo hints;
  2394. memset(&hints, 0, sizeof(hints));
  2395. hints.ai_family = AF_UNSPEC;
  2396. hints.ai_socktype = SOCK_STREAM;
  2397. auto host = unique_unresolvable_host(i);
  2398. struct addrinfo *result = nullptr;
  2399. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2400. &result, /*timeout_sec=*/1);
  2401. if (rc == 0 && result) { freeaddrinfo(result); }
  2402. }
  2403. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2404. // stack region they still believe holds their gaicb.
  2405. std::this_thread::sleep_for(std::chrono::seconds(3));
  2406. }
  2407. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2408. if (!should_run_issue_2431_tests()) {
  2409. GTEST_SKIP()
  2410. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2411. }
  2412. std::atomic<bool> stop{false};
  2413. std::vector<std::thread> threads;
  2414. for (int t = 0; t < 8; ++t) {
  2415. threads.emplace_back([t, &stop] {
  2416. int i = 0;
  2417. while (!stop.load(std::memory_order_relaxed)) {
  2418. struct addrinfo hints;
  2419. memset(&hints, 0, sizeof(hints));
  2420. hints.ai_family = AF_UNSPEC;
  2421. hints.ai_socktype = SOCK_STREAM;
  2422. auto host = unique_unresolvable_host(t * 100000 + i++);
  2423. struct addrinfo *result = nullptr;
  2424. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2425. &result, /*timeout_sec=*/1);
  2426. if (rc == 0 && result) { freeaddrinfo(result); }
  2427. }
  2428. });
  2429. }
  2430. std::this_thread::sleep_for(std::chrono::seconds(8));
  2431. stop.store(true, std::memory_order_relaxed);
  2432. for (auto &th : threads) {
  2433. th.join();
  2434. }
  2435. std::this_thread::sleep_for(std::chrono::seconds(3));
  2436. }
  2437. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2438. if (!should_run_issue_2431_tests()) {
  2439. GTEST_SKIP()
  2440. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2441. }
  2442. std::atomic<bool> stop{false};
  2443. std::vector<std::thread> threads;
  2444. for (int t = 0; t < 8; ++t) {
  2445. threads.emplace_back([t, &stop] {
  2446. int i = 0;
  2447. while (!stop.load(std::memory_order_relaxed)) {
  2448. auto host = unique_unresolvable_host(t * 100000 + i++);
  2449. Client cli(host, 80);
  2450. cli.set_connection_timeout(1, 0);
  2451. cli.set_read_timeout(1, 0);
  2452. cli.set_write_timeout(1, 0);
  2453. (void)cli.Get("/");
  2454. }
  2455. });
  2456. }
  2457. std::this_thread::sleep_for(std::chrono::seconds(8));
  2458. stop.store(true, std::memory_order_relaxed);
  2459. for (auto &th : threads) {
  2460. th.join();
  2461. }
  2462. std::this_thread::sleep_for(std::chrono::seconds(3));
  2463. }
  2464. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2465. TEST(ConnectionErrorTest, InvalidHost) {
  2466. auto host = "-abcde.com";
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. auto port = 443;
  2469. SSLClient cli(host, port);
  2470. #else
  2471. auto port = 80;
  2472. Client cli(host, port);
  2473. #endif
  2474. cli.set_connection_timeout(std::chrono::seconds(2));
  2475. auto res = cli.Get("/");
  2476. ASSERT_TRUE(!res);
  2477. EXPECT_EQ(Error::Connection, res.error());
  2478. }
  2479. TEST(ConnectionErrorTest, InvalidHost2) {
  2480. auto host = "httpcan.org/";
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. SSLClient cli(host);
  2483. #else
  2484. Client cli(host);
  2485. #endif
  2486. cli.set_connection_timeout(std::chrono::seconds(2));
  2487. auto res = cli.Get("/");
  2488. ASSERT_TRUE(!res);
  2489. EXPECT_EQ(Error::Connection, res.error());
  2490. }
  2491. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2492. auto host = "httpcan.org/";
  2493. #ifdef CPPHTTPLIB_SSL_ENABLED
  2494. SSLClient cli(host);
  2495. #else
  2496. Client cli(host);
  2497. #endif
  2498. cli.set_connection_timeout(std::chrono::seconds(2));
  2499. auto res = cli.Get("/");
  2500. ASSERT_TRUE(!res);
  2501. stringstream s;
  2502. s << "error code: " << res.error();
  2503. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2504. }
  2505. TEST(ConnectionErrorTest, InvalidPort) {
  2506. auto host = "localhost";
  2507. auto port = 44380;
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host, port);
  2510. #else
  2511. Client cli(host, port);
  2512. #endif
  2513. cli.set_connection_timeout(std::chrono::seconds(2));
  2514. auto res = cli.Get("/");
  2515. ASSERT_TRUE(!res);
  2516. EXPECT_TRUE(Error::Connection == res.error() ||
  2517. Error::ConnectionTimeout == res.error());
  2518. }
  2519. TEST(ConnectionErrorTest, Timeout_Online) {
  2520. auto host = "google.com";
  2521. #ifdef CPPHTTPLIB_SSL_ENABLED
  2522. auto port = 44380;
  2523. SSLClient cli(host, port);
  2524. #else
  2525. auto port = 8080;
  2526. Client cli(host, port);
  2527. #endif
  2528. cli.set_connection_timeout(std::chrono::seconds(2));
  2529. // only probe one address type so that the error reason
  2530. // correlates to the timed-out IPv4, not the unsupported
  2531. // IPv6 connection attempt
  2532. cli.set_address_family(AF_INET);
  2533. auto res = cli.Get("/");
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2536. }
  2537. TEST(CancelTest, NoCancel_Online) {
  2538. auto host = "httpbingo.org";
  2539. auto path = std::string{"/range/32"};
  2540. #ifdef CPPHTTPLIB_SSL_ENABLED
  2541. auto port = 443;
  2542. SSLClient cli(host, port);
  2543. #else
  2544. auto port = 80;
  2545. Client cli(host, port);
  2546. #endif
  2547. cli.set_connection_timeout(std::chrono::seconds(5));
  2548. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2550. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2551. EXPECT_EQ(StatusCode::OK_200, res->status);
  2552. }
  2553. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2554. // Use /bytes with a large payload so that the DownloadProgress callback
  2555. // (which only fires for Content-Length responses) is invoked before the
  2556. // entire body is received, giving cancellation a chance to fire.
  2557. auto host = "httpbingo.org";
  2558. auto path = std::string{"/bytes/524288"};
  2559. #ifdef CPPHTTPLIB_SSL_ENABLED
  2560. auto port = 443;
  2561. SSLClient cli(host, port);
  2562. #else
  2563. auto port = 80;
  2564. Client cli(host, port);
  2565. #endif
  2566. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. ASSERT_TRUE(!res);
  2569. EXPECT_EQ(Error::Canceled, res.error());
  2570. }
  2571. TEST(CancelTest, WithCancelLargePayload_Online) {
  2572. auto host = "httpbingo.org";
  2573. auto path = std::string{"/bytes/524288"};
  2574. #ifdef CPPHTTPLIB_SSL_ENABLED
  2575. auto port = 443;
  2576. SSLClient cli(host, port);
  2577. #else
  2578. auto port = 80;
  2579. Client cli(host, port);
  2580. #endif
  2581. cli.set_connection_timeout(std::chrono::seconds(5));
  2582. uint32_t count = 0;
  2583. auto res =
  2584. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2585. ASSERT_TRUE(!res);
  2586. EXPECT_EQ(Error::Canceled, res.error());
  2587. }
  2588. TEST(CancelTest, NoCancelPost) {
  2589. Server svr;
  2590. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2591. res.set_content("Hello World!", "text/plain");
  2592. });
  2593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2594. auto se = detail::scope_exit([&] {
  2595. svr.stop();
  2596. thread.join();
  2597. ASSERT_FALSE(svr.is_running());
  2598. });
  2599. svr.wait_until_ready();
  2600. Client cli(HOST, PORT);
  2601. cli.set_connection_timeout(std::chrono::seconds(5));
  2602. auto res =
  2603. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2604. "application/json", [](uint64_t, uint64_t) { return true; });
  2605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2606. EXPECT_EQ("Hello World!", res->body);
  2607. EXPECT_EQ(StatusCode::OK_200, res->status);
  2608. }
  2609. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2610. Server svr;
  2611. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2612. res.set_content("Hello World!", "text/plain");
  2613. });
  2614. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2615. auto se = detail::scope_exit([&] {
  2616. svr.stop();
  2617. thread.join();
  2618. ASSERT_FALSE(svr.is_running());
  2619. });
  2620. svr.wait_until_ready();
  2621. Client cli(HOST, PORT);
  2622. cli.set_connection_timeout(std::chrono::seconds(5));
  2623. auto res =
  2624. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2625. "application/json", [](uint64_t, uint64_t) { return false; });
  2626. ASSERT_TRUE(!res);
  2627. EXPECT_EQ(Error::Canceled, res.error());
  2628. }
  2629. TEST(CancelTest, WithCancelLargePayloadPost) {
  2630. Server svr;
  2631. svr.set_payload_max_length(200 * 1024 * 1024);
  2632. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2633. res.set_content(LARGE_DATA, "text/plain");
  2634. });
  2635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2636. auto se = detail::scope_exit([&] {
  2637. svr.stop();
  2638. thread.join();
  2639. ASSERT_FALSE(svr.is_running());
  2640. });
  2641. svr.wait_until_ready();
  2642. Client cli(HOST, PORT);
  2643. cli.set_payload_max_length(200 * 1024 * 1024);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, NoCancelPut) {
  2652. Server svr;
  2653. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2654. res.set_content("Hello World!", "text/plain");
  2655. });
  2656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2657. auto se = detail::scope_exit([&] {
  2658. svr.stop();
  2659. thread.join();
  2660. ASSERT_FALSE(svr.is_running());
  2661. });
  2662. svr.wait_until_ready();
  2663. Client cli(HOST, PORT);
  2664. cli.set_connection_timeout(std::chrono::seconds(5));
  2665. auto res =
  2666. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2667. "application/json", [](uint64_t, uint64_t) { return true; });
  2668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2669. EXPECT_EQ("Hello World!", res->body);
  2670. EXPECT_EQ(StatusCode::OK_200, res->status);
  2671. }
  2672. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2673. Server svr;
  2674. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2675. res.set_content("Hello World!", "text/plain");
  2676. });
  2677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2678. auto se = detail::scope_exit([&] {
  2679. svr.stop();
  2680. thread.join();
  2681. ASSERT_FALSE(svr.is_running());
  2682. });
  2683. svr.wait_until_ready();
  2684. Client cli(HOST, PORT);
  2685. cli.set_connection_timeout(std::chrono::seconds(5));
  2686. auto res =
  2687. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2688. "application/json", [](uint64_t, uint64_t) { return false; });
  2689. ASSERT_TRUE(!res);
  2690. EXPECT_EQ(Error::Canceled, res.error());
  2691. }
  2692. TEST(CancelTest, WithCancelLargePayloadPut) {
  2693. Server svr;
  2694. svr.set_payload_max_length(200 * 1024 * 1024);
  2695. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2696. res.set_content(LARGE_DATA, "text/plain");
  2697. });
  2698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2699. auto se = detail::scope_exit([&] {
  2700. svr.stop();
  2701. thread.join();
  2702. ASSERT_FALSE(svr.is_running());
  2703. });
  2704. svr.wait_until_ready();
  2705. Client cli(HOST, PORT);
  2706. cli.set_payload_max_length(200 * 1024 * 1024);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, NoCancelPatch) {
  2715. Server svr;
  2716. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2717. res.set_content("Hello World!", "text/plain");
  2718. });
  2719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2720. auto se = detail::scope_exit([&] {
  2721. svr.stop();
  2722. thread.join();
  2723. ASSERT_FALSE(svr.is_running());
  2724. });
  2725. svr.wait_until_ready();
  2726. Client cli(HOST, PORT);
  2727. cli.set_connection_timeout(std::chrono::seconds(5));
  2728. auto res =
  2729. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2730. "application/json", [](uint64_t, uint64_t) { return true; });
  2731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2732. EXPECT_EQ("Hello World!", res->body);
  2733. EXPECT_EQ(StatusCode::OK_200, res->status);
  2734. }
  2735. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2736. Server svr;
  2737. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2738. res.set_content("Hello World!", "text/plain");
  2739. });
  2740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2741. auto se = detail::scope_exit([&] {
  2742. svr.stop();
  2743. thread.join();
  2744. ASSERT_FALSE(svr.is_running());
  2745. });
  2746. svr.wait_until_ready();
  2747. Client cli(HOST, PORT);
  2748. cli.set_connection_timeout(std::chrono::seconds(5));
  2749. auto res =
  2750. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2751. "application/json", [](uint64_t, uint64_t) { return false; });
  2752. ASSERT_TRUE(!res);
  2753. EXPECT_EQ(Error::Canceled, res.error());
  2754. }
  2755. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2756. Server svr;
  2757. svr.set_payload_max_length(200 * 1024 * 1024);
  2758. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2759. res.set_content(LARGE_DATA, "text/plain");
  2760. });
  2761. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2762. auto se = detail::scope_exit([&] {
  2763. svr.stop();
  2764. thread.join();
  2765. ASSERT_FALSE(svr.is_running());
  2766. });
  2767. svr.wait_until_ready();
  2768. Client cli(HOST, PORT);
  2769. cli.set_payload_max_length(200 * 1024 * 1024);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, NoCancelDelete) {
  2778. Server svr;
  2779. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("Hello World!", "text/plain");
  2781. });
  2782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2783. auto se = detail::scope_exit([&] {
  2784. svr.stop();
  2785. thread.join();
  2786. ASSERT_FALSE(svr.is_running());
  2787. });
  2788. svr.wait_until_ready();
  2789. Client cli(HOST, PORT);
  2790. cli.set_connection_timeout(std::chrono::seconds(5));
  2791. auto res =
  2792. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2793. "application/json", [](uint64_t, uint64_t) { return true; });
  2794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2795. EXPECT_EQ("Hello World!", res->body);
  2796. EXPECT_EQ(StatusCode::OK_200, res->status);
  2797. }
  2798. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2799. Server svr;
  2800. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2801. res.set_content("Hello World!", "text/plain");
  2802. });
  2803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(HOST, PORT);
  2811. cli.set_connection_timeout(std::chrono::seconds(5));
  2812. auto res =
  2813. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2814. "application/json", [](uint64_t, uint64_t) { return false; });
  2815. ASSERT_TRUE(!res);
  2816. EXPECT_EQ(Error::Canceled, res.error());
  2817. }
  2818. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2819. Server svr;
  2820. svr.set_payload_max_length(200 * 1024 * 1024);
  2821. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2822. res.set_content(LARGE_DATA, "text/plain");
  2823. });
  2824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2825. auto se = detail::scope_exit([&] {
  2826. svr.stop();
  2827. thread.join();
  2828. ASSERT_FALSE(svr.is_running());
  2829. });
  2830. svr.wait_until_ready();
  2831. Client cli(HOST, PORT);
  2832. cli.set_payload_max_length(200 * 1024 * 1024);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. static std::string remove_whitespace(const std::string &input) {
  2841. std::string output;
  2842. output.reserve(input.size());
  2843. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2844. [](unsigned char c) { return !std::isspace(c); });
  2845. return output;
  2846. }
  2847. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2848. auto host = "httpbingo.org";
  2849. auto path = std::string{"/basic-auth/hello/world"};
  2850. #ifdef CPPHTTPLIB_SSL_ENABLED
  2851. auto port = 443;
  2852. SSLClient cli(host, port);
  2853. #else
  2854. auto port = 80;
  2855. Client cli(host, port);
  2856. #endif
  2857. {
  2858. auto res = cli.Get(path);
  2859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2860. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2861. }
  2862. {
  2863. auto res = cli.Get(
  2864. path, Headers{make_basic_authentication_header("hello", "world")});
  2865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2866. auto body = remove_whitespace(res->body);
  2867. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2868. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. {
  2872. cli.set_basic_auth("hello", "world");
  2873. auto res = cli.Get(path);
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. auto body = remove_whitespace(res->body);
  2876. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2877. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. {
  2881. cli.set_basic_auth("hello", "bad");
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2885. }
  2886. {
  2887. cli.set_basic_auth("bad", "world");
  2888. auto res = cli.Get(path);
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2891. }
  2892. }
  2893. #ifdef CPPHTTPLIB_SSL_ENABLED
  2894. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2895. auto host = "httpbingo.org";
  2896. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2897. auto paths = std::vector<std::string>{
  2898. "/digest-auth/auth/hello/world/MD5",
  2899. "/digest-auth/auth/hello/world/SHA-256",
  2900. };
  2901. auto port = 443;
  2902. SSLClient cli(host, port);
  2903. {
  2904. auto res = cli.Get(unauth_path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. {
  2909. cli.set_digest_auth("hello", "world");
  2910. for (const auto &path : paths) {
  2911. auto res = cli.Get(path.c_str());
  2912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2913. auto body = remove_whitespace(res->body);
  2914. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2915. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2916. EXPECT_EQ(StatusCode::OK_200, res->status);
  2917. }
  2918. cli.set_digest_auth("hello", "bad");
  2919. for (const auto &path : paths) {
  2920. auto res = cli.Get(path.c_str());
  2921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2922. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2923. }
  2924. }
  2925. }
  2926. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2927. // comma-separated list of challenges, and each challenge may itself carry a
  2928. // comma-separated auth-param list, so a server can legally offer Basic
  2929. // before Digest, either as two field lines or packed into one. Runs one 401
  2930. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2931. // value() joins them in receipt order) and checks that the retry carries a
  2932. // well-formed Digest Authorization header naming expected_realm.
  2933. static void
  2934. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2935. const std::string &expected_realm) {
  2936. std::atomic<int> hits{0};
  2937. Server svr;
  2938. svr.Get("/x", [&](const Request &req, Response &res) {
  2939. if (++hits == 1) {
  2940. res.status = StatusCode::Unauthorized_401;
  2941. for (const auto &challenge : challenges) {
  2942. res.set_header("WWW-Authenticate", challenge);
  2943. }
  2944. } else {
  2945. auto authorization = req.get_header_value("Authorization");
  2946. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2947. EXPECT_NE(std::string::npos,
  2948. authorization.find("realm=\"" + expected_realm + "\""));
  2949. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2950. res.set_content("ok", "text/plain");
  2951. }
  2952. });
  2953. auto port = svr.bind_to_any_port(HOST);
  2954. std::thread t([&]() { svr.listen_after_bind(); });
  2955. auto se = detail::scope_exit([&] {
  2956. svr.stop();
  2957. t.join();
  2958. });
  2959. svr.wait_until_ready();
  2960. Client cli(HOST, port);
  2961. cli.set_digest_auth("hello", "world");
  2962. auto res = cli.Get("/x");
  2963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2964. EXPECT_EQ(2, hits.load());
  2965. }
  2966. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2967. static const char *kDigestChallenge =
  2968. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2969. "algorithm=MD5";
  2970. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2971. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2972. "testrealm");
  2973. }
  2974. // Same challenge list with the schemes in the opposite order, to make sure
  2975. // the fix above didn't just special-case "Basic first".
  2976. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2977. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2978. "testrealm");
  2979. }
  2980. // A comma inside a quoted auth-param value must not be mistaken for the
  2981. // separator between two challenges (or two auth-params).
  2982. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2983. run_digest_challenge_list_test(
  2984. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2985. "algorithm=MD5"},
  2986. "test,realm");
  2987. }
  2988. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2989. // the params and leaves out the fragment.
  2990. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2991. Server svr;
  2992. std::string uri, target;
  2993. svr.Get("/a b", [&](const Request &req, Response &res) {
  2994. auto auth = req.get_header_value("Authorization");
  2995. if (auth.empty()) {
  2996. res.status = StatusCode::Unauthorized_401;
  2997. res.set_header("WWW-Authenticate",
  2998. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2999. return;
  3000. }
  3001. auto b = auth.find("uri=\"") + 5;
  3002. uri = auth.substr(b, auth.find('"', b) - b);
  3003. target = req.target;
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ("/a%20b?x=1", target);
  3017. EXPECT_EQ(target, uri);
  3018. }
  3019. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3020. // make_digest_authentication_header() dereferences both unconditionally, so
  3021. // a server sending a challenge missing either one must not be treated as
  3022. // usable -- doing so used to crash the client with std::out_of_range.
  3023. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3024. Server svr;
  3025. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3026. res.status = StatusCode::Unauthorized_401;
  3027. res.set_header("WWW-Authenticate", challenge);
  3028. });
  3029. auto port = svr.bind_to_any_port(HOST);
  3030. std::thread t([&]() { svr.listen_after_bind(); });
  3031. auto se = detail::scope_exit([&] {
  3032. svr.stop();
  3033. t.join();
  3034. });
  3035. svr.wait_until_ready();
  3036. Client cli(HOST, port);
  3037. cli.set_digest_auth("hello", "world");
  3038. auto res = cli.Get("/x");
  3039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3040. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3041. }
  3042. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3043. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3044. }
  3045. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3046. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3047. }
  3048. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3049. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3050. }
  3051. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3052. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3053. // when storing the values, so the header builder has to re-escape them (and
  3054. // keep algorithm a bare token); otherwise the value breaks out of its
  3055. // quoted-string and injects extra auth-params into the client's Authorization.
  3056. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3057. std::atomic<int> hits{0};
  3058. std::string authorization;
  3059. Server svr;
  3060. svr.Get("/x", [&](const Request &req, Response &res) {
  3061. if (++hits == 1) {
  3062. res.status = StatusCode::Unauthorized_401;
  3063. // On the wire the quotes embedded in the values are backslash-escaped.
  3064. res.set_header("WWW-Authenticate",
  3065. "Digest realm=\"testrealm\", "
  3066. "nonce=\"n\\\"; injected=\\\"x\", "
  3067. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3068. } else {
  3069. authorization = req.get_header_value("Authorization");
  3070. res.set_content("ok", "text/plain");
  3071. }
  3072. });
  3073. auto port = svr.bind_to_any_port(HOST);
  3074. std::thread t([&]() { svr.listen_after_bind(); });
  3075. auto se = detail::scope_exit([&] {
  3076. svr.stop();
  3077. t.join();
  3078. });
  3079. svr.wait_until_ready();
  3080. Client cli(HOST, port);
  3081. cli.set_digest_auth("hello", "world");
  3082. auto res = cli.Get("/x");
  3083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3084. EXPECT_EQ(2, hits.load());
  3085. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3086. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3087. // inside its quoted-string rather than starting an "injected" auth-param.
  3088. EXPECT_NE(std::string::npos,
  3089. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3090. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3091. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3092. }
  3093. #endif
  3094. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3095. auto host = "google.com";
  3096. auto another_host = "example.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3106. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3109. auto host = "google.com";
  3110. auto wrong_ip = "0.0.0.0";
  3111. #ifdef CPPHTTPLIB_SSL_ENABLED
  3112. SSLClient cli(host);
  3113. #else
  3114. Client cli(host);
  3115. #endif
  3116. cli.set_hostname_addr_map({{host, wrong_ip}});
  3117. auto res = cli.Get("/");
  3118. ASSERT_TRUE(!res);
  3119. EXPECT_EQ(Error::Connection, res.error());
  3120. }
  3121. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3122. // A mapped value that is not an IP literal must be resolved. "localhost"
  3123. // resolves from the hosts file, so this test needs no external DNS.
  3124. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3125. auto host = "target.invalid";
  3126. Server svr;
  3127. std::string received_host;
  3128. svr.Get("/hi", [&](const Request &req, Response &res) {
  3129. received_host = req.get_header_value("Host");
  3130. res.set_content("Hello World!", "text/plain");
  3131. });
  3132. auto port = svr.bind_to_any_port(HOST);
  3133. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3134. auto se = detail::scope_exit([&] {
  3135. svr.stop();
  3136. thread.join();
  3137. ASSERT_FALSE(svr.is_running());
  3138. });
  3139. svr.wait_until_ready();
  3140. Client cli(host, port);
  3141. cli.set_hostname_addr_map({{host, HOST}});
  3142. auto res = cli.Get("/hi");
  3143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3144. EXPECT_EQ(StatusCode::OK_200, res->status);
  3145. // The mapping only redirects the connection; the identity stays host_.
  3146. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3147. }
  3148. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3149. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3150. auto host = "target.invalid";
  3151. Server svr;
  3152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3153. res.set_content("Hello World!", "text/plain");
  3154. });
  3155. auto port = svr.bind_to_any_port("127.0.0.1");
  3156. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3157. auto se = detail::scope_exit([&] {
  3158. svr.stop();
  3159. thread.join();
  3160. ASSERT_FALSE(svr.is_running());
  3161. });
  3162. svr.wait_until_ready();
  3163. Client cli(host, port);
  3164. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3165. auto res = cli.Get("/hi");
  3166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. }
  3169. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3170. // An empty mapped value must leave host_ as the connection target. Without
  3171. // that guard the empty value would become the host argument, getaddrinfo
  3172. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3173. // loopback - silently connecting somewhere the caller never asked for.
  3174. // The server listens on loopback, so such a fallback would succeed and is
  3175. // therefore observable as a failure of this test.
  3176. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3177. Server svr;
  3178. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3179. res.set_content("Hello World!", "text/plain");
  3180. });
  3181. auto port = svr.bind_to_any_port(HOST);
  3182. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3183. auto se = detail::scope_exit([&] {
  3184. svr.stop();
  3185. thread.join();
  3186. ASSERT_FALSE(svr.is_running());
  3187. });
  3188. svr.wait_until_ready();
  3189. Client cli(blackhole, port);
  3190. cli.set_hostname_addr_map({{blackhole, ""}});
  3191. cli.set_connection_timeout(1);
  3192. auto res = cli.Get("/hi");
  3193. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3194. }
  3195. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/absolute-redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(RelativeRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/relative-redirect/3"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3232. EXPECT_EQ(StatusCode::OK_200, res->status);
  3233. }
  3234. TEST(TooManyRedirectTest, Redirect_Online) {
  3235. auto host = "httpbingo.org";
  3236. auto path = std::string{"/redirect/21"};
  3237. #ifdef CPPHTTPLIB_SSL_ENABLED
  3238. SSLClient cli(host);
  3239. #else
  3240. Client cli(host);
  3241. #endif
  3242. cli.set_follow_location(true);
  3243. auto res = cli.Get(path);
  3244. ASSERT_TRUE(!res);
  3245. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3246. }
  3247. #ifdef CPPHTTPLIB_SSL_ENABLED
  3248. TEST(YahooRedirectTest, Redirect_Online) {
  3249. Client cli("yahoo.com");
  3250. auto res = cli.Get("/");
  3251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3252. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3253. cli.set_follow_location(true);
  3254. res = cli.Get("/");
  3255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3256. EXPECT_EQ(StatusCode::OK_200, res->status);
  3257. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3258. }
  3259. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3260. #define REDIR_HOST "httpbingo.org"
  3261. #define REDIR_PATH "/redirect-to"
  3262. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3263. SSLClient cli(REDIR_HOST);
  3264. cli.set_follow_location(true);
  3265. auto res =
  3266. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3268. EXPECT_EQ(StatusCode::OK_200, res->status);
  3269. }
  3270. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3271. SSLClient cli(REDIR_HOST);
  3272. cli.set_follow_location(true);
  3273. Params params;
  3274. params.emplace("url", "http://example.com");
  3275. params.emplace("status_code", "302");
  3276. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. }
  3280. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3281. SSLClient cli(REDIR_HOST);
  3282. cli.set_follow_location(true);
  3283. Params params;
  3284. params.emplace("url", "http://example.com");
  3285. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. TEST(UrlWithSpace, Redirect_Online) {
  3290. SSLClient cli("edge.forgecdn.net");
  3291. cli.set_follow_location(true);
  3292. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. EXPECT_EQ(StatusCode::OK_200, res->status);
  3295. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3296. }
  3297. #endif
  3298. #if !defined(_WIN32) && !defined(_WIN64)
  3299. TEST(ReceiveSignals, Signal) {
  3300. auto setupSignalHandlers = []() {
  3301. struct sigaction act;
  3302. sigemptyset(&act.sa_mask);
  3303. act.sa_flags = SA_SIGINFO;
  3304. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3305. switch (sig) {
  3306. case SIGINT:
  3307. default: break;
  3308. }
  3309. };
  3310. ::sigaction(SIGINT, &act, nullptr);
  3311. };
  3312. Server svr;
  3313. int port = 0;
  3314. auto thread = std::thread([&]() {
  3315. setupSignalHandlers();
  3316. port = svr.bind_to_any_port(HOST);
  3317. svr.listen_after_bind();
  3318. });
  3319. auto se = detail::scope_exit([&] {
  3320. svr.stop();
  3321. thread.join();
  3322. ASSERT_FALSE(svr.is_running());
  3323. });
  3324. svr.wait_until_ready();
  3325. ASSERT_TRUE(svr.is_running());
  3326. pthread_kill(thread.native_handle(), SIGINT);
  3327. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3328. ASSERT_TRUE(svr.is_running());
  3329. }
  3330. #endif
  3331. TEST(RedirectToDifferentPort, Redirect) {
  3332. Server svr1;
  3333. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3334. res.set_content("Hello World!", "text/plain");
  3335. });
  3336. int svr1_port = 0;
  3337. auto thread1 = std::thread([&]() {
  3338. svr1_port = svr1.bind_to_any_port(HOST);
  3339. svr1.listen_after_bind();
  3340. });
  3341. Server svr2;
  3342. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3343. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3344. });
  3345. int svr2_port = 0;
  3346. auto thread2 = std::thread([&]() {
  3347. svr2_port = svr2.bind_to_any_port(HOST);
  3348. svr2.listen_after_bind();
  3349. });
  3350. auto se = detail::scope_exit([&] {
  3351. svr2.stop();
  3352. thread2.join();
  3353. svr1.stop();
  3354. thread1.join();
  3355. ASSERT_FALSE(svr2.is_running());
  3356. ASSERT_FALSE(svr1.is_running());
  3357. });
  3358. svr1.wait_until_ready();
  3359. svr2.wait_until_ready();
  3360. Client cli("localhost", svr2_port);
  3361. cli.set_follow_location(true);
  3362. auto res = cli.Get("/2");
  3363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3364. EXPECT_EQ(StatusCode::OK_200, res->status);
  3365. EXPECT_EQ("Hello World!", res->body);
  3366. }
  3367. // GET /redir on one server redirects to /target on another port, so the
  3368. // client follows it with a new client.
  3369. static Result
  3370. GetThroughRedirectToDifferentPort(Server::Handler target,
  3371. const std::function<void(Client &)> &setup,
  3372. const Headers &headers = Headers()) {
  3373. Server target_svr;
  3374. target_svr.Get("/target", target);
  3375. int target_port = 0;
  3376. auto target_thread = std::thread([&]() {
  3377. target_port = target_svr.bind_to_any_port(HOST);
  3378. target_svr.listen_after_bind();
  3379. });
  3380. Server origin_svr;
  3381. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3382. res.set_redirect(
  3383. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3384. });
  3385. int origin_port = 0;
  3386. auto origin_thread = std::thread([&]() {
  3387. origin_port = origin_svr.bind_to_any_port(HOST);
  3388. origin_svr.listen_after_bind();
  3389. });
  3390. auto se = detail::scope_exit([&] {
  3391. origin_svr.stop();
  3392. origin_thread.join();
  3393. target_svr.stop();
  3394. target_thread.join();
  3395. });
  3396. target_svr.wait_until_ready();
  3397. origin_svr.wait_until_ready();
  3398. Client cli("localhost", origin_port);
  3399. cli.set_follow_location(true);
  3400. setup(cli);
  3401. return cli.Get("/redir", headers);
  3402. }
  3403. static void
  3404. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3405. std::string captured_authorization;
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [&](const Request &req, Response &res) {
  3408. captured_authorization = req.get_header_value("Authorization");
  3409. res.set_content("OK", "text/plain");
  3410. },
  3411. set_auth);
  3412. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3413. EXPECT_EQ(StatusCode::OK_200, result->status);
  3414. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3415. EXPECT_TRUE(captured_authorization.empty());
  3416. }
  3417. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3418. TestDoNotForwardCredentialsOnRedirect(
  3419. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3420. }
  3421. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3422. TestDoNotForwardCredentialsOnRedirect(
  3423. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3424. }
  3425. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3426. std::string captured_cookie;
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [&](const Request &req, Response &res) {
  3429. captured_cookie = req.get_header_value("Cookie");
  3430. res.set_content("OK", "text/plain");
  3431. },
  3432. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3433. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3434. EXPECT_EQ(StatusCode::OK_200, result->status);
  3435. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3436. EXPECT_TRUE(captured_cookie.empty());
  3437. }
  3438. TEST(RedirectToSamePort, ForwardCookie) {
  3439. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3440. // header so that ordinary session flows keep working.
  3441. Server svr;
  3442. std::string captured_cookie;
  3443. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3444. res.set_redirect("/target", 302);
  3445. });
  3446. svr.Get("/target", [&](const Request &req, Response &res) {
  3447. captured_cookie = req.get_header_value("Cookie");
  3448. res.set_content("OK", "text/plain");
  3449. });
  3450. auto port = svr.bind_to_any_port(HOST);
  3451. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3452. auto se = detail::scope_exit([&] {
  3453. svr.stop();
  3454. thread.join();
  3455. ASSERT_FALSE(svr.is_running());
  3456. });
  3457. svr.wait_until_ready();
  3458. Client cli(HOST, port);
  3459. cli.set_follow_location(true);
  3460. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3461. auto res = cli.Get("/redir", headers);
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::OK_200, res->status);
  3464. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3465. }
  3466. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3467. std::string authorization;
  3468. std::string trace_id;
  3469. auto result = GetThroughRedirectToDifferentPort(
  3470. [&](const Request &req, Response &res) {
  3471. authorization = req.get_header_value("Authorization");
  3472. trace_id = req.get_header_value("X-Trace-Id");
  3473. res.set_content("OK", "text/plain");
  3474. },
  3475. [](Client &cli) {
  3476. cli.set_default_headers(
  3477. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3478. });
  3479. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3480. EXPECT_EQ(StatusCode::OK_200, result->status);
  3481. // Like a header given with the request, a default one goes along unless it
  3482. // carries credentials (RFC 9110 15.4).
  3483. EXPECT_TRUE(authorization.empty());
  3484. EXPECT_EQ("42", trace_id);
  3485. }
  3486. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3487. auto result = GetThroughRedirectToDifferentPort(
  3488. [](const Request &, Response &res) {
  3489. res.set_content(std::string(2048, 'x'), "text/plain");
  3490. },
  3491. [](Client &cli) { cli.set_payload_max_length(1024); });
  3492. EXPECT_FALSE(result);
  3493. }
  3494. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3495. auto result = GetThroughRedirectToDifferentPort(
  3496. [](const Request &req, Response &res) {
  3497. // Answer after a second, or once the client gives up.
  3498. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3499. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3500. }
  3501. res.set_content("late", "text/plain");
  3502. },
  3503. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3504. ASSERT_FALSE(result);
  3505. EXPECT_EQ(Error::Read, result.error());
  3506. }
  3507. #ifdef CPPHTTPLIB_SSL_ENABLED
  3508. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3509. auto result = GetThroughRedirectToDifferentPort(
  3510. [](const Request &, Response &res) {
  3511. res.status = StatusCode::Unauthorized_401;
  3512. res.set_header("WWW-Authenticate",
  3513. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3514. },
  3515. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3516. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3517. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3518. }
  3519. #endif
  3520. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3521. Server svr;
  3522. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3523. // Port number that overflows int — should not crash
  3524. res.set_redirect("http://localhost:99999999999999999999/target");
  3525. });
  3526. auto port = svr.bind_to_any_port(HOST);
  3527. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3528. auto se = detail::scope_exit([&] {
  3529. svr.stop();
  3530. thread.join();
  3531. ASSERT_FALSE(svr.is_running());
  3532. });
  3533. svr.wait_until_ready();
  3534. Client cli(HOST, port);
  3535. cli.set_follow_location(true);
  3536. auto res = cli.Get("/redir");
  3537. // Should fail gracefully, not crash (no valid response due to bad port)
  3538. EXPECT_FALSE(res);
  3539. }
  3540. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3541. Server svr;
  3542. auto port = svr.bind_to_any_port(HOST);
  3543. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3544. // The server's own port followed by junk must not be followed
  3545. res.set_redirect("http://" + std::string(HOST) + ":" +
  3546. std::to_string(port) + "junk/target");
  3547. });
  3548. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3549. res.set_content("target", "text/plain");
  3550. });
  3551. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. thread.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. svr.wait_until_ready();
  3558. Client cli(HOST, port);
  3559. cli.set_follow_location(true);
  3560. auto res = cli.Get("/redir");
  3561. EXPECT_FALSE(res);
  3562. }
  3563. TEST(RedirectFromPageWithContent, Redirect) {
  3564. Server svr;
  3565. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3566. res.set_content("___", "text/plain");
  3567. res.set_redirect("/2");
  3568. });
  3569. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3570. res.set_content("Hello World!", "text/plain");
  3571. });
  3572. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3573. auto se = detail::scope_exit([&] {
  3574. svr.stop();
  3575. th.join();
  3576. ASSERT_FALSE(svr.is_running());
  3577. });
  3578. svr.wait_until_ready();
  3579. {
  3580. Client cli("localhost", PORT);
  3581. cli.set_follow_location(true);
  3582. std::string body;
  3583. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3584. body.append(data, data_length);
  3585. return true;
  3586. });
  3587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3588. EXPECT_EQ(StatusCode::OK_200, res->status);
  3589. EXPECT_EQ("Hello World!", body);
  3590. }
  3591. {
  3592. Client cli("localhost", PORT);
  3593. std::string body;
  3594. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3595. body.append(data, data_length);
  3596. return true;
  3597. });
  3598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3599. EXPECT_EQ(StatusCode::Found_302, res->status);
  3600. EXPECT_EQ("___", body);
  3601. }
  3602. }
  3603. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3604. Server svr;
  3605. auto port_str = std::to_string(PORT);
  3606. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3607. auto expected_host = "[::1]:" + port_str;
  3608. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3609. res.set_content("___", "text/plain");
  3610. // res.set_redirect("/2");
  3611. res.set_redirect(redirect_url);
  3612. });
  3613. svr.Get("/2", [&](const Request &req, Response &res) {
  3614. auto host_header = req.headers.find("Host");
  3615. ASSERT_TRUE(host_header != req.headers.end());
  3616. EXPECT_EQ(expected_host, host_header->second);
  3617. res.set_content("Hello World!", "text/plain");
  3618. });
  3619. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. th.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3626. // actually starts anything, so the condition !svr.is_running() will
  3627. // always remain true, and the loop never stops.
  3628. // This basically counts how many milliseconds have passed since the
  3629. // call to svr.listen(), and if after 5 seconds nothing started yet
  3630. // aborts the test.
  3631. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3632. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3633. ASSERT_LT(milliseconds, 5000U);
  3634. }
  3635. {
  3636. Client cli("::1", PORT);
  3637. cli.set_follow_location(true);
  3638. std::string body;
  3639. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3640. body.append(data, data_length);
  3641. return true;
  3642. });
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::OK_200, res->status);
  3645. EXPECT_EQ("Hello World!", body);
  3646. }
  3647. {
  3648. Client cli("::1", PORT);
  3649. std::string body;
  3650. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3651. body.append(data, data_length);
  3652. return true;
  3653. });
  3654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3655. EXPECT_EQ(StatusCode::Found_302, res->status);
  3656. EXPECT_EQ("___", body);
  3657. }
  3658. }
  3659. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3660. Server svr;
  3661. svr.Get("/foo", [](const Request &req, Response &res) {
  3662. auto a = req.params.find("a");
  3663. if (a != req.params.end()) {
  3664. res.set_content((*a).second, "text/plain");
  3665. res.status = StatusCode::OK_200;
  3666. } else {
  3667. res.status = StatusCode::BadRequest_400;
  3668. }
  3669. });
  3670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3671. auto se = detail::scope_exit([&] {
  3672. svr.stop();
  3673. thread.join();
  3674. ASSERT_FALSE(svr.is_running());
  3675. });
  3676. svr.wait_until_ready();
  3677. {
  3678. Client cli(HOST, PORT);
  3679. cli.set_path_encode(false);
  3680. auto res = cli.Get("/foo?a=explicitly+encoded");
  3681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3682. EXPECT_EQ(StatusCode::OK_200, res->status);
  3683. // This expects it back with a space, as the `+` won't have been
  3684. // url-encoded, and server-side the params get decoded turning `+`
  3685. // into spaces.
  3686. EXPECT_EQ("explicitly encoded", res->body);
  3687. }
  3688. }
  3689. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3690. // When path encoding is disabled the client must transmit the supplied
  3691. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3692. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3693. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3694. // than a space (0x20). Assert on the raw wire target to catch this.
  3695. Server svr;
  3696. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3697. svr.Get("/foo", [&](const Request &req, Response &res) {
  3698. EXPECT_EQ(expected_target, req.target);
  3699. res.status = StatusCode::OK_200;
  3700. });
  3701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3702. auto se = detail::scope_exit([&] {
  3703. svr.stop();
  3704. thread.join();
  3705. ASSERT_FALSE(svr.is_running());
  3706. });
  3707. svr.wait_until_ready();
  3708. {
  3709. Client cli(HOST, PORT);
  3710. cli.set_path_encode(false);
  3711. auto res = cli.Get(expected_target.c_str());
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. }
  3715. }
  3716. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3717. // `open_stream()` used to skip the path encoding that the buffered send
  3718. // path applies, so the same `path` produced different bytes in the request
  3719. // line depending on which API was used. Assert the two agree.
  3720. Server svr;
  3721. std::string target;
  3722. svr.Get(".*", [&](const Request &req, Response &res) {
  3723. target = req.target;
  3724. res.status = StatusCode::OK_200;
  3725. });
  3726. auto port = svr.bind_to_any_port(HOST);
  3727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3728. auto se = detail::scope_exit([&] {
  3729. svr.stop();
  3730. thread.join();
  3731. ASSERT_FALSE(svr.is_running());
  3732. });
  3733. svr.wait_until_ready();
  3734. struct {
  3735. const char *path;
  3736. const char *expected;
  3737. } cases[] = {
  3738. {"/a b?x=1", "/a%20b?x=1"},
  3739. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3740. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3741. };
  3742. for (const auto &c : cases) {
  3743. Client cli(HOST, port);
  3744. target.clear();
  3745. auto res = cli.Get(c.path);
  3746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3747. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3748. auto buffered_target = target;
  3749. target.clear();
  3750. auto handle = cli.open_stream("GET", c.path);
  3751. EXPECT_TRUE(handle.is_valid())
  3752. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3753. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3754. }
  3755. }
  3756. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3757. // The `set_path_encode(false)` contract — transmit the supplied target
  3758. // verbatim — must hold for the streaming API too.
  3759. Server svr;
  3760. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3761. std::string target;
  3762. svr.Get("/foo", [&](const Request &req, Response &res) {
  3763. target = req.target;
  3764. res.status = StatusCode::OK_200;
  3765. });
  3766. auto port = svr.bind_to_any_port(HOST);
  3767. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3768. auto se = detail::scope_exit([&] {
  3769. svr.stop();
  3770. thread.join();
  3771. ASSERT_FALSE(svr.is_running());
  3772. });
  3773. svr.wait_until_ready();
  3774. {
  3775. Client cli(HOST, port);
  3776. cli.set_path_encode(false);
  3777. auto handle = cli.open_stream("GET", expected_target);
  3778. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3779. EXPECT_EQ(expected_target, target);
  3780. }
  3781. }
  3782. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3783. // With path encoding enabled a CR/LF in the target is percent-encoded
  3784. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3785. // write_request_line still backstops `set_path_encode(false)`, which is
  3786. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3787. Server svr;
  3788. // Captured before routing: the decoded path contains a newline, which a
  3789. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3790. std::string target;
  3791. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3792. target = req.target;
  3793. res.status = StatusCode::OK_200;
  3794. return Server::HandlerResponse::Handled;
  3795. });
  3796. auto port = svr.bind_to_any_port(HOST);
  3797. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3798. auto se = detail::scope_exit([&] {
  3799. svr.stop();
  3800. thread.join();
  3801. ASSERT_FALSE(svr.is_running());
  3802. });
  3803. svr.wait_until_ready();
  3804. {
  3805. Client cli(HOST, port);
  3806. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3807. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3808. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3809. }
  3810. }
  3811. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3812. // Every control character is percent-encoded, not just CR/LF, so the target
  3813. // passes the request-target check in write_request_line.
  3814. Server svr;
  3815. std::string target;
  3816. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3817. target = req.target;
  3818. res.status = StatusCode::OK_200;
  3819. return Server::HandlerResponse::Handled;
  3820. });
  3821. auto port = svr.bind_to_any_port(HOST);
  3822. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3823. auto se = detail::scope_exit([&] {
  3824. svr.stop();
  3825. thread.join();
  3826. ASSERT_FALSE(svr.is_running());
  3827. });
  3828. svr.wait_until_ready();
  3829. {
  3830. Client cli(HOST, port);
  3831. auto res = cli.Get("/a\tb\x1b\x7f");
  3832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3833. EXPECT_EQ("/a%09b%1B%7F", target);
  3834. }
  3835. }
  3836. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3837. // Nothing may reach the wire: a raw CR/LF target would split the request
  3838. // line and inject headers.
  3839. Server svr;
  3840. // Pre-routing so that "not called" means nothing reached the server at all,
  3841. // rather than merely failing to match a handler pattern.
  3842. auto handler_called = false;
  3843. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3844. handler_called = true;
  3845. res.status = StatusCode::OK_200;
  3846. return Server::HandlerResponse::Handled;
  3847. });
  3848. auto port = svr.bind_to_any_port(HOST);
  3849. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3850. auto se = detail::scope_exit([&] {
  3851. svr.stop();
  3852. thread.join();
  3853. ASSERT_FALSE(svr.is_running());
  3854. });
  3855. svr.wait_until_ready();
  3856. {
  3857. Client cli(HOST, port);
  3858. cli.set_path_encode(false);
  3859. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3860. EXPECT_FALSE(handle.is_valid());
  3861. EXPECT_EQ(Error::Write, handle.error);
  3862. EXPECT_FALSE(handler_called);
  3863. }
  3864. }
  3865. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3866. // Which of the two branches runs is decided by whether the query component
  3867. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3868. // an empty query and must still fall back to building one from
  3869. // `req.params`, while a non-empty query must win over `req.params`.
  3870. Server svr;
  3871. std::string target;
  3872. svr.Get("/foo", [&](const Request &req, Response &res) {
  3873. target = req.target;
  3874. res.status = StatusCode::OK_200;
  3875. });
  3876. auto port = svr.bind_to_any_port(HOST);
  3877. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3878. auto se = detail::scope_exit([&] {
  3879. svr.stop();
  3880. thread.join();
  3881. ASSERT_FALSE(svr.is_running());
  3882. });
  3883. svr.wait_until_ready();
  3884. {
  3885. // Trailing `?` -> empty query component -> `req.params` is used.
  3886. Client cli(HOST, port);
  3887. Request req;
  3888. req.method = "GET";
  3889. req.path = "/foo?";
  3890. req.params.emplace("a", "1");
  3891. target.clear();
  3892. auto res = cli.send(req);
  3893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3894. EXPECT_EQ("/foo?a=1", target);
  3895. }
  3896. {
  3897. // Non-empty query in `req.path` -> `req.params` is not appended.
  3898. Client cli(HOST, port);
  3899. Request req;
  3900. req.method = "GET";
  3901. req.path = "/foo?b=2";
  3902. req.params.emplace("a", "1");
  3903. target.clear();
  3904. auto res = cli.send(req);
  3905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3906. EXPECT_EQ("/foo?b=2", target);
  3907. }
  3908. }
  3909. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3910. Server svr;
  3911. svr.Get("/", [](const Request &req, Response &) {
  3912. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3913. });
  3914. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3915. auto se = detail::scope_exit([&] {
  3916. svr.stop();
  3917. thread.join();
  3918. ASSERT_FALSE(svr.is_running());
  3919. });
  3920. svr.wait_until_ready();
  3921. {
  3922. Client cli(HOST, PORT);
  3923. cli.set_path_encode(false);
  3924. auto res = cli.Get("/?something=%0A");
  3925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3926. EXPECT_EQ(StatusCode::OK_200, res->status);
  3927. }
  3928. }
  3929. TEST(BindServerTest, BindDualStack) {
  3930. Server svr;
  3931. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3932. res.set_content("Hello World!", "text/plain");
  3933. });
  3934. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3935. auto se = detail::scope_exit([&] {
  3936. svr.stop();
  3937. thread.join();
  3938. ASSERT_FALSE(svr.is_running());
  3939. });
  3940. svr.wait_until_ready();
  3941. {
  3942. Client cli("127.0.0.1", PORT);
  3943. auto res = cli.Get("/1");
  3944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ("Hello World!", res->body);
  3947. }
  3948. {
  3949. Client cli("::1", PORT);
  3950. auto res = cli.Get("/1");
  3951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. EXPECT_EQ("Hello World!", res->body);
  3954. }
  3955. }
  3956. TEST(BindServerTest, BindAndListenSeparately) {
  3957. Server svr;
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. svr.stop();
  3962. }
  3963. // Reports whether anything is still listening on a loopback port. A plain
  3964. // connect() is used instead of a Client request because a socket left bound by
  3965. // mistake accepts the connection into its backlog and never answers, which
  3966. // would hang the test instead of failing it.
  3967. static bool is_loopback_port_accepting(int port) {
  3968. sockaddr_in addr{};
  3969. addr.sin_family = AF_INET;
  3970. addr.sin_port = htons(static_cast<uint16_t>(port));
  3971. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3972. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3973. EXPECT_NE(sock, INVALID_SOCKET);
  3974. if (sock == INVALID_SOCKET) { return false; }
  3975. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3976. static_cast<socklen_t>(sizeof(addr)));
  3977. detail::close_socket(sock);
  3978. return ret == 0;
  3979. }
  3980. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3981. Server svr;
  3982. auto port = svr.bind_to_any_port("127.0.0.1");
  3983. ASSERT_TRUE(port > 0);
  3984. svr.stop();
  3985. // bind_to_any_port() already called listen(2), so until stop() closed the
  3986. // descriptor the port kept accepting connections into the backlog. ASSERT
  3987. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3988. // below blocks forever in the accept loop.
  3989. ASSERT_FALSE(is_loopback_port_accepting(port));
  3990. // Nothing is left to accept on, so listen_after_bind() must report failure
  3991. // instead of returning success without ever serving.
  3992. EXPECT_FALSE(svr.listen_after_bind());
  3993. // The failed listen marks the server decommissioned, so a waiter returns
  3994. // instead of spinning forever.
  3995. svr.wait_until_ready();
  3996. }
  3997. #ifdef CPPHTTPLIB_SSL_ENABLED
  3998. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3999. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4000. CLIENT_CA_CERT_DIR);
  4001. int port = svr.bind_to_any_port("0.0.0.0");
  4002. ASSERT_TRUE(svr.is_valid());
  4003. ASSERT_TRUE(port > 0);
  4004. svr.stop();
  4005. }
  4006. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4007. // or a rejected CustomRoute() registration would not stop the server binding.
  4008. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4010. CLIENT_CA_CERT_DIR);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4013. EXPECT_FALSE(svr.is_valid());
  4014. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4015. }
  4016. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4017. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4018. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4019. int port = svr.bind_to_any_port("0.0.0.0");
  4020. ASSERT_TRUE(svr.is_valid());
  4021. ASSERT_TRUE(port > 0);
  4022. svr.stop();
  4023. }
  4024. TEST(BindServerTest, UpdateCertsPem) {
  4025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4026. int port = svr.bind_to_any_port("0.0.0.0");
  4027. ASSERT_TRUE(svr.is_valid());
  4028. ASSERT_TRUE(port > 0);
  4029. // Read PEM files
  4030. std::string cert_pem, key_pem, ca_pem;
  4031. read_file(SERVER_CERT_FILE, cert_pem);
  4032. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4033. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4034. // Update server certificates using PEM API
  4035. ASSERT_TRUE(
  4036. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4037. ASSERT_TRUE(svr.is_valid());
  4038. svr.stop();
  4039. }
  4040. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4041. // Start server with client CA (enables client auth)
  4042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4043. ASSERT_TRUE(svr.is_valid());
  4044. bool handler_called = false;
  4045. svr.Get("/test", [&](const Request &req, Response &res) {
  4046. handler_called = true;
  4047. // Verify client certificate is present
  4048. auto cert = req.peer_cert();
  4049. EXPECT_TRUE(static_cast<bool>(cert));
  4050. res.set_content("ok", "text/plain");
  4051. });
  4052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4053. auto se = detail::scope_exit([&] {
  4054. svr.stop();
  4055. t.join();
  4056. ASSERT_FALSE(svr.is_running());
  4057. });
  4058. svr.wait_until_ready();
  4059. // Read PEM files
  4060. std::string cert_pem, key_pem, ca_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4064. // Update server certificates and client CA using PEM API while server running
  4065. ASSERT_TRUE(
  4066. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4067. // Connect with client certificate
  4068. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4069. cli.enable_server_certificate_verification(false);
  4070. cli.set_connection_timeout(30);
  4071. auto res = cli.Get("/test");
  4072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4073. ASSERT_EQ(StatusCode::OK_200, res->status);
  4074. ASSERT_TRUE(handler_called);
  4075. EXPECT_EQ("ok", res->body);
  4076. }
  4077. // Puts a CA that did not sign the client's certificate in the old one's place.
  4078. static bool replace_client_ca(SSLServer &svr) {
  4079. std::string cert_pem, key_pem, ca_pem;
  4080. read_file(SERVER_CERT_FILE, cert_pem);
  4081. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4082. read_file(SERVER_CERT2_FILE, ca_pem);
  4083. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4084. ca_pem.c_str());
  4085. }
  4086. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4088. ASSERT_TRUE(svr.is_valid());
  4089. svr.Get("/test", [](const Request &, Response &res) {
  4090. res.set_content("ok", "text/plain");
  4091. });
  4092. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4093. auto se = detail::scope_exit([&] {
  4094. svr.stop();
  4095. t.join();
  4096. ASSERT_FALSE(svr.is_running());
  4097. });
  4098. svr.wait_until_ready();
  4099. auto get = [] {
  4100. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4101. cli.enable_server_certificate_verification(false);
  4102. return cli.Get("/test");
  4103. };
  4104. ASSERT_TRUE(get());
  4105. ASSERT_TRUE(replace_client_ca(svr));
  4106. EXPECT_FALSE(get());
  4107. }
  4108. TEST(SSLClientServerTest, VerifyCallbackKeepsClientCertificateRequired) {
  4109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4110. ASSERT_TRUE(svr.is_valid());
  4111. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4112. return v.preverify_ok;
  4113. });
  4114. svr.Get("/test", [](const Request &, Response &res) {
  4115. res.set_content("ok", "text/plain");
  4116. });
  4117. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4118. auto se = detail::scope_exit([&] {
  4119. svr.stop();
  4120. t.join();
  4121. ASSERT_FALSE(svr.is_running());
  4122. });
  4123. svr.wait_until_ready();
  4124. SSLClient without_cert(HOST, PORT);
  4125. without_cert.enable_server_certificate_verification(false);
  4126. EXPECT_FALSE(without_cert.Get("/test"));
  4127. SSLClient with_cert(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4128. with_cert.enable_server_certificate_verification(false);
  4129. auto res = with_cert.Get("/test");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ("ok", res->body);
  4132. }
  4133. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4135. ASSERT_TRUE(svr.is_valid());
  4136. tls::set_verify_callback(svr.tls_context(),
  4137. [](const tls::VerifyContext &) -> bool {
  4138. throw std::runtime_error("verify");
  4139. });
  4140. svr.Get("/test", [](const Request &, Response &res) {
  4141. res.set_content("ok", "text/plain");
  4142. });
  4143. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4144. auto se = detail::scope_exit([&] {
  4145. svr.stop();
  4146. t.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. svr.wait_until_ready();
  4150. auto get = [] {
  4151. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4152. cli.enable_server_certificate_verification(false);
  4153. return cli.Get("/test");
  4154. };
  4155. EXPECT_FALSE(get());
  4156. // The handshake is over, so an update does not wait for it.
  4157. std::string cert_pem, key_pem;
  4158. read_file(SERVER_CERT_FILE, cert_pem);
  4159. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4160. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4161. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4162. return v.preverify_ok;
  4163. });
  4164. auto res = get();
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ("ok", res->body);
  4167. }
  4168. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4169. // A client that resumes its session gets through, but not once the client CA
  4170. // has changed, as a resumed session does not show the certificate again.
  4171. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4173. ASSERT_TRUE(svr.is_valid());
  4174. svr.Get("/test", [](const Request &, Response &res) {
  4175. res.set_content("ok", "text/plain");
  4176. });
  4177. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4178. auto se = detail::scope_exit([&] {
  4179. svr.stop();
  4180. t.join();
  4181. ASSERT_FALSE(svr.is_running());
  4182. });
  4183. svr.wait_until_ready();
  4184. auto ctx = SSL_CTX_new(TLS_client_method());
  4185. auto ctx_se = detail::scope_exit([&] { SSL_CTX_free(ctx); });
  4186. ASSERT_EQ(
  4187. 1, SSL_CTX_use_certificate_file(ctx, CLIENT_CERT_FILE, SSL_FILETYPE_PEM));
  4188. ASSERT_EQ(1, SSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4189. SSL_FILETYPE_PEM));
  4190. SSL_SESSION *session = nullptr;
  4191. auto session_se = detail::scope_exit([&] { SSL_SESSION_free(session); });
  4192. // A request over a new connection, resuming `session` when there is one and
  4193. // keeping the connection's own in its place. Tells whether it was answered.
  4194. auto reused = false;
  4195. auto get = [&]() {
  4196. auto error = Error::Success;
  4197. auto sock = detail::create_client_socket(
  4198. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4199. /*connection_timeout_sec=*/5, 0,
  4200. /*read_timeout_sec=*/5, 0,
  4201. /*write_timeout_sec=*/5, 0, std::string(), error);
  4202. if (sock == INVALID_SOCKET) { return false; }
  4203. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4204. auto ssl = SSL_new(ctx);
  4205. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4206. SSL_set_fd(ssl, static_cast<int>(sock));
  4207. if (session) { SSL_set_session(ssl, session); }
  4208. if (SSL_connect(ssl) != 1) { return false; }
  4209. reused = SSL_session_reused(ssl) == 1;
  4210. // Reading the response also takes in a TLS 1.3 session ticket.
  4211. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4212. "Connection: close\r\n\r\n";
  4213. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4214. std::string res;
  4215. char buf[256];
  4216. int n;
  4217. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4218. res.append(buf, static_cast<size_t>(n));
  4219. }
  4220. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4221. SSL_shutdown(ssl);
  4222. SSL_SESSION_free(session);
  4223. session = SSL_get1_session(ssl);
  4224. return res.find("200 OK") != std::string::npos;
  4225. };
  4226. ASSERT_TRUE(get());
  4227. ASSERT_TRUE(get());
  4228. EXPECT_TRUE(reused);
  4229. ASSERT_TRUE(replace_client_ca(svr));
  4230. EXPECT_FALSE(get());
  4231. }
  4232. #endif
  4233. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4234. // wolfSSL shares its session cache between contexts, so a resumed session
  4235. // could carry a client certificate checked against another server's CA, or
  4236. // against a client CA since replaced.
  4237. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4239. ASSERT_TRUE(svr.is_valid());
  4240. // Trusts a CA that did not sign the client's certificate.
  4241. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4242. ASSERT_TRUE(other.is_valid());
  4243. for (auto s : {&svr, &other}) {
  4244. s->Get("/test", [](const Request &, Response &res) {
  4245. res.set_content("ok", "text/plain");
  4246. });
  4247. }
  4248. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4249. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4250. auto se = detail::scope_exit([&] {
  4251. other.stop();
  4252. svr.stop();
  4253. t2.join();
  4254. t.join();
  4255. });
  4256. svr.wait_until_ready();
  4257. other.wait_until_ready();
  4258. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4259. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4260. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4261. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4262. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4263. ASSERT_EQ(WOLFSSL_SUCCESS,
  4264. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4265. WOLFSSL_FILETYPE_PEM));
  4266. WOLFSSL_SESSION *session = nullptr;
  4267. auto session_se = detail::scope_exit([&] {
  4268. if (session) { wolfSSL_SESSION_free(session); }
  4269. });
  4270. // A request over a new connection, resuming `session` when there is one and
  4271. // keeping the connection's own in its place. Tells whether it was answered.
  4272. auto get = [&](int port) {
  4273. auto error = Error::Success;
  4274. auto sock = detail::create_client_socket(
  4275. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4276. /*connection_timeout_sec=*/5, 0,
  4277. /*read_timeout_sec=*/5, 0,
  4278. /*write_timeout_sec=*/5, 0, std::string(), error);
  4279. if (sock == INVALID_SOCKET) { return false; }
  4280. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4281. auto ssl = wolfSSL_new(ctx);
  4282. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4283. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4284. if (session) { wolfSSL_set_session(ssl, session); }
  4285. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4286. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4287. "Connection: close\r\n\r\n";
  4288. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4289. std::string res;
  4290. char buf[256];
  4291. int n;
  4292. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4293. res.append(buf, static_cast<size_t>(n));
  4294. }
  4295. wolfSSL_shutdown(ssl);
  4296. if (session) { wolfSSL_SESSION_free(session); }
  4297. session = wolfSSL_get1_session(ssl);
  4298. return res.find("200 OK") != std::string::npos;
  4299. };
  4300. ASSERT_TRUE(get(PORT));
  4301. EXPECT_FALSE(get(PORT + 1));
  4302. ASSERT_TRUE(get(PORT));
  4303. ASSERT_TRUE(replace_client_ca(svr));
  4304. EXPECT_FALSE(get(PORT));
  4305. }
  4306. #endif
  4307. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4309. ASSERT_TRUE(svr.is_valid());
  4310. svr.Get("/test", [](const Request &, Response &res) {
  4311. res.set_content("ok", "text/plain");
  4312. });
  4313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4314. auto se = detail::scope_exit([&] {
  4315. svr.stop();
  4316. t.join();
  4317. ASSERT_FALSE(svr.is_running());
  4318. });
  4319. svr.wait_until_ready();
  4320. // A connection that sends no ClientHello keeps its handshake in progress,
  4321. // once the server has had a moment to start it.
  4322. auto error = Error::Success;
  4323. auto sock = detail::create_client_socket(
  4324. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4325. /*connection_timeout_sec=*/5, 0,
  4326. /*read_timeout_sec=*/5, 0,
  4327. /*write_timeout_sec=*/5, 0, std::string(), error);
  4328. ASSERT_NE(INVALID_SOCKET, sock);
  4329. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4330. std::string cert_pem, key_pem;
  4331. read_file(SERVER_CERT_FILE, cert_pem);
  4332. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4333. auto update = std::async(std::launch::async, [&]() {
  4334. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4335. });
  4336. EXPECT_EQ(std::future_status::timeout,
  4337. update.wait_for(std::chrono::milliseconds(200)));
  4338. detail::close_socket(sock);
  4339. EXPECT_TRUE(update.get());
  4340. SSLClient cli(HOST, PORT);
  4341. cli.enable_server_certificate_verification(false);
  4342. auto res = cli.Get("/test");
  4343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. }
  4346. #endif
  4347. TEST(ErrorHandlerTest, ContentLength) {
  4348. Server svr;
  4349. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4350. res.status = StatusCode::OK_200;
  4351. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4352. "text/html"); // <= Content-Length still 13
  4353. });
  4354. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4355. res.set_content("Hello World!\n", "text/plain");
  4356. res.status = 524;
  4357. });
  4358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4359. auto se = detail::scope_exit([&] {
  4360. svr.stop();
  4361. thread.join();
  4362. ASSERT_FALSE(svr.is_running());
  4363. });
  4364. svr.wait_until_ready();
  4365. {
  4366. Client cli(HOST, PORT);
  4367. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4371. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4372. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4373. }
  4374. }
  4375. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4376. TEST(ExceptionTest, WithoutExceptionHandler) {
  4377. Server svr;
  4378. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4379. throw std::runtime_error("exception...");
  4380. });
  4381. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4382. throw std::runtime_error("exception\r\n...");
  4383. });
  4384. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4385. auto se = detail::scope_exit([&] {
  4386. svr.stop();
  4387. listen_thread.join();
  4388. ASSERT_FALSE(svr.is_running());
  4389. });
  4390. svr.wait_until_ready();
  4391. Client cli("localhost", PORT);
  4392. {
  4393. auto res = cli.Get("/exception");
  4394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4395. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4396. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4397. }
  4398. {
  4399. auto res = cli.Get("/unknown");
  4400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4401. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4402. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4403. }
  4404. }
  4405. TEST(ExceptionTest, WithExceptionHandler) {
  4406. Server svr;
  4407. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4408. std::exception_ptr ep) {
  4409. EXPECT_FALSE(ep == nullptr);
  4410. try {
  4411. std::rethrow_exception(ep);
  4412. } catch (std::exception &e) {
  4413. EXPECT_EQ("abc", std::string(e.what()));
  4414. } catch (...) {}
  4415. res.status = StatusCode::InternalServerError_500;
  4416. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4417. "text/html"); // <= Content-Length still 13 at this point
  4418. });
  4419. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4420. res.set_content("Hello World!\n", "text/plain");
  4421. throw std::runtime_error("abc");
  4422. });
  4423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4424. auto se = detail::scope_exit([&] {
  4425. svr.stop();
  4426. thread.join();
  4427. ASSERT_FALSE(svr.is_running());
  4428. });
  4429. svr.wait_until_ready();
  4430. for (size_t i = 0; i < 10; i++) {
  4431. Client cli(HOST, PORT);
  4432. for (size_t j = 0; j < 100; j++) {
  4433. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4435. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4436. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4437. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4438. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4439. }
  4440. cli.set_keep_alive(true);
  4441. for (size_t j = 0; j < 100; j++) {
  4442. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4444. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4445. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4446. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4447. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4448. }
  4449. }
  4450. }
  4451. TEST(ExceptionTest, AndErrorHandler) {
  4452. Server svr;
  4453. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4454. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4455. });
  4456. svr.set_exception_handler(
  4457. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4458. EXPECT_FALSE(ep == nullptr);
  4459. try {
  4460. std::rethrow_exception(ep);
  4461. } catch (std::exception &e) {
  4462. res.set_content(e.what(), "text/html");
  4463. } catch (...) {}
  4464. res.status = StatusCode::InternalServerError_500;
  4465. });
  4466. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4467. throw std::runtime_error("EXCEPTION");
  4468. });
  4469. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4470. res.set_content("ERROR", "text/html");
  4471. res.status = StatusCode::InternalServerError_500;
  4472. });
  4473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4474. auto se = detail::scope_exit([&] {
  4475. svr.stop();
  4476. thread.join();
  4477. ASSERT_FALSE(svr.is_running());
  4478. });
  4479. svr.wait_until_ready();
  4480. Client cli(HOST, PORT);
  4481. {
  4482. auto res = cli.Get("/exception");
  4483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4485. EXPECT_EQ("EXCEPTION", res->body);
  4486. }
  4487. {
  4488. auto res = cli.Get("/error");
  4489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4490. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4491. EXPECT_EQ("ERROR", res->body);
  4492. }
  4493. {
  4494. auto res = cli.Get("/invalid");
  4495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4497. EXPECT_EQ("NOT_FOUND", res->body);
  4498. }
  4499. }
  4500. #endif
  4501. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4502. // process_request() wraps only routing() in a try/catch, so an exception from
  4503. // any other user callback used to unwind into the task queue - which does not
  4504. // catch - and terminate the process. Each test below runs the server on a
  4505. // single worker thread: a guard that catches the exception but still loses the
  4506. // thread would otherwise be hidden by a spare worker serving the follow-up
  4507. // request. Note that a regression here aborts the whole test binary rather
  4508. // than failing one test.
  4509. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4510. Server svr;
  4511. svr.new_task_queue = [] { return new ThreadPool(1); };
  4512. std::atomic<int> reported{0};
  4513. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4514. if (err == Error::UserCallbackException) { reported++; }
  4515. });
  4516. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4517. res.set_content_provider(
  4518. 1024, "text/plain",
  4519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4520. sink.write("hello", 5);
  4521. throw std::runtime_error("from the content provider");
  4522. });
  4523. });
  4524. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4525. res.set_content("ok", "text/plain");
  4526. });
  4527. auto port = svr.bind_to_any_port(HOST);
  4528. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4529. auto se = detail::scope_exit([&] {
  4530. svr.stop();
  4531. listen_thread.join();
  4532. ASSERT_FALSE(svr.is_running());
  4533. });
  4534. svr.wait_until_ready();
  4535. {
  4536. Client cli(HOST, port);
  4537. cli.set_read_timeout(5, 0);
  4538. EXPECT_FALSE(cli.Get("/throw"));
  4539. }
  4540. EXPECT_TRUE(svr.is_running());
  4541. EXPECT_EQ(1, reported.load());
  4542. // A request on a fresh connection is still served.
  4543. {
  4544. Client cli(HOST, port);
  4545. auto res = cli.Get("/ok");
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("ok", res->body);
  4549. }
  4550. }
  4551. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4552. Server svr;
  4553. svr.new_task_queue = [] { return new ThreadPool(1); };
  4554. std::atomic<bool> should_throw{true};
  4555. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4556. res.set_content("hi", "text/plain");
  4557. });
  4558. svr.set_post_routing_handler(
  4559. [&](const Request & /*req*/, Response & /*res*/) {
  4560. if (should_throw) {
  4561. throw std::runtime_error("from the post-routing handler");
  4562. }
  4563. });
  4564. auto port = svr.bind_to_any_port(HOST);
  4565. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4566. auto se = detail::scope_exit([&] {
  4567. svr.stop();
  4568. listen_thread.join();
  4569. ASSERT_FALSE(svr.is_running());
  4570. });
  4571. svr.wait_until_ready();
  4572. {
  4573. Client cli(HOST, port);
  4574. cli.set_read_timeout(5, 0);
  4575. EXPECT_FALSE(cli.Get("/hi"));
  4576. }
  4577. EXPECT_TRUE(svr.is_running());
  4578. should_throw = false;
  4579. {
  4580. Client cli(HOST, port);
  4581. auto res = cli.Get("/hi");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ("hi", res->body);
  4585. }
  4586. }
  4587. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4588. // The guard reports the caught exception through the error logger, which is
  4589. // a user callback too. A logger that throws has to be contained as well, or
  4590. // the process would terminate from inside the catch.
  4591. Server svr;
  4592. svr.new_task_queue = [] { return new ThreadPool(1); };
  4593. std::atomic<int> reported{0};
  4594. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4595. if (err == Error::UserCallbackException) {
  4596. reported++;
  4597. throw std::runtime_error("from the error logger");
  4598. }
  4599. });
  4600. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4601. res.set_content_provider(
  4602. 1024, "text/plain",
  4603. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4604. sink.write("hello", 5);
  4605. throw std::runtime_error("from the content provider");
  4606. });
  4607. });
  4608. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4609. res.set_content("ok", "text/plain");
  4610. });
  4611. auto port = svr.bind_to_any_port(HOST);
  4612. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4613. auto se = detail::scope_exit([&] {
  4614. svr.stop();
  4615. listen_thread.join();
  4616. ASSERT_FALSE(svr.is_running());
  4617. });
  4618. svr.wait_until_ready();
  4619. {
  4620. Client cli(HOST, port);
  4621. cli.set_read_timeout(5, 0);
  4622. EXPECT_FALSE(cli.Get("/throw"));
  4623. }
  4624. EXPECT_TRUE(svr.is_running());
  4625. EXPECT_EQ(1, reported.load());
  4626. {
  4627. Client cli(HOST, port);
  4628. auto res = cli.Get("/ok");
  4629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4630. EXPECT_EQ(StatusCode::OK_200, res->status);
  4631. EXPECT_EQ("ok", res->body);
  4632. }
  4633. }
  4634. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4635. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4636. // so the exception unwinds through the ws::WebSocket object on its way to
  4637. // the guard. None of the HTTP cases above cross that.
  4638. Server svr;
  4639. svr.new_task_queue = [] { return new ThreadPool(1); };
  4640. std::atomic<int> reported{0};
  4641. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4642. if (err == Error::UserCallbackException) { reported++; }
  4643. });
  4644. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4645. throw std::runtime_error("from the WebSocket handler");
  4646. });
  4647. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4648. res.set_content("ok", "text/plain");
  4649. });
  4650. auto port = svr.bind_to_any_port(HOST);
  4651. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4652. auto se = detail::scope_exit([&] {
  4653. svr.stop();
  4654. listen_thread.join();
  4655. ASSERT_FALSE(svr.is_running());
  4656. });
  4657. svr.wait_until_ready();
  4658. {
  4659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4660. "/ws");
  4661. auto res = client.connect();
  4662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4663. // The server dropped the connection instead of dying.
  4664. std::string msg;
  4665. EXPECT_FALSE(client.read(msg));
  4666. client.close();
  4667. }
  4668. EXPECT_TRUE(svr.is_running());
  4669. EXPECT_EQ(1, reported.load());
  4670. {
  4671. Client cli(HOST, port);
  4672. auto res = cli.Get("/ok");
  4673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4674. EXPECT_EQ(StatusCode::OK_200, res->status);
  4675. EXPECT_EQ("ok", res->body);
  4676. }
  4677. }
  4678. #ifdef CPPHTTPLIB_SSL_ENABLED
  4679. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4680. // SSLServer::process_and_close_socket() is a separate overload with its own
  4681. // guard, so it is exercised on its own.
  4682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4683. ASSERT_TRUE(svr.is_valid());
  4684. svr.new_task_queue = [] { return new ThreadPool(1); };
  4685. std::atomic<int> reported{0};
  4686. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4687. if (err == Error::UserCallbackException) { reported++; }
  4688. });
  4689. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4690. res.set_content_provider(
  4691. 1024, "text/plain",
  4692. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4693. sink.write("hello", 5);
  4694. throw std::runtime_error("from the content provider");
  4695. });
  4696. });
  4697. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4698. res.set_content("ok", "text/plain");
  4699. });
  4700. auto port = svr.bind_to_any_port(HOST);
  4701. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4702. auto se = detail::scope_exit([&] {
  4703. svr.stop();
  4704. listen_thread.join();
  4705. ASSERT_FALSE(svr.is_running());
  4706. });
  4707. svr.wait_until_ready();
  4708. {
  4709. SSLClient cli(HOST, port);
  4710. cli.enable_server_certificate_verification(false);
  4711. cli.set_read_timeout(5, 0);
  4712. EXPECT_FALSE(cli.Get("/throw"));
  4713. }
  4714. EXPECT_TRUE(svr.is_running());
  4715. EXPECT_EQ(1, reported.load());
  4716. {
  4717. SSLClient cli(HOST, port);
  4718. cli.enable_server_certificate_verification(false);
  4719. auto res = cli.Get("/ok");
  4720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("ok", res->body);
  4723. }
  4724. }
  4725. #endif
  4726. #endif
  4727. TEST(NoContentTest, ContentLength) {
  4728. Server svr;
  4729. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4730. res.status = StatusCode::NoContent_204;
  4731. });
  4732. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4733. auto se = detail::scope_exit([&] {
  4734. svr.stop();
  4735. thread.join();
  4736. ASSERT_FALSE(svr.is_running());
  4737. });
  4738. svr.wait_until_ready();
  4739. {
  4740. Client cli(HOST, PORT);
  4741. auto res = cli.Get("/hi");
  4742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4743. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4744. // RFC 9110 8.6: none in a 204 response
  4745. EXPECT_FALSE(res->has_header("Content-Length"));
  4746. }
  4747. }
  4748. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4749. Server svr;
  4750. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4751. res.set_header("Content-Length", "5");
  4752. res.set_content("hello world", "text/plain");
  4753. });
  4754. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4755. // A body that reads as the last chunk, were it taken as chunked
  4756. res.set_header("Transfer-Encoding", "chunked");
  4757. res.set_content("0\r\n\r\n", "text/plain");
  4758. });
  4759. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4760. res.set_header("Content-Length", "2");
  4761. res.set_content_provider(5, "text/plain",
  4762. [](size_t offset, size_t length, DataSink &sink) {
  4763. sink.write(&"hello"[offset], length);
  4764. return true;
  4765. });
  4766. });
  4767. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4768. res.set_header("Content-Length", "1234");
  4769. });
  4770. thread t = thread([&] { svr.listen(HOST, PORT); });
  4771. auto se = detail::scope_exit([&] {
  4772. svr.stop();
  4773. t.join();
  4774. ASSERT_FALSE(svr.is_running());
  4775. });
  4776. svr.wait_until_ready();
  4777. Client cli(HOST, PORT);
  4778. cli.set_read_timeout(1, 0);
  4779. auto expect_body = [&](const Result &res, const std::string &body) {
  4780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4781. EXPECT_EQ(body, res->body);
  4782. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4783. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4784. };
  4785. Headers identity{{"Accept-Encoding", ""}};
  4786. expect_body(cli.Get("/body", identity), "hello world");
  4787. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4788. expect_body(cli.Get("/body",
  4789. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4790. "he");
  4791. expect_body(cli.Get("/provider", identity), "hello");
  4792. expect_body(cli.Get("/empty", identity), "");
  4793. // A HEAD response may give the length of the body a GET would get.
  4794. auto res = cli.Head("/empty");
  4795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4796. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4797. }
  4798. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4799. Server svr;
  4800. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4801. res.set_content("short", "text/plain");
  4802. });
  4803. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4804. res.body += " with a footer";
  4805. res.set_header("Transfer-Encoding", "chunked");
  4806. });
  4807. thread t = thread([&] { svr.listen(HOST, PORT); });
  4808. auto se = detail::scope_exit([&] {
  4809. svr.stop();
  4810. t.join();
  4811. ASSERT_FALSE(svr.is_running());
  4812. });
  4813. svr.wait_until_ready();
  4814. Client cli(HOST, PORT);
  4815. cli.set_read_timeout(1, 0);
  4816. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4818. EXPECT_EQ("short with a footer", res->body);
  4819. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4820. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4821. }
  4822. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4823. Server svr;
  4824. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4825. res.set_header("Content-Length", "3");
  4826. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4827. sink.write("abc", 3);
  4828. sink.done();
  4829. return true;
  4830. });
  4831. });
  4832. thread t = thread([&] { svr.listen(HOST, PORT); });
  4833. auto se = detail::scope_exit([&] {
  4834. svr.stop();
  4835. t.join();
  4836. ASSERT_FALSE(svr.is_running());
  4837. });
  4838. svr.wait_until_ready();
  4839. Client cli(HOST, PORT);
  4840. cli.set_keep_alive(true);
  4841. auto res = cli.Get("/");
  4842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4843. EXPECT_EQ("abc", res->body);
  4844. EXPECT_FALSE(res->has_header("Content-Length"));
  4845. EXPECT_EQ("close", res->get_header_value("Connection"));
  4846. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4847. // No body to delimit
  4848. auto head = cli.Head("/");
  4849. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4850. EXPECT_FALSE(head->has_header("Connection"));
  4851. }
  4852. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4853. #ifdef CPPHTTPLIB_SSL_ENABLED
  4854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4855. ASSERT_TRUE(svr.is_valid());
  4856. #else
  4857. Server svr;
  4858. #endif
  4859. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4860. if (req.path == "/routing_handler") {
  4861. res.set_header("PRE_ROUTING", "on");
  4862. res.set_content("Routing Handler", "text/plain");
  4863. return httplib::Server::HandlerResponse::Handled;
  4864. }
  4865. return httplib::Server::HandlerResponse::Unhandled;
  4866. });
  4867. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4868. res.set_content("Error", "text/html");
  4869. });
  4870. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4871. if (req.path == "/routing_handler") {
  4872. res.set_header("POST_ROUTING", "on");
  4873. }
  4874. });
  4875. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4876. res.set_content("Hello World!\n", "text/plain");
  4877. });
  4878. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4879. auto se = detail::scope_exit([&] {
  4880. svr.stop();
  4881. thread.join();
  4882. ASSERT_FALSE(svr.is_running());
  4883. });
  4884. svr.wait_until_ready();
  4885. {
  4886. #ifdef CPPHTTPLIB_SSL_ENABLED
  4887. SSLClient cli(HOST, PORT);
  4888. cli.enable_server_certificate_verification(false);
  4889. #else
  4890. Client cli(HOST, PORT);
  4891. #endif
  4892. auto res = cli.Get("/routing_handler");
  4893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4894. EXPECT_EQ(StatusCode::OK_200, res->status);
  4895. EXPECT_EQ("Routing Handler", res->body);
  4896. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4897. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4898. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4899. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4900. }
  4901. {
  4902. #ifdef CPPHTTPLIB_SSL_ENABLED
  4903. SSLClient cli(HOST, PORT);
  4904. cli.enable_server_certificate_verification(false);
  4905. #else
  4906. Client cli(HOST, PORT);
  4907. #endif
  4908. auto res = cli.Get("/hi");
  4909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4910. EXPECT_EQ(StatusCode::OK_200, res->status);
  4911. EXPECT_EQ("Hello World!\n", res->body);
  4912. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4913. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4914. }
  4915. {
  4916. #ifdef CPPHTTPLIB_SSL_ENABLED
  4917. SSLClient cli(HOST, PORT);
  4918. cli.enable_server_certificate_verification(false);
  4919. #else
  4920. Client cli(HOST, PORT);
  4921. #endif
  4922. auto res = cli.Get("/aaa");
  4923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4925. EXPECT_EQ("Error", res->body);
  4926. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4927. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4928. }
  4929. }
  4930. TEST(RequestHandlerTest, PreRequestHandler) {
  4931. auto route_path = "/user/:user";
  4932. Server svr;
  4933. svr.Get("/hi", [](const Request &, Response &res) {
  4934. res.set_content("hi", "text/plain");
  4935. });
  4936. svr.Get(route_path, [](const Request &req, Response &res) {
  4937. res.set_content(req.path_params.at("user"), "text/plain");
  4938. });
  4939. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4940. if (req.matched_route == route_path) {
  4941. auto user = req.path_params.at("user");
  4942. if (user != "john") {
  4943. res.status = StatusCode::Forbidden_403;
  4944. res.set_content("error", "text/html");
  4945. return Server::HandlerResponse::Handled;
  4946. }
  4947. }
  4948. return Server::HandlerResponse::Unhandled;
  4949. });
  4950. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4951. auto se = detail::scope_exit([&] {
  4952. svr.stop();
  4953. thread.join();
  4954. ASSERT_FALSE(svr.is_running());
  4955. });
  4956. svr.wait_until_ready();
  4957. Client cli(HOST, PORT);
  4958. {
  4959. auto res = cli.Get("/hi");
  4960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4961. EXPECT_EQ(StatusCode::OK_200, res->status);
  4962. EXPECT_EQ("hi", res->body);
  4963. }
  4964. {
  4965. auto res = cli.Get("/user/john");
  4966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. EXPECT_EQ("john", res->body);
  4969. }
  4970. {
  4971. auto res = cli.Get("/user/invalid-user");
  4972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4973. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4974. EXPECT_EQ("error", res->body);
  4975. }
  4976. }
  4977. // The pre-request handler must run before the request body is read, so a
  4978. // rejected request never forces the server to buffer a (potentially large)
  4979. // body. Here the posted body is larger than the payload limit: if the body
  4980. // were read first the server would answer 413, but because the pre-request
  4981. // handler runs first it answers 403 and the body is never read.
  4982. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4983. Server svr;
  4984. svr.set_payload_max_length(8);
  4985. auto handler_ran = false;
  4986. svr.Post("/reject", [&](const Request &req, Response &res) {
  4987. handler_ran = true;
  4988. res.set_content(req.body, "text/plain");
  4989. });
  4990. svr.Post("/accept", [](const Request &req, Response &res) {
  4991. res.set_content(req.body, "text/plain");
  4992. });
  4993. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4994. if (req.matched_route == "/reject") {
  4995. res.status = StatusCode::Forbidden_403;
  4996. res.set_content("denied", "text/plain");
  4997. return Server::HandlerResponse::Handled;
  4998. }
  4999. return Server::HandlerResponse::Unhandled;
  5000. });
  5001. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5002. auto se = detail::scope_exit([&] {
  5003. svr.stop();
  5004. thread.join();
  5005. ASSERT_FALSE(svr.is_running());
  5006. });
  5007. svr.wait_until_ready();
  5008. Client cli(HOST, PORT);
  5009. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5010. // rejects with 403 before the body is read, so 413 is never reached.
  5011. {
  5012. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5014. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5015. EXPECT_EQ("denied", res->body);
  5016. EXPECT_FALSE(handler_ran);
  5017. }
  5018. // An approved route still reads the body and enforces the payload limit.
  5019. {
  5020. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5023. }
  5024. }
  5025. TEST(UserDataTest, BasicOperations) {
  5026. httplib::UserData ud;
  5027. // Initially empty
  5028. EXPECT_FALSE(ud.has("key"));
  5029. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5030. // set and get
  5031. ud.set("key", 42);
  5032. EXPECT_TRUE(ud.has("key"));
  5033. auto *p = ud.get<int>("key");
  5034. ASSERT_NE(nullptr, p);
  5035. EXPECT_EQ(42, *p);
  5036. // Type mismatch → nullptr
  5037. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5038. // Overwrite with different type
  5039. ud.set("key", std::string("hello"));
  5040. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5041. auto *s = ud.get<std::string>("key");
  5042. ASSERT_NE(nullptr, s);
  5043. EXPECT_EQ("hello", *s);
  5044. // erase
  5045. ud.erase("key");
  5046. EXPECT_FALSE(ud.has("key"));
  5047. // clear
  5048. ud.set("a", 1);
  5049. ud.set("b", 2);
  5050. ud.clear();
  5051. EXPECT_FALSE(ud.has("a"));
  5052. EXPECT_FALSE(ud.has("b"));
  5053. }
  5054. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5055. struct AuthCtx {
  5056. std::string user_id;
  5057. };
  5058. Server svr;
  5059. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5060. res.user_data.set("auth", AuthCtx{"alice"});
  5061. return Server::HandlerResponse::Unhandled;
  5062. });
  5063. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5064. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5065. ASSERT_NE(nullptr, ctx);
  5066. res.set_content("Hello " + ctx->user_id, "text/plain");
  5067. });
  5068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5069. auto se = detail::scope_exit([&] {
  5070. svr.stop();
  5071. thread.join();
  5072. ASSERT_FALSE(svr.is_running());
  5073. });
  5074. svr.wait_until_ready();
  5075. Client cli(HOST, PORT);
  5076. auto res = cli.Get("/me");
  5077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. EXPECT_EQ("Hello alice", res->body);
  5080. }
  5081. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5082. struct RoleCtx {
  5083. std::string role;
  5084. };
  5085. Server svr;
  5086. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5087. res.user_data.set("role", RoleCtx{"admin"});
  5088. return Server::HandlerResponse::Unhandled;
  5089. });
  5090. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5091. auto *ctx = res.user_data.get<RoleCtx>("role");
  5092. ASSERT_NE(nullptr, ctx);
  5093. res.set_content(ctx->role, "text/plain");
  5094. });
  5095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5096. auto se = detail::scope_exit([&] {
  5097. svr.stop();
  5098. thread.join();
  5099. ASSERT_FALSE(svr.is_running());
  5100. });
  5101. svr.wait_until_ready();
  5102. Client cli(HOST, PORT);
  5103. auto res = cli.Get("/role");
  5104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5105. EXPECT_EQ(StatusCode::OK_200, res->status);
  5106. EXPECT_EQ("admin", res->body);
  5107. }
  5108. TEST(InvalidFormatTest, StatusCode) {
  5109. Server svr;
  5110. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5111. res.set_content("Hello World!\n", "text/plain");
  5112. res.status = 9999; // Status should be a three-digit code...
  5113. });
  5114. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5115. auto se = detail::scope_exit([&] {
  5116. svr.stop();
  5117. thread.join();
  5118. ASSERT_FALSE(svr.is_running());
  5119. });
  5120. svr.wait_until_ready();
  5121. {
  5122. Client cli(HOST, PORT);
  5123. auto res = cli.Get("/hi");
  5124. ASSERT_FALSE(res);
  5125. }
  5126. }
  5127. TEST(URLFragmentTest, WithFragment) {
  5128. Server svr;
  5129. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5130. EXPECT_TRUE(req.target == "/hi");
  5131. });
  5132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5133. auto se = detail::scope_exit([&] {
  5134. svr.stop();
  5135. thread.join();
  5136. ASSERT_FALSE(svr.is_running());
  5137. });
  5138. svr.wait_until_ready();
  5139. {
  5140. Client cli(HOST, PORT);
  5141. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5142. EXPECT_TRUE(res);
  5143. EXPECT_EQ(StatusCode::OK_200, res->status);
  5144. res = cli.Get("/hi%23key1=val1=key2=val2");
  5145. EXPECT_TRUE(res);
  5146. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5147. }
  5148. }
  5149. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5150. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5151. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5152. Server svr;
  5153. std::vector<std::string> targets;
  5154. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5155. targets.push_back(req.target);
  5156. });
  5157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5158. auto se = detail::scope_exit([&] {
  5159. svr.stop();
  5160. thread.join();
  5161. ASSERT_FALSE(svr.is_running());
  5162. });
  5163. svr.wait_until_ready();
  5164. Client cli(HOST, PORT);
  5165. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5166. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5167. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5168. // A '?' after the '#' belongs to the fragment, not to the query.
  5169. Request req;
  5170. req.method = "GET";
  5171. req.path = "/hi#f?x=1";
  5172. req.params.emplace("a", "1");
  5173. Response res;
  5174. auto error = Error::Success;
  5175. EXPECT_TRUE(cli.send(req, res, error));
  5176. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5177. "/hi?a=1"}),
  5178. targets);
  5179. }
  5180. TEST(HeaderWriter, SetHeaderWriter) {
  5181. Server svr;
  5182. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5183. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5184. return detail::write_headers(strm, hdrs);
  5185. });
  5186. svr.Get("/hi", [](const Request &req, Response &res) {
  5187. auto it = req.headers.find("CustomClientHeader");
  5188. EXPECT_TRUE(it != req.headers.end());
  5189. EXPECT_EQ(it->second, "CustomClientValue");
  5190. res.set_content("Hello World!\n", "text/plain");
  5191. });
  5192. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5193. auto se = detail::scope_exit([&] {
  5194. svr.stop();
  5195. thread.join();
  5196. ASSERT_FALSE(svr.is_running());
  5197. });
  5198. svr.wait_until_ready();
  5199. {
  5200. Client cli(HOST, PORT);
  5201. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5202. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5203. return detail::write_headers(strm, hdrs);
  5204. });
  5205. auto res = cli.Get("/hi");
  5206. EXPECT_TRUE(res);
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. auto it = res->headers.find("CustomServerHeader");
  5209. EXPECT_TRUE(it != res->headers.end());
  5210. EXPECT_EQ(it->second, "CustomServerValue");
  5211. }
  5212. }
  5213. class ServerTest : public ::testing::Test {
  5214. protected:
  5215. ServerTest()
  5216. : cli_(HOST, PORT)
  5217. #ifdef CPPHTTPLIB_SSL_ENABLED
  5218. ,
  5219. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5220. #endif
  5221. {
  5222. #ifdef CPPHTTPLIB_SSL_ENABLED
  5223. cli_.enable_server_certificate_verification(false);
  5224. #endif
  5225. // Allow LARGE_DATA (100MB) responses
  5226. cli_.set_payload_max_length(200 * 1024 * 1024);
  5227. }
  5228. virtual void SetUp() {
  5229. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5230. svr_.set_payload_max_length(200 * 1024 * 1024);
  5231. svr_.set_mount_point("/", "./www");
  5232. svr_.set_mount_point("/mount", "./www2");
  5233. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5234. svr_.Get("/hi",
  5235. [&](const Request & /*req*/, Response &res) {
  5236. res.set_content("Hello World!", "text/plain");
  5237. })
  5238. .Get("/file_content",
  5239. [&](const Request & /*req*/, Response &res) {
  5240. res.set_file_content("./www/dir/test.html");
  5241. })
  5242. .Get("/file_content_with_content_type",
  5243. [&](const Request & /*req*/, Response &res) {
  5244. res.set_file_content("./www/file", "text/plain");
  5245. })
  5246. .Get("/invalid_file_content",
  5247. [&](const Request & /*req*/, Response &res) {
  5248. res.set_file_content("./www/dir/invalid_file_path");
  5249. })
  5250. .Get("/http_response_splitting",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5253. EXPECT_EQ(0U, res.headers.size());
  5254. EXPECT_FALSE(res.has_header("a"));
  5255. res.set_header("a", "1\nSet-Cookie: a=1");
  5256. EXPECT_EQ(0U, res.headers.size());
  5257. EXPECT_FALSE(res.has_header("a"));
  5258. res.set_header("a", "1\rSet-Cookie: a=1");
  5259. EXPECT_EQ(0U, res.headers.size());
  5260. EXPECT_FALSE(res.has_header("a"));
  5261. res.set_header("a\r\nb", "0");
  5262. EXPECT_EQ(0U, res.headers.size());
  5263. EXPECT_FALSE(res.has_header("a"));
  5264. res.set_header("a\rb", "0");
  5265. EXPECT_EQ(0U, res.headers.size());
  5266. EXPECT_FALSE(res.has_header("a"));
  5267. res.set_header("a\nb", "0");
  5268. EXPECT_EQ(0U, res.headers.size());
  5269. EXPECT_FALSE(res.has_header("a"));
  5270. res.set_redirect("1\r\nSet-Cookie: a=1");
  5271. EXPECT_EQ(0U, res.headers.size());
  5272. EXPECT_FALSE(res.has_header("Location"));
  5273. })
  5274. .Get("/slow",
  5275. [&](const Request & /*req*/, Response &res) {
  5276. std::this_thread::sleep_for(std::chrono::seconds(4));
  5277. res.set_content("slow", "text/plain");
  5278. })
  5279. #if 0
  5280. .Post("/slowpost",
  5281. [&](const Request & /*req*/, Response &res) {
  5282. std::this_thread::sleep_for(std::chrono::seconds(2));
  5283. res.set_content("slow", "text/plain");
  5284. })
  5285. #endif
  5286. .Get("/remote_addr",
  5287. [&](const Request &req, Response &res) {
  5288. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5289. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5290. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5291. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5292. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5293. #endif
  5294. res.set_content(req.remote_addr, "text/plain");
  5295. })
  5296. .Get("/local_addr",
  5297. [&](const Request &req, Response &res) {
  5298. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5299. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5300. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5301. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5302. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5303. #endif
  5304. auto local_addr = req.local_addr;
  5305. auto local_port = std::to_string(req.local_port);
  5306. res.set_content(local_addr.append(":").append(local_port),
  5307. "text/plain");
  5308. })
  5309. .Get("/endwith%",
  5310. [&](const Request & /*req*/, Response &res) {
  5311. res.set_content("Hello World!", "text/plain");
  5312. })
  5313. .Get("/a\\+\\+b",
  5314. [&](const Request &req, Response &res) {
  5315. ASSERT_TRUE(req.has_param("a +b"));
  5316. auto val = req.get_param_value("a +b");
  5317. res.set_content(val, "text/plain");
  5318. })
  5319. .Get("/", [&](const Request & /*req*/,
  5320. Response &res) { res.set_redirect("/hi"); })
  5321. .Post("/1",
  5322. [](const Request & /*req*/, Response &res) {
  5323. res.set_redirect("/2", StatusCode::SeeOther_303);
  5324. })
  5325. .Get("/2",
  5326. [](const Request & /*req*/, Response &res) {
  5327. res.set_content("redirected.", "text/plain");
  5328. res.status = StatusCode::OK_200;
  5329. })
  5330. .Post("/person",
  5331. [&](const Request &req, Response &res) {
  5332. if (req.has_param("name") && req.has_param("note")) {
  5333. persons_[req.get_param_value("name")] =
  5334. req.get_param_value("note");
  5335. } else {
  5336. res.status = StatusCode::BadRequest_400;
  5337. }
  5338. })
  5339. .Put("/person",
  5340. [&](const Request &req, Response &res) {
  5341. if (req.has_param("name") && req.has_param("note")) {
  5342. persons_[req.get_param_value("name")] =
  5343. req.get_param_value("note");
  5344. } else {
  5345. res.status = StatusCode::BadRequest_400;
  5346. }
  5347. })
  5348. .Get("/person/(.*)",
  5349. [&](const Request &req, Response &res) {
  5350. string name = req.matches[1];
  5351. if (persons_.find(name) != persons_.end()) {
  5352. auto note = persons_[name];
  5353. res.set_content(note, "text/plain");
  5354. } else {
  5355. res.status = StatusCode::NotFound_404;
  5356. }
  5357. })
  5358. .Delete("/person",
  5359. [&](const Request &req, Response &res) {
  5360. if (req.has_param("name")) {
  5361. string name = req.get_param_value("name");
  5362. if (persons_.find(name) != persons_.end()) {
  5363. persons_.erase(name);
  5364. res.set_content("DELETED", "text/plain");
  5365. } else {
  5366. res.status = StatusCode::NotFound_404;
  5367. }
  5368. } else {
  5369. res.status = StatusCode::BadRequest_400;
  5370. }
  5371. })
  5372. .Post("/x-www-form-urlencoded-json",
  5373. [&](const Request &req, Response &res) {
  5374. auto json = req.get_param_value("json");
  5375. ASSERT_EQ(JSON_DATA, json);
  5376. res.set_content(json, "appliation/json");
  5377. res.status = StatusCode::OK_200;
  5378. })
  5379. .Get("/streamed-chunked",
  5380. [&](const Request & /*req*/, Response &res) {
  5381. res.set_chunked_content_provider(
  5382. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5383. sink.os << "123";
  5384. sink.os << "456";
  5385. sink.os << "789";
  5386. sink.done();
  5387. return true;
  5388. });
  5389. })
  5390. .Get("/streamed-chunked-with-prohibited-trailer",
  5391. [&](const Request & /*req*/, Response &res) {
  5392. auto i = new int(0);
  5393. // Declare both a prohibited trailer (Content-Length) and an
  5394. // allowed one
  5395. res.set_header("Trailer", "Content-Length, X-Allowed");
  5396. res.set_chunked_content_provider(
  5397. "text/plain",
  5398. [i](size_t /*offset*/, DataSink &sink) {
  5399. switch (*i) {
  5400. case 0: sink.os << "123"; break;
  5401. case 1: sink.os << "456"; break;
  5402. case 2: sink.os << "789"; break;
  5403. case 3: {
  5404. sink.done_with_trailer(
  5405. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5406. } break;
  5407. }
  5408. (*i)++;
  5409. return true;
  5410. },
  5411. [i](bool success) {
  5412. EXPECT_TRUE(success);
  5413. delete i;
  5414. });
  5415. })
  5416. .Get("/streamed-chunked2",
  5417. [&](const Request & /*req*/, Response &res) {
  5418. auto i = new int(0);
  5419. res.set_chunked_content_provider(
  5420. "text/plain",
  5421. [i](size_t /*offset*/, DataSink &sink) {
  5422. switch (*i) {
  5423. case 0: sink.os << "123"; break;
  5424. case 1: sink.os << "456"; break;
  5425. case 2: sink.os << "789"; break;
  5426. case 3: sink.done(); break;
  5427. }
  5428. (*i)++;
  5429. return true;
  5430. },
  5431. [i](bool success) {
  5432. EXPECT_TRUE(success);
  5433. delete i;
  5434. });
  5435. })
  5436. .Get("/streamed-chunked-with-trailer",
  5437. [&](const Request & /*req*/, Response &res) {
  5438. auto i = new int(0);
  5439. res.set_header("Trailer", "Dummy1, Dummy2");
  5440. res.set_chunked_content_provider(
  5441. "text/plain",
  5442. [i](size_t /*offset*/, DataSink &sink) {
  5443. switch (*i) {
  5444. case 0: sink.os << "123"; break;
  5445. case 1: sink.os << "456"; break;
  5446. case 2: sink.os << "789"; break;
  5447. case 3: {
  5448. sink.done_with_trailer(
  5449. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5450. } break;
  5451. }
  5452. (*i)++;
  5453. return true;
  5454. },
  5455. [i](bool success) {
  5456. EXPECT_TRUE(success);
  5457. delete i;
  5458. });
  5459. })
  5460. .Get("/streamed",
  5461. [&](const Request & /*req*/, Response &res) {
  5462. res.set_content_provider(
  5463. 6, "text/plain",
  5464. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5465. sink.os << (offset < 3 ? "a" : "b");
  5466. return true;
  5467. });
  5468. })
  5469. .Get("/streamed-without-length",
  5470. [&](const Request & /*req*/, Response &res) {
  5471. auto data = new std::string("abcdefg");
  5472. res.set_content_provider(
  5473. "text/plain",
  5474. [data](size_t offset, DataSink &sink) {
  5475. if (offset < data->size()) {
  5476. sink.os << data->substr(offset);
  5477. }
  5478. sink.done();
  5479. return true;
  5480. },
  5481. [data](bool success) {
  5482. EXPECT_TRUE(success);
  5483. delete data;
  5484. });
  5485. })
  5486. .Get("/streamed-with-range",
  5487. [&](const Request &req, Response &res) {
  5488. auto data = new std::string("abcdefg");
  5489. // An explicit status keeps the server from picking the 206 it
  5490. // would otherwise choose for a ranged request, so the response
  5491. // is not a partial representation.
  5492. auto status = req.get_param_value("status");
  5493. if (status == "200") {
  5494. res.status = StatusCode::OK_200;
  5495. } else if (status == "403") {
  5496. res.status = StatusCode::Forbidden_403;
  5497. }
  5498. res.set_content_provider(
  5499. data->size(), "text/plain",
  5500. [data](size_t offset, size_t length, DataSink &sink) {
  5501. size_t DATA_CHUNK_SIZE = 4;
  5502. const auto &d = *data;
  5503. auto out_len =
  5504. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5505. auto ret =
  5506. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5507. EXPECT_TRUE(ret);
  5508. return true;
  5509. },
  5510. [data, &req](bool success) {
  5511. EXPECT_EQ(success, !req.has_param("error"));
  5512. delete data;
  5513. });
  5514. })
  5515. .Get("/streamed-cancel",
  5516. [&](const Request & /*req*/, Response &res) {
  5517. res.set_content_provider(
  5518. size_t(-1), "text/plain",
  5519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5520. sink.os << "data_chunk";
  5521. return true;
  5522. });
  5523. })
  5524. .Get("/regex-with-delimiter",
  5525. [&](const Request &req, Response & /*res*/) {
  5526. ASSERT_TRUE(req.has_param("key"));
  5527. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5528. })
  5529. .Get("/with-range",
  5530. [&](const Request & /*req*/, Response &res) {
  5531. res.set_content("abcdefg", "text/plain");
  5532. })
  5533. .Get("/test-start-time",
  5534. [&](const Request &req, Response & /*res*/) {
  5535. EXPECT_NE(req.start_time_,
  5536. std::chrono::steady_clock::time_point::min());
  5537. })
  5538. .Get("/with-range-customized-response",
  5539. [&](const Request & /*req*/, Response &res) {
  5540. res.status = StatusCode::BadRequest_400;
  5541. res.set_content(JSON_DATA, "application/json");
  5542. })
  5543. .Post("/chunked",
  5544. [&](const Request &req, Response & /*res*/) {
  5545. EXPECT_EQ(req.body, "dechunked post body");
  5546. })
  5547. .Post("/large-chunked",
  5548. [&](const Request &req, Response & /*res*/) {
  5549. std::string expected(6 * 30 * 1024u, 'a');
  5550. EXPECT_EQ(req.body, expected);
  5551. })
  5552. .Post("/multipart",
  5553. [&](const Request &req, Response & /*res*/) {
  5554. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5555. req.form.get_field_count("text2") +
  5556. req.form.get_field_count("file3") +
  5557. req.form.get_field_count("file4"));
  5558. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5559. req.form.get_file_count("file2"));
  5560. ASSERT_TRUE(!req.form.has_file("???"));
  5561. ASSERT_TRUE(!req.form.has_field("???"));
  5562. ASSERT_TRUE(req.body.empty());
  5563. {
  5564. const auto &text = req.form.get_field("text1");
  5565. EXPECT_EQ("text default", text);
  5566. }
  5567. {
  5568. const auto &text = req.form.get_field("text2");
  5569. EXPECT_EQ("aωb", text);
  5570. }
  5571. {
  5572. const auto &file = req.form.get_file("file1");
  5573. EXPECT_EQ("hello.txt", file.filename);
  5574. EXPECT_EQ("text/plain", file.content_type);
  5575. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5576. }
  5577. {
  5578. const auto &file = req.form.get_file("file2");
  5579. EXPECT_EQ("world.json", file.filename);
  5580. EXPECT_EQ("application/json", file.content_type);
  5581. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5582. }
  5583. {
  5584. const auto &text = req.form.get_field("file3");
  5585. EXPECT_EQ(0u, text.size());
  5586. }
  5587. {
  5588. const auto &text = req.form.get_field("file4");
  5589. EXPECT_EQ(0u, text.size());
  5590. }
  5591. })
  5592. .Post("/multipart/multi_file_values",
  5593. [&](const Request &req, Response & /*res*/) {
  5594. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5595. req.form.get_field_count("multi_text1"));
  5596. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5597. ASSERT_TRUE(!req.form.has_file("???"));
  5598. ASSERT_TRUE(!req.form.has_field("???"));
  5599. ASSERT_TRUE(req.body.empty());
  5600. {
  5601. const auto &text = req.form.get_field("text");
  5602. EXPECT_EQ("default text", text);
  5603. }
  5604. {
  5605. const auto &text1_values = req.form.get_fields("multi_text1");
  5606. EXPECT_EQ(2u, text1_values.size());
  5607. EXPECT_EQ("aaaaa", text1_values[0]);
  5608. EXPECT_EQ("bbbbb", text1_values[1]);
  5609. }
  5610. {
  5611. const auto &file1_values = req.form.get_files("multi_file1");
  5612. EXPECT_EQ(2u, file1_values.size());
  5613. auto file1 = file1_values[0];
  5614. EXPECT_EQ(file1.filename, "hello.txt");
  5615. EXPECT_EQ(file1.content_type, "text/plain");
  5616. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5617. auto file2 = file1_values[1];
  5618. EXPECT_EQ(file2.filename, "world.json");
  5619. EXPECT_EQ(file2.content_type, "application/json");
  5620. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5621. }
  5622. })
  5623. .Post("/empty",
  5624. [&](const Request &req, Response &res) {
  5625. EXPECT_EQ(req.body, "");
  5626. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5627. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5628. res.set_content("empty", "text/plain");
  5629. })
  5630. .Post("/empty-no-content-type",
  5631. [&](const Request &req, Response &res) {
  5632. EXPECT_EQ(req.body, "");
  5633. EXPECT_FALSE(req.has_header("Content-Type"));
  5634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5635. res.set_content("empty-no-content-type", "text/plain");
  5636. })
  5637. .Post("/path-only",
  5638. [&](const Request &req, Response &res) {
  5639. EXPECT_EQ(req.body, "");
  5640. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5642. res.set_content("path-only", "text/plain");
  5643. })
  5644. .Post("/path-headers-only",
  5645. [&](const Request &req, Response &res) {
  5646. EXPECT_EQ(req.body, "");
  5647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5649. EXPECT_EQ("world", req.get_header_value("hello"));
  5650. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5651. res.set_content("path-headers-only", "text/plain");
  5652. })
  5653. .Post("/post-large",
  5654. [&](const Request &req, Response &res) {
  5655. EXPECT_EQ(req.body, LARGE_DATA);
  5656. res.set_content(req.body, "text/plain");
  5657. })
  5658. .Post("/post-loopback",
  5659. [&](const Request &, Response &res,
  5660. ContentReader const &content_reader) {
  5661. std::string body;
  5662. content_reader([&](const char *data, size_t data_length) {
  5663. body.append(data, data_length);
  5664. return true;
  5665. });
  5666. res.set_content(body, "text/plain");
  5667. })
  5668. .Put("/put-loopback",
  5669. [&](const Request &, Response &res,
  5670. ContentReader const &content_reader) {
  5671. std::string body;
  5672. content_reader([&](const char *data, size_t data_length) {
  5673. body.append(data, data_length);
  5674. return true;
  5675. });
  5676. res.set_content(body, "text/plain");
  5677. })
  5678. .Patch("/patch-loopback",
  5679. [&](const Request &, Response &res,
  5680. ContentReader const &content_reader) {
  5681. std::string body;
  5682. content_reader([&](const char *data, size_t data_length) {
  5683. body.append(data, data_length);
  5684. return true;
  5685. });
  5686. res.set_content(body, "text/plain");
  5687. })
  5688. .Put("/empty-no-content-type",
  5689. [&](const Request &req, Response &res) {
  5690. EXPECT_EQ(req.body, "");
  5691. EXPECT_FALSE(req.has_header("Content-Type"));
  5692. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5693. res.set_content("empty-no-content-type", "text/plain");
  5694. })
  5695. .Put("/put",
  5696. [&](const Request &req, Response &res) {
  5697. EXPECT_EQ(req.body, "PUT");
  5698. res.set_content(req.body, "text/plain");
  5699. })
  5700. .Put("/put-large",
  5701. [&](const Request &req, Response &res) {
  5702. EXPECT_EQ(req.body, LARGE_DATA);
  5703. res.set_content(req.body, "text/plain");
  5704. })
  5705. .Patch("/patch",
  5706. [&](const Request &req, Response &res) {
  5707. EXPECT_EQ(req.body, "PATCH");
  5708. res.set_content(req.body, "text/plain");
  5709. })
  5710. .Delete("/delete",
  5711. [&](const Request & /*req*/, Response &res) {
  5712. res.set_content("DELETE", "text/plain");
  5713. })
  5714. .Delete("/delete-body",
  5715. [&](const Request &req, Response &res) {
  5716. EXPECT_EQ(req.body, "content");
  5717. res.set_content(req.body, "text/plain");
  5718. })
  5719. .Options(R"(\*)",
  5720. [&](const Request & /*req*/, Response &res) {
  5721. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5722. })
  5723. .CustomRoute("PROPFIND", "/dav/:id",
  5724. [&](const Request &req, Response &res) {
  5725. res.set_header("x-body-size",
  5726. std::to_string(req.body.size()));
  5727. res.set_header("x-matched-route", req.matched_route);
  5728. res.set_header("x-dav-id", req.path_params.at("id"));
  5729. res.status = StatusCode::MultiStatus_207;
  5730. res.set_content(req.body, "application/xml");
  5731. })
  5732. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5733. [&](const Request &req, Response &res) {
  5734. res.set_header("x-dav-match", req.matches[1]);
  5735. res.status = StatusCode::MultiStatus_207;
  5736. })
  5737. .CustomRoute("MKCOL", "/dav-mkcol",
  5738. [&](const Request &req, Response &res) {
  5739. EXPECT_TRUE(req.body.empty());
  5740. res.status = StatusCode::Created_201;
  5741. })
  5742. .CustomRoute(
  5743. "REPORT", "/dav-report",
  5744. [&](const Request & /*req*/, Response &res,
  5745. const ContentReader &content_reader) {
  5746. std::string body;
  5747. content_reader([&](const char *data, size_t data_length) {
  5748. body.append(data, data_length);
  5749. return true;
  5750. });
  5751. res.set_header("x-body-size", std::to_string(body.size()));
  5752. res.status = StatusCode::MultiStatus_207;
  5753. res.set_content(body, "application/xml");
  5754. })
  5755. .Get("/request-target",
  5756. [&](const Request &req, Response & /*res*/) {
  5757. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5758. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5759. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5760. })
  5761. .Get("/long-query-value",
  5762. [&](const Request &req, Response & /*res*/) {
  5763. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5764. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5765. })
  5766. .Get("/too-long-query-value",
  5767. [&](const Request &req, Response & /*res*/) {
  5768. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5769. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5770. })
  5771. .Get("/array-param",
  5772. [&](const Request &req, Response & /*res*/) {
  5773. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5774. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5775. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5776. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5777. })
  5778. .Get("/array-param-values",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. auto values = req.get_param_values("array");
  5781. EXPECT_EQ(3u, values.size());
  5782. EXPECT_EQ("value1", values[0]);
  5783. EXPECT_EQ("value2", values[1]);
  5784. EXPECT_EQ("value3", values[2]);
  5785. auto empty = req.get_param_values("nonexistent");
  5786. EXPECT_TRUE(empty.empty());
  5787. })
  5788. .Post("/validate-no-multiple-headers",
  5789. [&](const Request &req, Response & /*res*/) {
  5790. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5791. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5792. })
  5793. .Post("/content_receiver",
  5794. [&](const Request &req, Response &res,
  5795. const ContentReader &content_reader) {
  5796. if (req.is_multipart_form_data()) {
  5797. std::vector<FormData> items;
  5798. content_reader(
  5799. [&](const FormData &file) {
  5800. items.push_back(file);
  5801. return true;
  5802. },
  5803. [&](const char *data, size_t data_length) {
  5804. items.back().content.append(data, data_length);
  5805. return true;
  5806. });
  5807. EXPECT_EQ(5u, items.size());
  5808. {
  5809. const auto &file = get_file_value(items, "text1");
  5810. EXPECT_TRUE(file.filename.empty());
  5811. EXPECT_EQ("text default", file.content);
  5812. }
  5813. {
  5814. const auto &file = get_file_value(items, "text2");
  5815. EXPECT_TRUE(file.filename.empty());
  5816. EXPECT_EQ("aωb", file.content);
  5817. }
  5818. {
  5819. const auto &file = get_file_value(items, "file1");
  5820. EXPECT_EQ("hello.txt", file.filename);
  5821. EXPECT_EQ("text/plain", file.content_type);
  5822. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5823. }
  5824. {
  5825. const auto &file = get_file_value(items, "file2");
  5826. EXPECT_EQ("world.json", file.filename);
  5827. EXPECT_EQ("application/json", file.content_type);
  5828. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5829. }
  5830. {
  5831. const auto &file = get_file_value(items, "file3");
  5832. EXPECT_TRUE(file.filename.empty());
  5833. EXPECT_EQ("application/octet-stream", file.content_type);
  5834. EXPECT_EQ(0u, file.content.size());
  5835. }
  5836. } else {
  5837. std::string body;
  5838. content_reader([&](const char *data, size_t data_length) {
  5839. EXPECT_EQ(7U, data_length);
  5840. body.append(data, data_length);
  5841. return true;
  5842. });
  5843. EXPECT_EQ(body, "content");
  5844. res.set_content(body, "text/plain");
  5845. }
  5846. })
  5847. .Put("/content_receiver",
  5848. [&](const Request & /*req*/, Response &res,
  5849. const ContentReader &content_reader) {
  5850. std::string body;
  5851. content_reader([&](const char *data, size_t data_length) {
  5852. body.append(data, data_length);
  5853. return true;
  5854. });
  5855. EXPECT_EQ(body, "content");
  5856. res.set_content(body, "text/plain");
  5857. })
  5858. .Patch("/content_receiver",
  5859. [&](const Request & /*req*/, Response &res,
  5860. const ContentReader &content_reader) {
  5861. std::string body;
  5862. content_reader([&](const char *data, size_t data_length) {
  5863. body.append(data, data_length);
  5864. return true;
  5865. });
  5866. EXPECT_EQ(body, "content");
  5867. res.set_content(body, "text/plain");
  5868. })
  5869. .Post("/query-string-and-body",
  5870. [&](const Request &req, Response & /*res*/) {
  5871. ASSERT_TRUE(req.has_param("key"));
  5872. EXPECT_EQ(req.get_param_value("key"), "value");
  5873. EXPECT_EQ(req.body, "content");
  5874. })
  5875. .Get("/last-request",
  5876. [&](const Request &req, Response & /*res*/) {
  5877. EXPECT_EQ("close", req.get_header_value("Connection"));
  5878. })
  5879. .Get(R"(/redirect/(\d+))",
  5880. [&](const Request &req, Response &res) {
  5881. auto num = std::stoi(req.matches[1]) + 1;
  5882. std::string url = "/redirect/" + std::to_string(num);
  5883. res.set_redirect(url);
  5884. })
  5885. .Post("/binary",
  5886. [&](const Request &req, Response &res) {
  5887. EXPECT_EQ(4U, req.body.size());
  5888. EXPECT_EQ("application/octet-stream",
  5889. req.get_header_value("Content-Type"));
  5890. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5891. res.set_content(req.body, "application/octet-stream");
  5892. })
  5893. .Put("/binary",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_EQ(4U, req.body.size());
  5896. EXPECT_EQ("application/octet-stream",
  5897. req.get_header_value("Content-Type"));
  5898. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5899. res.set_content(req.body, "application/octet-stream");
  5900. })
  5901. .Patch("/binary",
  5902. [&](const Request &req, Response &res) {
  5903. EXPECT_EQ(4U, req.body.size());
  5904. EXPECT_EQ("application/octet-stream",
  5905. req.get_header_value("Content-Type"));
  5906. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5907. res.set_content(req.body, "application/octet-stream");
  5908. })
  5909. .Delete("/binary",
  5910. [&](const Request &req, Response &res) {
  5911. EXPECT_EQ(4U, req.body.size());
  5912. EXPECT_EQ("application/octet-stream",
  5913. req.get_header_value("Content-Type"));
  5914. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5915. res.set_content(req.body, "application/octet-stream");
  5916. })
  5917. .Get("/issue1772",
  5918. [&](const Request & /*req*/, Response &res) {
  5919. res.status = 401;
  5920. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5921. })
  5922. .Delete("/issue609",
  5923. [](const httplib::Request &, httplib::Response &res,
  5924. const httplib::ContentReader &) {
  5925. res.set_content("ok", "text/plain");
  5926. })
  5927. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5928. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5929. .Get("/compress",
  5930. [&](const Request & /*req*/, Response &res) {
  5931. res.set_content(
  5932. "12345678901234567890123456789012345678901234567890123456789"
  5933. "01234567890123456789012345678901234567890",
  5934. "text/plain");
  5935. })
  5936. .Get("/compress-with-charset",
  5937. [&](const Request & /*req*/, Response &res) {
  5938. res.set_content(
  5939. "12345678901234567890123456789012345678901234567890123456789"
  5940. "01234567890123456789012345678901234567890",
  5941. "application/json; charset=utf-8");
  5942. })
  5943. .Get("/nocompress",
  5944. [&](const Request & /*req*/, Response &res) {
  5945. res.set_content(
  5946. "12345678901234567890123456789012345678901234567890123456789"
  5947. "01234567890123456789012345678901234567890",
  5948. "application/octet-stream");
  5949. })
  5950. .Post("/compress-multipart",
  5951. [&](const Request &req, Response & /*res*/) {
  5952. EXPECT_EQ(2u, req.form.fields.size());
  5953. ASSERT_TRUE(!req.form.has_field("???"));
  5954. {
  5955. const auto &text = req.form.get_field("key1");
  5956. EXPECT_EQ("test", text);
  5957. }
  5958. {
  5959. const auto &text = req.form.get_field("key2");
  5960. EXPECT_EQ("--abcdefg123", text);
  5961. }
  5962. })
  5963. #endif
  5964. ;
  5965. persons_["john"] = "programmer";
  5966. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5967. svr_.wait_until_ready();
  5968. }
  5969. virtual void TearDown() {
  5970. svr_.stop();
  5971. if (!request_threads_.empty()) {
  5972. std::this_thread::sleep_for(std::chrono::seconds(1));
  5973. for (auto &t : request_threads_) {
  5974. t.join();
  5975. }
  5976. }
  5977. t_.join();
  5978. }
  5979. map<string, string> persons_;
  5980. #ifdef CPPHTTPLIB_SSL_ENABLED
  5981. SSLClient cli_;
  5982. SSLServer svr_;
  5983. #else
  5984. Client cli_;
  5985. Server svr_;
  5986. #endif
  5987. thread t_;
  5988. std::vector<thread> request_threads_;
  5989. };
  5990. TEST_F(ServerTest, GetMethod200) {
  5991. auto res = cli_.Get("/hi");
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ("HTTP/1.1", res->version);
  5994. EXPECT_EQ(StatusCode::OK_200, res->status);
  5995. EXPECT_EQ("OK", res->reason);
  5996. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5997. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5998. EXPECT_EQ("Hello World!", res->body);
  5999. }
  6000. TEST_F(ServerTest, GetEmptyFile) {
  6001. auto res = cli_.Get("/empty_file");
  6002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6003. EXPECT_EQ(StatusCode::OK_200, res->status);
  6004. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6005. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6006. EXPECT_EQ("", res->body);
  6007. }
  6008. TEST_F(ServerTest, GetFileContent) {
  6009. auto res = cli_.Get("/file_content");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6014. EXPECT_EQ("test.html", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetFileContentWithRange) {
  6017. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6022. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6023. EXPECT_EQ("est", res->body);
  6024. }
  6025. TEST_F(ServerTest, GetFileContentWithContentType) {
  6026. auto res = cli_.Get("/file_content_with_content_type");
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. EXPECT_EQ(StatusCode::OK_200, res->status);
  6029. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6030. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6031. EXPECT_EQ("file\n", res->body);
  6032. }
  6033. TEST_F(ServerTest, GetInvalidFileContent) {
  6034. auto res = cli_.Get("/invalid_file_content");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6037. }
  6038. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6039. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ("HTTP/1.1", res->version);
  6042. EXPECT_EQ(StatusCode::OK_200, res->status);
  6043. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6044. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6045. EXPECT_EQ("Hello World!", res->body);
  6046. }
  6047. TEST_F(ServerTest, GetMethod302) {
  6048. auto res = cli_.Get("/");
  6049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6050. EXPECT_EQ(StatusCode::Found_302, res->status);
  6051. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6052. }
  6053. TEST_F(ServerTest, GetMethod302Redirect) {
  6054. cli_.set_follow_location(true);
  6055. auto res = cli_.Get("/");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::OK_200, res->status);
  6058. EXPECT_EQ("Hello World!", res->body);
  6059. EXPECT_EQ("/hi", res->location);
  6060. }
  6061. TEST_F(ServerTest, GetMethod404) {
  6062. auto res = cli_.Get("/invalid");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6065. }
  6066. TEST_F(ServerTest, HeadMethod200) {
  6067. auto res = cli_.Head("/hi");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::OK_200, res->status);
  6070. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6071. EXPECT_TRUE(res->body.empty());
  6072. }
  6073. TEST_F(ServerTest, HeadMethod200Static) {
  6074. auto res = cli_.Head("/mount/dir/index.html");
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6078. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6079. EXPECT_TRUE(res->body.empty());
  6080. }
  6081. TEST_F(ServerTest, HeadMethod404) {
  6082. auto res = cli_.Head("/invalid");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6085. EXPECT_TRUE(res->body.empty());
  6086. }
  6087. TEST_F(ServerTest, GetMethodPersonJohn) {
  6088. auto res = cli_.Get("/person/john");
  6089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6090. EXPECT_EQ(StatusCode::OK_200, res->status);
  6091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6092. EXPECT_EQ("programmer", res->body);
  6093. }
  6094. TEST_F(ServerTest, PostMethod1) {
  6095. auto res = cli_.Get("/person/john1");
  6096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6097. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6098. res = cli_.Post("/person", "name=john1&note=coder",
  6099. "application/x-www-form-urlencoded");
  6100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6101. ASSERT_EQ(StatusCode::OK_200, res->status);
  6102. res = cli_.Get("/person/john1");
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. ASSERT_EQ(StatusCode::OK_200, res->status);
  6105. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6106. ASSERT_EQ("coder", res->body);
  6107. }
  6108. TEST_F(ServerTest, PostMethod2) {
  6109. auto res = cli_.Get("/person/john2");
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6112. Params params;
  6113. params.emplace("name", "john2");
  6114. params.emplace("note", "coder");
  6115. res = cli_.Post("/person", params);
  6116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6117. ASSERT_EQ(StatusCode::OK_200, res->status);
  6118. res = cli_.Get("/person/john2");
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. ASSERT_EQ(StatusCode::OK_200, res->status);
  6121. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6122. ASSERT_EQ("coder", res->body);
  6123. }
  6124. TEST_F(ServerTest, PutMethod3) {
  6125. auto res = cli_.Get("/person/john3");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6128. Params params;
  6129. params.emplace("name", "john3");
  6130. params.emplace("note", "coder");
  6131. res = cli_.Put("/person", params);
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. ASSERT_EQ(StatusCode::OK_200, res->status);
  6134. res = cli_.Get("/person/john3");
  6135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6136. ASSERT_EQ(StatusCode::OK_200, res->status);
  6137. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6138. ASSERT_EQ("coder", res->body);
  6139. }
  6140. TEST_F(ServerTest, DeleteMethod1) {
  6141. auto res = cli_.Get("/person/john4");
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6144. Params params;
  6145. params.emplace("name", "john4");
  6146. params.emplace("note", "coder");
  6147. res = cli_.Post("/person", params);
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. ASSERT_EQ(StatusCode::OK_200, res->status);
  6150. res = cli_.Get("/person/john4");
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. ASSERT_EQ(StatusCode::OK_200, res->status);
  6153. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6154. ASSERT_EQ("coder", res->body);
  6155. Params delete_params;
  6156. delete_params.emplace("name", "john4");
  6157. res = cli_.Delete("/person", delete_params);
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ("DELETED", res->body);
  6161. res = cli_.Get("/person/john4");
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6164. }
  6165. TEST_F(ServerTest, DeleteMethod2) {
  6166. auto res = cli_.Get("/person/john5");
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6169. Params params;
  6170. params.emplace("name", "john5");
  6171. params.emplace("note", "developer");
  6172. res = cli_.Post("/person", params);
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. ASSERT_EQ(StatusCode::OK_200, res->status);
  6175. res = cli_.Get("/person/john5");
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. ASSERT_EQ(StatusCode::OK_200, res->status);
  6178. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6179. ASSERT_EQ("developer", res->body);
  6180. Params delete_params;
  6181. delete_params.emplace("name", "john5");
  6182. Headers headers;
  6183. headers.emplace("Custom-Header", "test-value");
  6184. res = cli_.Delete("/person", headers, delete_params);
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. ASSERT_EQ(StatusCode::OK_200, res->status);
  6187. ASSERT_EQ("DELETED", res->body);
  6188. res = cli_.Get("/person/john5");
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6191. }
  6192. TEST_F(ServerTest, DeleteMethod3) {
  6193. auto res = cli_.Get("/person/john6");
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6196. Params params;
  6197. params.emplace("name", "john6");
  6198. params.emplace("note", "tester");
  6199. res = cli_.Post("/person", params);
  6200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6201. ASSERT_EQ(StatusCode::OK_200, res->status);
  6202. res = cli_.Get("/person/john6");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. ASSERT_EQ(StatusCode::OK_200, res->status);
  6205. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6206. ASSERT_EQ("tester", res->body);
  6207. Params delete_params;
  6208. delete_params.emplace("name", "john6");
  6209. Headers headers;
  6210. headers.emplace("Custom-Header", "test-value");
  6211. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. ASSERT_EQ(StatusCode::OK_200, res->status);
  6214. ASSERT_EQ("DELETED", res->body);
  6215. res = cli_.Get("/person/john6");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6218. }
  6219. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6220. Params params;
  6221. params.emplace("json", JSON_DATA);
  6222. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::OK_200, res->status);
  6225. ASSERT_EQ(JSON_DATA, res->body);
  6226. }
  6227. TEST_F(ServerTest, PostEmptyContent) {
  6228. auto res = cli_.Post("/empty", "", "text/plain");
  6229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6230. ASSERT_EQ(StatusCode::OK_200, res->status);
  6231. ASSERT_EQ("empty", res->body);
  6232. }
  6233. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6234. auto res = cli_.Post("/empty-no-content-type");
  6235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6236. ASSERT_EQ(StatusCode::OK_200, res->status);
  6237. ASSERT_EQ("empty-no-content-type", res->body);
  6238. }
  6239. TEST_F(ServerTest, PostPathOnly) {
  6240. auto res = cli_.Post("/path-only");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. ASSERT_EQ(StatusCode::OK_200, res->status);
  6243. ASSERT_EQ("path-only", res->body);
  6244. }
  6245. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6246. auto res = cli_.Post("/path-headers-only",
  6247. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. ASSERT_EQ(StatusCode::OK_200, res->status);
  6250. ASSERT_EQ("path-headers-only", res->body);
  6251. }
  6252. TEST_F(ServerTest, PostLarge) {
  6253. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. ASSERT_EQ(StatusCode::OK_200, res->status);
  6256. EXPECT_EQ(LARGE_DATA, res->body);
  6257. }
  6258. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6259. auto res = cli_.Put("/empty-no-content-type");
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. ASSERT_EQ(StatusCode::OK_200, res->status);
  6262. ASSERT_EQ("empty-no-content-type", res->body);
  6263. }
  6264. TEST_F(ServerTest, GetMethodDir) {
  6265. auto res = cli_.Get("/dir/");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6269. auto body = R"(<html>
  6270. <head>
  6271. </head>
  6272. <body>
  6273. <a href="/dir/test.html">Test</a>
  6274. <a href="/hi">hi</a>
  6275. </body>
  6276. </html>
  6277. )";
  6278. EXPECT_EQ(body, res->body);
  6279. }
  6280. TEST_F(ServerTest, GetMethodDirTest) {
  6281. auto res = cli_.Get("/dir/test.html");
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. EXPECT_EQ(StatusCode::OK_200, res->status);
  6284. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6285. EXPECT_EQ("test.html", res->body);
  6286. }
  6287. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6288. auto res = cli_.Get("/dir/../dir/test.html");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6292. EXPECT_EQ("test.html", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodInvalidPath) {
  6295. auto res = cli_.Get("/dir/../test.html");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6298. }
  6299. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6300. auto res = cli_.Get("/../www/dir/test.html");
  6301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6302. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6303. }
  6304. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6305. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6307. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6308. }
  6309. TEST_F(ServerTest, GetMethodDirMountTest) {
  6310. auto res = cli_.Get("/mount/dir/test.html");
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6314. EXPECT_EQ("test.html", res->body);
  6315. }
  6316. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6317. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6321. EXPECT_EQ("test.html", res->body);
  6322. }
  6323. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6324. auto res = cli_.Get("/mount/dir/../test.html");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6327. }
  6328. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6329. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6332. }
  6333. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6334. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6337. }
  6338. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6339. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6341. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6342. }
  6343. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6344. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6347. }
  6348. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6349. auto res = cli_.Get("/mount/dir");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6352. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6353. }
  6354. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6355. auto res = cli_.Get("//dir");
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6358. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6359. }
  6360. TEST_F(ServerTest, PostMethod303) {
  6361. auto res = cli_.Post("/1", "body", "text/plain");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6364. EXPECT_EQ("/2", res->get_header_value("Location"));
  6365. }
  6366. TEST_F(ServerTest, PostMethod303Redirect) {
  6367. cli_.set_follow_location(true);
  6368. auto res = cli_.Post("/1", "body", "text/plain");
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::OK_200, res->status);
  6371. EXPECT_EQ("redirected.", res->body);
  6372. EXPECT_EQ("/2", res->location);
  6373. }
  6374. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6375. auto res = cli_.Get("/dir/test.abcde");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::OK_200, res->status);
  6378. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6379. EXPECT_EQ("abcde", res->body);
  6380. }
  6381. TEST_F(ServerTest, StaticFileRange) {
  6382. auto res =
  6383. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6386. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6387. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6388. EXPECT_EQ(true, res->has_header("Content-Range"));
  6389. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6390. EXPECT_EQ(std::string("cd"), res->body);
  6391. }
  6392. TEST_F(ServerTest, StaticFileRanges) {
  6393. auto res = cli_.Get("/dir/test.abcde",
  6394. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6397. EXPECT_TRUE(
  6398. res->get_header_value("Content-Type")
  6399. .find(
  6400. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6401. 0);
  6402. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6403. }
  6404. TEST_F(ServerTest, StaticFileRangeHead) {
  6405. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6408. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6409. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6410. EXPECT_EQ(true, res->has_header("Content-Range"));
  6411. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6412. }
  6413. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6414. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6417. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6418. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6419. EXPECT_EQ(true, res->has_header("Content-Range"));
  6420. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6421. res->get_header_value("Content-Range"));
  6422. EXPECT_EQ("LAST\n", res->body);
  6423. }
  6424. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6425. auto res =
  6426. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6430. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6431. EXPECT_EQ(true, res->has_header("Content-Range"));
  6432. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6433. }
  6434. TEST_F(ServerTest, StaticFileBigFile) {
  6435. auto res = cli_.Get("/dir/1MB.txt");
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ(StatusCode::OK_200, res->status);
  6438. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6439. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6440. }
  6441. TEST_F(ServerTest, InvalidBaseDirMount) {
  6442. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6443. }
  6444. TEST_F(ServerTest, Binary) {
  6445. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6446. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6447. "application/octet-stream");
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. ASSERT_EQ(StatusCode::OK_200, res->status);
  6450. ASSERT_EQ(4U, res->body.size());
  6451. res = cli_.Put("/binary", binary.data(), binary.size(),
  6452. "application/octet-stream");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. ASSERT_EQ(StatusCode::OK_200, res->status);
  6455. ASSERT_EQ(4U, res->body.size());
  6456. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6457. "application/octet-stream");
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. ASSERT_EQ(StatusCode::OK_200, res->status);
  6460. ASSERT_EQ(4U, res->body.size());
  6461. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6462. "application/octet-stream");
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. ASSERT_EQ(StatusCode::OK_200, res->status);
  6465. ASSERT_EQ(4U, res->body.size());
  6466. }
  6467. TEST_F(ServerTest, BinaryString) {
  6468. auto binary = std::string("\x00\x01\x02\x03", 4);
  6469. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. ASSERT_EQ(4U, res->body.size());
  6473. res = cli_.Put("/binary", binary, "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. ASSERT_EQ(StatusCode::OK_200, res->status);
  6480. ASSERT_EQ(4U, res->body.size());
  6481. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. ASSERT_EQ(StatusCode::OK_200, res->status);
  6484. ASSERT_EQ(4U, res->body.size());
  6485. }
  6486. TEST_F(ServerTest, EmptyRequest) {
  6487. auto res = cli_.Get("");
  6488. ASSERT_TRUE(!res);
  6489. EXPECT_EQ(Error::Connection, res.error());
  6490. }
  6491. TEST_F(ServerTest, LongRequest) {
  6492. std::string request;
  6493. for (size_t i = 0; i < 545; i++) {
  6494. request += "/TooLongRequest";
  6495. }
  6496. request += "OK";
  6497. auto res = cli_.Get(request.c_str());
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6500. }
  6501. TEST_F(ServerTest, TooLongRequest) {
  6502. std::string request;
  6503. for (size_t i = 0; i < 546; i++) {
  6504. request += "/TooLongRequest";
  6505. }
  6506. request += "_NG";
  6507. auto start = std::chrono::high_resolution_clock::now();
  6508. cli_.set_keep_alive(true);
  6509. auto res = cli_.Get(request.c_str());
  6510. auto end = std::chrono::high_resolution_clock::now();
  6511. auto elapsed =
  6512. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6513. .count();
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6516. EXPECT_LE(elapsed, 1000);
  6517. EXPECT_EQ("close", res->get_header_value("Connection"));
  6518. EXPECT_FALSE(cli_.is_socket_open());
  6519. }
  6520. TEST_F(ServerTest, AlmostTooLongRequest) {
  6521. // test for #2046 - URI length check shouldn't include other content on req
  6522. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6523. // leading /, space, HTTP/1.1)
  6524. std::string request =
  6525. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6526. auto res = cli_.Get(request.c_str());
  6527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6529. }
  6530. TEST_F(ServerTest, LongHeader) {
  6531. Request req;
  6532. req.method = "GET";
  6533. req.path = "/hi";
  6534. std::string host_and_port;
  6535. host_and_port += HOST;
  6536. host_and_port += ":";
  6537. host_and_port += std::to_string(PORT);
  6538. req.headers.emplace("Host", host_and_port.c_str());
  6539. req.headers.emplace("Accept", "*/*");
  6540. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6541. req.headers.emplace(
  6542. "Header-Name",
  6543. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6544. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@");
  6572. auto res = std::make_shared<Response>();
  6573. auto error = Error::Success;
  6574. auto ret = cli_.send(req, *res, error);
  6575. ASSERT_TRUE(ret);
  6576. EXPECT_EQ(StatusCode::OK_200, res->status);
  6577. }
  6578. TEST_F(ServerTest, LongQueryValue) {
  6579. auto start = std::chrono::high_resolution_clock::now();
  6580. cli_.set_keep_alive(true);
  6581. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6582. auto end = std::chrono::high_resolution_clock::now();
  6583. auto elapsed =
  6584. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6585. .count();
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6588. EXPECT_LE(elapsed, 1000);
  6589. EXPECT_EQ("close", res->get_header_value("Connection"));
  6590. EXPECT_FALSE(cli_.is_socket_open());
  6591. }
  6592. TEST_F(ServerTest, TooLongQueryValue) {
  6593. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6594. ASSERT_FALSE(res);
  6595. EXPECT_EQ(Error::Read, res.error());
  6596. }
  6597. TEST_F(ServerTest, TooLongHeader) {
  6598. Request req;
  6599. req.method = "GET";
  6600. req.path = "/hi";
  6601. std::string host_and_port;
  6602. host_and_port += HOST;
  6603. host_and_port += ":";
  6604. host_and_port += std::to_string(PORT);
  6605. req.headers.emplace("Host", host_and_port.c_str());
  6606. req.headers.emplace("Accept", "*/*");
  6607. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6608. req.headers.emplace(
  6609. "Header-Name",
  6610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@");
  6639. auto res = std::make_shared<Response>();
  6640. auto error = Error::Success;
  6641. auto ret = cli_.send(req, *res, error);
  6642. ASSERT_TRUE(ret);
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. }
  6645. TEST_F(ServerTest, HeaderCountAtLimit) {
  6646. // Test with headers just under the 100 limit
  6647. httplib::Headers headers;
  6648. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6649. // This should keep us just under the 100 header limit
  6650. for (int i = 0; i < 95; i++) {
  6651. std::string name = "X-Test-Header-" + std::to_string(i);
  6652. std::string value = "value" + std::to_string(i);
  6653. headers.emplace(name, value);
  6654. }
  6655. // This should work fine as we're under the limit
  6656. auto res = cli_.Get("/hi", headers);
  6657. EXPECT_TRUE(res);
  6658. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6659. }
  6660. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6661. // Test with many headers to exceed the 100 limit
  6662. httplib::Headers headers;
  6663. // Add 150 headers to definitely exceed the 100 limit
  6664. for (int i = 0; i < 150; i++) {
  6665. std::string name = "X-Test-Header-" + std::to_string(i);
  6666. std::string value = "value" + std::to_string(i);
  6667. headers.emplace(name, value);
  6668. }
  6669. // This should fail due to exceeding header count limit
  6670. cli_.set_keep_alive(true);
  6671. auto res = cli_.Get("/hi", headers);
  6672. // The server should respond with 400 Bad Request
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6675. EXPECT_EQ("close", res->get_header_value("Connection"));
  6676. EXPECT_FALSE(cli_.is_socket_open());
  6677. }
  6678. TEST_F(ServerTest, PercentEncoding) {
  6679. auto res = cli_.Get("/e%6edwith%");
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::OK_200, res->status);
  6682. }
  6683. TEST_F(ServerTest, PercentEncodingUnicode) {
  6684. auto res = cli_.Get("/e%u006edwith%");
  6685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6686. EXPECT_EQ(StatusCode::OK_200, res->status);
  6687. }
  6688. TEST_F(ServerTest, InvalidPercentEncoding) {
  6689. auto res = cli_.Get("/%endwith%");
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6692. }
  6693. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6694. auto res = cli_.Get("/%uendwith%");
  6695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6696. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6697. }
  6698. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6699. auto res = cli_.Get("/hello?aaa=bbb%");
  6700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6702. }
  6703. TEST_F(ServerTest, PlusSignEncoding) {
  6704. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6706. EXPECT_EQ(StatusCode::OK_200, res->status);
  6707. EXPECT_EQ("a +b", res->body);
  6708. }
  6709. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6710. // This test simulates a potential DoS attack using many headers
  6711. // to verify our security fix prevents memory exhaustion
  6712. httplib::Headers attack_headers;
  6713. // Attempt to add many headers like an attacker would (200 headers to far
  6714. // exceed limit)
  6715. for (int i = 0; i < 200; i++) {
  6716. std::string name = "X-Attack-Header-" + std::to_string(i);
  6717. std::string value = "attack_payload_" + std::to_string(i);
  6718. attack_headers.emplace(name, value);
  6719. }
  6720. // Try to POST with excessive headers
  6721. cli_.set_keep_alive(true);
  6722. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6723. // Should either fail or return 400 Bad Request due to security limit
  6724. if (res) {
  6725. // If we get a response, it should be 400 Bad Request
  6726. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6727. EXPECT_EQ("close", res->get_header_value("Connection"));
  6728. }
  6729. EXPECT_FALSE(cli_.is_socket_open());
  6730. }
  6731. TEST_F(ServerTest, MultipartFormData) {
  6732. UploadFormDataItems items = {
  6733. {"text1", "text default", "", ""},
  6734. {"text2", "aωb", "", ""},
  6735. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6736. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6737. {"file3", "", "", "application/octet-stream"},
  6738. {"file4", "", "", " application/json tmp-string "}};
  6739. auto res = cli_.Post("/multipart", items);
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. }
  6743. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6744. UploadFormDataItems items = {
  6745. {"text", "default text", "", ""},
  6746. {"multi_text1", "aaaaa", "", ""},
  6747. {"multi_text1", "bbbbb", "", ""},
  6748. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6749. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6750. "application/json"},
  6751. };
  6752. auto res = cli_.Post("/multipart/multi_file_values", items);
  6753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6754. EXPECT_EQ(StatusCode::OK_200, res->status);
  6755. }
  6756. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6757. auto res = cli_.Get("/hi");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6761. EXPECT_EQ("Hello World!", res->body);
  6762. }
  6763. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6764. Request req;
  6765. req.method = "POST";
  6766. req.path = "/chunked";
  6767. std::string host_and_port;
  6768. host_and_port += HOST;
  6769. host_and_port += ":";
  6770. host_and_port += std::to_string(PORT);
  6771. req.headers.emplace("Host", host_and_port.c_str());
  6772. req.headers.emplace("Accept", "*/*");
  6773. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6774. req.headers.emplace("Content-Type", "text/plain");
  6775. req.headers.emplace("Content-Length", "0");
  6776. req.headers.emplace(
  6777. "Transfer-Encoding",
  6778. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6779. // Client does not chunk, so make a chunked body manually.
  6780. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6781. auto res = std::make_shared<Response>();
  6782. auto error = Error::Success;
  6783. auto ret = cli_.send(req, *res, error);
  6784. ASSERT_TRUE(ret);
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. }
  6787. template <typename ClientT>
  6788. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6789. int expected_status) {
  6790. Request req;
  6791. req.method = "POST";
  6792. req.path = "/chunked";
  6793. std::string host_and_port;
  6794. host_and_port += HOST;
  6795. host_and_port += ":";
  6796. host_and_port += std::to_string(PORT);
  6797. req.headers.emplace("Host", host_and_port.c_str());
  6798. req.headers.emplace("Content-Length", "0");
  6799. req.headers.emplace("Transfer-Encoding", "chunked");
  6800. req.body = body;
  6801. auto res = std::make_shared<Response>();
  6802. auto error = Error::Success;
  6803. ASSERT_TRUE(cli.send(req, *res, error));
  6804. EXPECT_EQ(expected_status, res->status);
  6805. }
  6806. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6807. // rather than treat them as valid lengths.
  6808. template <typename ClientT>
  6809. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6810. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6811. }
  6812. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6813. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6814. }
  6815. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6816. expect_chunked_body_rejected(
  6817. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6818. }
  6819. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6820. // chunk-size line carries no CR, LF or other control character ahead of its
  6821. // terminator. Such a line must be refused rather than read as extension text.
  6822. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6823. expect_chunked_body_rejected(
  6824. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6825. }
  6826. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6827. expect_chunked_body_rejected(
  6828. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6829. }
  6830. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6831. expect_chunked_body_rejected(
  6832. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6833. }
  6834. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6835. // The literal stays split: a hex escape consumes every hex digit that
  6836. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6837. expect_chunked_body_rejected(
  6838. cli_, "4;a\x01"
  6839. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, AcceptsChunkExtension) {
  6842. expect_chunked_body_status(cli_,
  6843. "4;name=value\r\ndech\r\n"
  6844. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6845. "0;last\r\n\r\n",
  6846. StatusCode::OK_200);
  6847. }
  6848. TEST_F(ServerTest, GetStreamed2) {
  6849. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6852. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6853. EXPECT_EQ(true, res->has_header("Content-Range"));
  6854. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6855. EXPECT_EQ(std::string("ab"), res->body);
  6856. }
  6857. TEST_F(ServerTest, GetStreamed) {
  6858. auto res = cli_.Get("/streamed");
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. EXPECT_EQ(StatusCode::OK_200, res->status);
  6861. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6862. EXPECT_EQ(std::string("aaabbb"), res->body);
  6863. }
  6864. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6865. auto res = cli_.Get("/streamed-without-length",
  6866. Headers{make_range_header({{0, -1}})});
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. EXPECT_EQ(false, res->has_header("Content-Length"));
  6870. EXPECT_EQ(false, res->has_header("Content-Range"));
  6871. EXPECT_EQ(std::string("abcdefg"), res->body);
  6872. }
  6873. TEST_F(ServerTest, GetStreamedWithRange1) {
  6874. auto res =
  6875. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6877. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6878. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6879. EXPECT_EQ(true, res->has_header("Content-Range"));
  6880. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6881. EXPECT_EQ(std::string("def"), res->body);
  6882. }
  6883. TEST_F(ServerTest, GetStreamedWithRange2) {
  6884. auto res =
  6885. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6888. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6889. EXPECT_EQ(true, res->has_header("Content-Range"));
  6890. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6891. EXPECT_EQ(std::string("bcdefg"), res->body);
  6892. }
  6893. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6894. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6896. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6897. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6898. EXPECT_EQ(true, res->has_header("Content-Range"));
  6899. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6900. EXPECT_EQ(std::string("efg"), res->body);
  6901. }
  6902. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6903. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6904. // the entire representation.
  6905. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6906. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6908. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6909. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6910. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6911. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6912. }
  6913. }
  6914. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6915. auto res =
  6916. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6919. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ(false, res->has_header("Content-Range"));
  6921. EXPECT_EQ(0U, res->body.size());
  6922. }
  6923. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6924. // Only a 206 is served as a partial representation. Under any other status
  6925. // `apply_ranges()` reported the full content length, so the body must match
  6926. // that header, and the content provider must never be asked for an offset
  6927. // outside the representation.
  6928. auto check = [&](int status, const char *range) {
  6929. auto path =
  6930. std::string("/streamed-with-range?status=") + std::to_string(status);
  6931. auto ctx = path + " Range: " + range;
  6932. auto res = cli_.Get(path, Headers{{"Range", range}});
  6933. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6934. EXPECT_EQ(status, res->status) << ctx;
  6935. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6937. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6938. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6939. };
  6940. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6941. check(403, "bytes=3-5");
  6942. // The offset is far past the representation.
  6943. check(403, "bytes=100000-100200");
  6944. // `first_pos` is still -1 here, and the bounds asserts in
  6945. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6946. check(403, "bytes=-3");
  6947. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6948. // multipart branch would have written one that is empty.
  6949. check(403, "bytes=1-2, 4-5");
  6950. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6951. // covers the whole representation.
  6952. check(200, "bytes=3-5");
  6953. check(200, "bytes=1-2, 4-5");
  6954. }
  6955. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6956. auto res =
  6957. cli_.Get("/streamed-with-range",
  6958. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6959. "92233720368547758079223372036854775807"}});
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6962. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6963. EXPECT_EQ(false, res->has_header("Content-Range"));
  6964. EXPECT_EQ(0U, res->body.size());
  6965. }
  6966. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6967. auto res = cli_.Get(
  6968. "/with-range",
  6969. Headers{{"Range",
  6970. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6971. {"Accept-Encoding", ""}});
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6974. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6975. EXPECT_EQ(true, res->has_header("Content-Range"));
  6976. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6977. EXPECT_EQ(std::string("abcdefg"), res->body);
  6978. }
  6979. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6980. auto res = cli_.Get("/with-range", Headers{
  6981. {"Range", "bytes=0-"},
  6982. {"Accept-Encoding", ""},
  6983. });
  6984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6985. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6986. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6987. EXPECT_EQ(true, res->has_header("Content-Range"));
  6988. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6989. EXPECT_EQ(std::string("abcdefg"), res->body);
  6990. }
  6991. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6992. auto res = cli_.Get("/streamed-with-range",
  6993. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6996. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6997. EXPECT_EQ(false, res->has_header("Content-Range"));
  6998. EXPECT_EQ(267U, res->body.size());
  6999. // Check that both range contents are present
  7000. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7001. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7002. // Check that Content-Range headers are present for both ranges
  7003. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7004. std::string::npos);
  7005. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7006. std::string::npos);
  7007. }
  7008. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7009. Ranges ranges;
  7010. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7011. ranges.emplace_back(0, -1);
  7012. }
  7013. auto res = cli_.Get("/streamed-with-range?error",
  7014. Headers{{make_range_header(ranges)}});
  7015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7016. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7017. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7018. EXPECT_EQ(false, res->has_header("Content-Range"));
  7019. EXPECT_EQ(0U, res->body.size());
  7020. }
  7021. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7022. auto res = cli_.Get("/streamed-with-range",
  7023. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7026. EXPECT_EQ(5U, res->body.size());
  7027. // Check that overlapping ranges are coalesced into a single range
  7028. EXPECT_EQ("bcdef", res->body);
  7029. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7030. // Should be single range, not multipart
  7031. EXPECT_TRUE(res->has_header("Content-Range"));
  7032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7033. }
  7034. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7035. auto res = cli_.Get("/streamed-with-range",
  7036. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7039. EXPECT_EQ(268U, res->body.size());
  7040. // Check that both range contents are present
  7041. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7042. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7043. // Check that Content-Range headers are present for both ranges
  7044. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7045. std::string::npos);
  7046. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7047. std::string::npos);
  7048. }
  7049. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7050. auto res = cli_.Get("/streamed-with-range",
  7051. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7054. EXPECT_EQ(269U, res->body.size());
  7055. // Check that both duplicate range contents are present
  7056. size_t first_abc = res->body.find("abc\r\n");
  7057. EXPECT_TRUE(first_abc != std::string::npos);
  7058. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7059. EXPECT_TRUE(second_abc != std::string::npos);
  7060. // Check that Content-Range headers are present for both ranges
  7061. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7062. EXPECT_TRUE(first_range != std::string::npos);
  7063. size_t second_range =
  7064. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7065. EXPECT_TRUE(second_range != std::string::npos);
  7066. }
  7067. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7068. auto res =
  7069. cli_.Get("/streamed-with-range?error",
  7070. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7072. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7073. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7074. EXPECT_EQ(false, res->has_header("Content-Range"));
  7075. EXPECT_EQ(0U, res->body.size());
  7076. }
  7077. TEST_F(ServerTest, GetStreamedEndless) {
  7078. uint64_t offset = 0;
  7079. auto res = cli_.Get("/streamed-cancel",
  7080. [&](const char * /*data*/, uint64_t data_length) {
  7081. if (offset < 100) {
  7082. offset += data_length;
  7083. return true;
  7084. }
  7085. return false;
  7086. });
  7087. ASSERT_TRUE(!res);
  7088. EXPECT_EQ(Error::Canceled, res.error());
  7089. }
  7090. TEST_F(ServerTest, ClientStop) {
  7091. std::atomic_size_t count{4};
  7092. std::vector<std::thread> threads;
  7093. for (auto i = count.load(); i != 0; --i) {
  7094. threads.emplace_back([&]() {
  7095. auto res = cli_.Get("/streamed-cancel",
  7096. [&](const char *, uint64_t) { return true; });
  7097. --count;
  7098. ASSERT_TRUE(!res);
  7099. EXPECT_TRUE(res.error() == Error::Canceled ||
  7100. res.error() == Error::Read || res.error() == Error::Write);
  7101. });
  7102. }
  7103. std::this_thread::sleep_for(std::chrono::seconds(2));
  7104. while (count != 0) {
  7105. cli_.stop();
  7106. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7107. }
  7108. for (auto &t : threads) {
  7109. t.join();
  7110. }
  7111. }
  7112. TEST_F(ServerTest, GetWithRange1) {
  7113. auto res = cli_.Get("/with-range", Headers{
  7114. make_range_header({{3, 5}}),
  7115. {"Accept-Encoding", ""},
  7116. });
  7117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7118. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7119. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7120. EXPECT_EQ(true, res->has_header("Content-Range"));
  7121. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7122. EXPECT_EQ(std::string("def"), res->body);
  7123. }
  7124. TEST_F(ServerTest, GetWithRange2) {
  7125. auto res = cli_.Get("/with-range", Headers{
  7126. make_range_header({{1, -1}}),
  7127. {"Accept-Encoding", ""},
  7128. });
  7129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7131. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7132. EXPECT_EQ(true, res->has_header("Content-Range"));
  7133. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7134. EXPECT_EQ(std::string("bcdefg"), res->body);
  7135. }
  7136. TEST_F(ServerTest, GetWithRange3) {
  7137. auto res = cli_.Get("/with-range", Headers{
  7138. make_range_header({{0, 0}}),
  7139. {"Accept-Encoding", ""},
  7140. });
  7141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7142. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7143. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7144. EXPECT_EQ(true, res->has_header("Content-Range"));
  7145. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7146. EXPECT_EQ(std::string("a"), res->body);
  7147. }
  7148. TEST_F(ServerTest, GetWithRange4) {
  7149. auto res = cli_.Get("/with-range", Headers{
  7150. make_range_header({{-1, 2}}),
  7151. {"Accept-Encoding", ""},
  7152. });
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7155. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7156. EXPECT_EQ(true, res->has_header("Content-Range"));
  7157. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7158. EXPECT_EQ(std::string("fg"), res->body);
  7159. }
  7160. TEST_F(ServerTest, GetWithRange5) {
  7161. auto res = cli_.Get("/with-range", Headers{
  7162. make_range_header({{0, 5}}),
  7163. {"Accept-Encoding", ""},
  7164. });
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7167. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7168. EXPECT_EQ(true, res->has_header("Content-Range"));
  7169. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7170. EXPECT_EQ(std::string("abcdef"), res->body);
  7171. }
  7172. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7173. auto res =
  7174. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7177. }
  7178. TEST_F(ServerTest, GetWithRangeMultipart) {
  7179. auto res =
  7180. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7183. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7184. EXPECT_EQ(false, res->has_header("Content-Range"));
  7185. EXPECT_EQ(267U, res->body.size());
  7186. }
  7187. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7188. auto res = cli_.Get("/with-range",
  7189. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7191. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7192. }
  7193. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7194. auto res = cli_.Get("/with-range-customized-response",
  7195. Headers{{make_range_header({{1, 2}})}});
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7198. EXPECT_EQ(true, res->has_header("Content-Length"));
  7199. EXPECT_EQ(false, res->has_header("Content-Range"));
  7200. EXPECT_EQ(JSON_DATA, res->body);
  7201. }
  7202. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7203. auto res = cli_.Get("/with-range-customized-response",
  7204. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7206. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7207. EXPECT_EQ(true, res->has_header("Content-Length"));
  7208. EXPECT_EQ(false, res->has_header("Content-Range"));
  7209. EXPECT_EQ(JSON_DATA, res->body);
  7210. }
  7211. TEST_F(ServerTest, Issue1772) {
  7212. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7214. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7215. }
  7216. TEST_F(ServerTest, Issue609) {
  7217. auto res = cli_.Delete("/issue609");
  7218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7219. EXPECT_EQ(StatusCode::OK_200, res->status);
  7220. EXPECT_EQ(std::string("ok"), res->body);
  7221. }
  7222. TEST_F(ServerTest, GetStreamedChunked) {
  7223. auto res = cli_.Get("/streamed-chunked");
  7224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7225. EXPECT_EQ(StatusCode::OK_200, res->status);
  7226. EXPECT_EQ(std::string("123456789"), res->body);
  7227. }
  7228. TEST_F(ServerTest, GetStreamedChunked2) {
  7229. auto res = cli_.Get("/streamed-chunked2");
  7230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7231. EXPECT_EQ(StatusCode::OK_200, res->status);
  7232. EXPECT_EQ(std::string("123456789"), res->body);
  7233. }
  7234. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7235. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::OK_200, res->status);
  7238. EXPECT_EQ(std::string("123456789"), res->body);
  7239. EXPECT_TRUE(res->has_header("Trailer"));
  7240. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7241. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7242. // Trailers are now stored separately from headers (security fix)
  7243. EXPECT_EQ(2U, res->trailers.size());
  7244. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7245. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7246. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7247. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7248. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7249. // Verify trailers are NOT in headers (security verification)
  7250. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7251. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7252. }
  7253. TEST_F(ServerTest, LargeChunkedPost) {
  7254. Request req;
  7255. req.method = "POST";
  7256. req.path = "/large-chunked";
  7257. std::string host_and_port;
  7258. host_and_port += HOST;
  7259. host_and_port += ":";
  7260. host_and_port += std::to_string(PORT);
  7261. req.headers.emplace("Host", host_and_port.c_str());
  7262. req.headers.emplace("Accept", "*/*");
  7263. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7264. req.headers.emplace("Content-Type", "text/plain");
  7265. req.headers.emplace("Content-Length", "0");
  7266. req.headers.emplace("Transfer-Encoding", "chunked");
  7267. std::string long_string(30 * 1024u, 'a');
  7268. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7269. // Attempt to make a large enough post to exceed OS buffers, to test that
  7270. // the server handles short reads if the full chunk data isn't available.
  7271. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7272. auto res = std::make_shared<Response>();
  7273. auto error = Error::Success;
  7274. auto ret = cli_.send(req, *res, error);
  7275. ASSERT_TRUE(ret);
  7276. EXPECT_EQ(StatusCode::OK_200, res->status);
  7277. }
  7278. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7279. auto res = cli_.Get("/remote_addr");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::OK_200, res->status);
  7282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7283. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7284. }
  7285. TEST_F(ServerTest, GetMethodLocalAddr) {
  7286. auto res = cli_.Get("/local_addr");
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7290. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7291. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7292. }
  7293. TEST_F(ServerTest, HTTPResponseSplitting) {
  7294. auto res = cli_.Get("/http_response_splitting");
  7295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7296. EXPECT_EQ(StatusCode::OK_200, res->status);
  7297. }
  7298. TEST_F(ServerTest, SlowRequest) {
  7299. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7300. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7301. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7302. }
  7303. #if 0
  7304. TEST_F(ServerTest, SlowPost) {
  7305. char buffer[64 * 1024];
  7306. memset(buffer, 0x42, sizeof(buffer));
  7307. auto res = cli_.Post(
  7308. "/slowpost", 64 * 1024 * 1024,
  7309. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7310. auto ret = sink.write(buffer, sizeof(buffer));
  7311. EXPECT_TRUE(ret);
  7312. return true;
  7313. },
  7314. "text/plain");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::OK_200, res->status);
  7317. }
  7318. TEST_F(ServerTest, SlowPostFail) {
  7319. char buffer[64 * 1024];
  7320. memset(buffer, 0x42, sizeof(buffer));
  7321. cli_.set_write_timeout(std::chrono::seconds(0));
  7322. auto res = cli_.Post(
  7323. "/slowpost", 64 * 1024 * 1024,
  7324. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7325. sink.write(buffer, sizeof(buffer));
  7326. return true;
  7327. },
  7328. "text/plain");
  7329. ASSERT_TRUE(!res);
  7330. EXPECT_EQ(Error::Write, res.error());
  7331. }
  7332. #endif
  7333. TEST_F(ServerTest, Put) {
  7334. auto res = cli_.Put("/put", "PUT", "text/plain");
  7335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7336. EXPECT_EQ(StatusCode::OK_200, res->status);
  7337. EXPECT_EQ("PUT", res->body);
  7338. }
  7339. TEST_F(ServerTest, PutWithContentProvider) {
  7340. auto res = cli_.Put(
  7341. "/put", 3,
  7342. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7343. sink.os << "PUT";
  7344. return true;
  7345. },
  7346. "text/plain");
  7347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7348. EXPECT_EQ(StatusCode::OK_200, res->status);
  7349. EXPECT_EQ("PUT", res->body);
  7350. }
  7351. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7352. auto res = cli_.Post(
  7353. "/post", 42,
  7354. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7355. return false;
  7356. },
  7357. "text/plain");
  7358. ASSERT_TRUE(!res);
  7359. EXPECT_EQ(Error::Canceled, res.error());
  7360. }
  7361. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7362. auto res = cli_.Put(
  7363. "/put",
  7364. [](size_t /*offset*/, DataSink &sink) {
  7365. sink.os << "PUT";
  7366. sink.done();
  7367. return true;
  7368. },
  7369. "text/plain");
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. EXPECT_EQ("PUT", res->body);
  7373. }
  7374. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7375. auto res = cli_.Post(
  7376. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7377. "text/plain");
  7378. ASSERT_TRUE(!res);
  7379. EXPECT_EQ(Error::Canceled, res.error());
  7380. }
  7381. TEST_F(ServerTest, PostLoopBack) {
  7382. std::string body;
  7383. auto res = cli_.Post(
  7384. "/post-loopback", 9,
  7385. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7386. EXPECT_EQ(9u, length);
  7387. sink.write("123", 3);
  7388. sink.write("456", 3);
  7389. sink.write("789", 3);
  7390. return true;
  7391. },
  7392. "text/plain",
  7393. [&body](const char *data, size_t data_length) {
  7394. body.append(data, data_length);
  7395. return true;
  7396. });
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("123456789", body);
  7400. }
  7401. TEST_F(ServerTest, PutLoopBack) {
  7402. std::string body;
  7403. auto res = cli_.Put(
  7404. "/put-loopback", 9,
  7405. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7406. EXPECT_EQ(9u, length);
  7407. sink.write("123", 3);
  7408. sink.write("456", 3);
  7409. sink.write("789", 3);
  7410. return true;
  7411. },
  7412. "text/plain",
  7413. [&body](const char *data, size_t data_length) {
  7414. body.append(data, data_length);
  7415. return true;
  7416. });
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. EXPECT_EQ("123456789", body);
  7420. }
  7421. TEST_F(ServerTest, PatchLoopBack) {
  7422. std::string body;
  7423. auto res = cli_.Patch(
  7424. "/patch-loopback", 9,
  7425. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7426. EXPECT_EQ(9u, length);
  7427. sink.write("123", 3);
  7428. sink.write("456", 3);
  7429. sink.write("789", 3);
  7430. return true;
  7431. },
  7432. "text/plain",
  7433. [&body](const char *data, size_t data_length) {
  7434. body.append(data, data_length);
  7435. return true;
  7436. });
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. EXPECT_EQ("123456789", body);
  7440. }
  7441. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7442. std::string body;
  7443. auto res = cli_.Post(
  7444. "/post-loopback",
  7445. [](size_t /*offset*/, DataSink &sink) {
  7446. sink.write("123", 3);
  7447. sink.write("456", 3);
  7448. sink.write("789", 3);
  7449. sink.done();
  7450. return true;
  7451. },
  7452. "text/plain",
  7453. [&body](const char *data, size_t data_length) {
  7454. body.append(data, data_length);
  7455. return true;
  7456. });
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("123456789", body);
  7460. }
  7461. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7462. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7463. cli_.set_compress(true);
  7464. auto res = cli_.Put(
  7465. "/put", 3,
  7466. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7467. sink.os << "PUT";
  7468. return true;
  7469. },
  7470. "text/plain");
  7471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7472. EXPECT_EQ(StatusCode::OK_200, res->status);
  7473. EXPECT_EQ("PUT", res->body);
  7474. }
  7475. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7476. cli_.set_compress(true);
  7477. auto res = cli_.Post(
  7478. "/post", 42,
  7479. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7480. return false;
  7481. },
  7482. "text/plain");
  7483. ASSERT_TRUE(!res);
  7484. EXPECT_EQ(Error::Canceled, res.error());
  7485. }
  7486. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7487. cli_.set_compress(true);
  7488. auto res = cli_.Put(
  7489. "/put",
  7490. [](size_t /*offset*/, DataSink &sink) {
  7491. sink.os << "PUT";
  7492. sink.done();
  7493. return true;
  7494. },
  7495. "text/plain");
  7496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7497. EXPECT_EQ(StatusCode::OK_200, res->status);
  7498. EXPECT_EQ("PUT", res->body);
  7499. }
  7500. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7501. cli_.set_compress(true);
  7502. auto res = cli_.Post(
  7503. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7504. "text/plain");
  7505. ASSERT_TRUE(!res);
  7506. EXPECT_EQ(Error::Canceled, res.error());
  7507. }
  7508. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7509. cli_.set_compress(true);
  7510. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::OK_200, res->status);
  7513. EXPECT_EQ(LARGE_DATA, res->body);
  7514. }
  7515. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7516. #ifdef CPPHTTPLIB_SSL_ENABLED
  7517. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7518. Client cli(s.c_str());
  7519. cli.enable_server_certificate_verification(false);
  7520. #else
  7521. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7522. Client cli(s.c_str());
  7523. #endif
  7524. cli.set_compress(true);
  7525. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7527. EXPECT_EQ(StatusCode::OK_200, res->status);
  7528. EXPECT_EQ(LARGE_DATA, res->body);
  7529. // The compressed size should be less than a 10th of the original. May vary
  7530. // depending on the zlib library.
  7531. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7532. static_cast<uint64_t>(10 * 1024 * 1024));
  7533. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7534. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7535. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7536. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7537. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7538. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7539. #endif
  7540. }
  7541. TEST_F(ServerTest, PutContentWithDeflate) {
  7542. cli_.set_compress(false);
  7543. Headers headers;
  7544. headers.emplace("Content-Encoding", "deflate");
  7545. // PUT in deflate format:
  7546. auto res = cli_.Put("/put", headers,
  7547. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. EXPECT_EQ("PUT", res->body);
  7551. }
  7552. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7553. Headers headers;
  7554. headers.emplace("Accept-Encoding", "gzip, deflate");
  7555. auto res = cli_.Get("/streamed-chunked", headers);
  7556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7557. EXPECT_EQ(StatusCode::OK_200, res->status);
  7558. EXPECT_EQ(std::string("123456789"), res->body);
  7559. }
  7560. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7561. Headers headers;
  7562. headers.emplace("Accept-Encoding", "gzip, deflate");
  7563. auto res = cli_.Get("/streamed-chunked2", headers);
  7564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7565. EXPECT_EQ(StatusCode::OK_200, res->status);
  7566. EXPECT_EQ(std::string("123456789"), res->body);
  7567. }
  7568. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7569. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. }
  7573. TEST(GzipDecompressor, ChunkedDecompression) {
  7574. std::string data;
  7575. for (size_t i = 0; i < 32 * 1024; ++i) {
  7576. data.push_back(static_cast<char>('a' + i % 26));
  7577. }
  7578. std::string compressed_data;
  7579. {
  7580. httplib::detail::gzip_compressor compressor;
  7581. bool result = compressor.compress(
  7582. data.data(), data.size(),
  7583. /*last=*/true,
  7584. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7585. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7586. compressed_data_size);
  7587. return true;
  7588. });
  7589. ASSERT_TRUE(result);
  7590. }
  7591. std::string decompressed_data;
  7592. {
  7593. httplib::detail::gzip_decompressor decompressor;
  7594. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7595. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7596. size_t chunk_size = 130;
  7597. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7598. chunk_begin += chunk_size) {
  7599. size_t current_chunk_size =
  7600. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7601. bool result = decompressor.decompress(
  7602. compressed_data.data() + chunk_begin, current_chunk_size,
  7603. [&](const char *decompressed_data_chunk,
  7604. size_t decompressed_data_chunk_size) {
  7605. decompressed_data.insert(decompressed_data.size(),
  7606. decompressed_data_chunk,
  7607. decompressed_data_chunk_size);
  7608. return true;
  7609. });
  7610. ASSERT_TRUE(result);
  7611. }
  7612. }
  7613. ASSERT_EQ(data, decompressed_data);
  7614. }
  7615. TEST(GzipDecompressor, DeflateDecompression) {
  7616. std::string original_text = "Raw deflate without gzip";
  7617. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7618. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7619. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7620. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7621. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7622. std::string decompressed_data;
  7623. {
  7624. httplib::detail::gzip_decompressor decompressor;
  7625. bool result = decompressor.decompress(
  7626. compressed_data.data(), compressed_data.size(),
  7627. [&](const char *decompressed_data_chunk,
  7628. size_t decompressed_data_chunk_size) {
  7629. decompressed_data.insert(decompressed_data.size(),
  7630. decompressed_data_chunk,
  7631. decompressed_data_chunk_size);
  7632. return true;
  7633. });
  7634. ASSERT_TRUE(result);
  7635. }
  7636. ASSERT_EQ(original_text, decompressed_data);
  7637. }
  7638. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7639. std::string original_text = "Raw deflate without gzip";
  7640. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7641. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7642. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7643. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7644. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7645. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7646. std::string decompressed_data;
  7647. {
  7648. httplib::detail::gzip_decompressor decompressor;
  7649. bool result = decompressor.decompress(
  7650. compressed_data.data(), compressed_data.size(),
  7651. [&](const char *decompressed_data_chunk,
  7652. size_t decompressed_data_chunk_size) {
  7653. decompressed_data.insert(decompressed_data.size(),
  7654. decompressed_data_chunk,
  7655. decompressed_data_chunk_size);
  7656. return true;
  7657. });
  7658. ASSERT_TRUE(result);
  7659. }
  7660. ASSERT_EQ(original_text, decompressed_data);
  7661. }
  7662. #endif
  7663. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7664. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7665. Headers headers;
  7666. headers.emplace("Accept-Encoding", "br");
  7667. auto res = cli_.Get("/streamed-chunked", headers);
  7668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7669. EXPECT_EQ(StatusCode::OK_200, res->status);
  7670. EXPECT_EQ(std::string("123456789"), res->body);
  7671. }
  7672. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7673. Headers headers;
  7674. headers.emplace("Accept-Encoding", "br");
  7675. auto res = cli_.Get("/streamed-chunked2", headers);
  7676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7677. EXPECT_EQ(StatusCode::OK_200, res->status);
  7678. EXPECT_EQ(std::string("123456789"), res->body);
  7679. }
  7680. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7681. cli_.set_compress(true);
  7682. auto res = cli_.Put(
  7683. "/put", 3,
  7684. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7685. sink.os << "PUT";
  7686. return true;
  7687. },
  7688. "text/plain");
  7689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7690. EXPECT_EQ(StatusCode::OK_200, res->status);
  7691. EXPECT_EQ("PUT", res->body);
  7692. }
  7693. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7694. cli_.set_compress(true);
  7695. auto res = cli_.Put(
  7696. "/put",
  7697. [](size_t /*offset*/, DataSink &sink) {
  7698. sink.os << "PUT";
  7699. sink.done();
  7700. return true;
  7701. },
  7702. "text/plain");
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. EXPECT_EQ("PUT", res->body);
  7706. }
  7707. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7708. cli_.set_compress(true);
  7709. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::OK_200, res->status);
  7712. EXPECT_EQ(LARGE_DATA, res->body);
  7713. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7714. }
  7715. #endif
  7716. TEST_F(ServerTest, Patch) {
  7717. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. EXPECT_EQ("PATCH", res->body);
  7721. }
  7722. TEST_F(ServerTest, Delete) {
  7723. auto res = cli_.Delete("/delete");
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::OK_200, res->status);
  7726. EXPECT_EQ("DELETE", res->body);
  7727. }
  7728. TEST_F(ServerTest, DeleteContentReceiver) {
  7729. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::OK_200, res->status);
  7732. EXPECT_EQ("content", res->body);
  7733. }
  7734. TEST_F(ServerTest, Options) {
  7735. auto res = cli_.Options("*");
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::OK_200, res->status);
  7738. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7739. EXPECT_TRUE(res->body.empty());
  7740. }
  7741. TEST_F(ServerTest, URL) {
  7742. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. }
  7746. TEST_F(ServerTest, ArrayParam) {
  7747. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7749. EXPECT_EQ(StatusCode::OK_200, res->status);
  7750. }
  7751. TEST_F(ServerTest, ArrayParamValues) {
  7752. auto res =
  7753. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. }
  7757. TEST_F(ServerTest, NoMultipleHeaders) {
  7758. Headers headers = {{"Content-Length", "5"}};
  7759. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7760. "text/plain");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. }
  7764. TEST_F(ServerTest, PostContentReceiver) {
  7765. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. ASSERT_EQ(StatusCode::OK_200, res->status);
  7768. ASSERT_EQ("content", res->body);
  7769. }
  7770. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7771. UploadFormDataItems items = {
  7772. {"text1", "text default", "", ""},
  7773. {"text2", "aωb", "", ""},
  7774. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7775. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7776. {"file3", "", "", "application/octet-stream"},
  7777. };
  7778. auto res = cli_.Post("/content_receiver", items);
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. }
  7782. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7783. UploadFormDataItems items = {
  7784. {"text1", "text default", "", ""},
  7785. {"text2", "aωb", "", ""},
  7786. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7787. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7788. {"file3", "", "", "application/octet-stream"},
  7789. };
  7790. auto boundary = std::string("+++++");
  7791. std::string body;
  7792. for (const auto &item : items) {
  7793. body += "--" + boundary + "\r\n";
  7794. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7795. if (!item.filename.empty()) {
  7796. body += "; filename=\"" + item.filename + "\"";
  7797. }
  7798. body += "\r\n";
  7799. if (!item.content_type.empty()) {
  7800. body += "Content-Type: " + item.content_type + "\r\n";
  7801. }
  7802. body += "\r\n";
  7803. body += item.content + "\r\n";
  7804. }
  7805. body += "--" + boundary + "--\r\n";
  7806. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7807. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::OK_200, res->status);
  7810. }
  7811. TEST(MultipartFormDataTest, FieldEscaping) {
  7812. Server svr;
  7813. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7814. const ContentReader &content_reader) {
  7815. ASSERT_TRUE(req.is_multipart_form_data());
  7816. std::vector<FormData> received;
  7817. content_reader(
  7818. [&](const FormData &file) {
  7819. received.push_back(file);
  7820. return true;
  7821. },
  7822. [&](const char *data, size_t data_length) {
  7823. received.back().content.append(data, data_length);
  7824. return true;
  7825. });
  7826. // '"', CR and LF in names and filenames are escaped following the
  7827. // WHATWG HTML standard, so each part still parses as a single part
  7828. // with no injected headers. Content types get CR/LF escaped too,
  7829. // while '"' (legal there, e.g. quoted charset) is preserved.
  7830. ASSERT_EQ(4U, received.size());
  7831. EXPECT_EQ("na%22me", received[0].name);
  7832. EXPECT_EQ("quoted name", received[0].content);
  7833. EXPECT_EQ("file", received[1].name);
  7834. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7835. received[1].filename);
  7836. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7837. EXPECT_EQ("injected", received[1].content);
  7838. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7839. EXPECT_EQ("my%22file.txt", received[2].filename);
  7840. EXPECT_EQ("cr lf name", received[2].content);
  7841. EXPECT_EQ("typed", received[3].name);
  7842. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7843. received[3].content_type);
  7844. EXPECT_EQ("typed content", received[3].content);
  7845. });
  7846. auto port = svr.bind_to_any_port("localhost");
  7847. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7848. auto se = detail::scope_exit([&] {
  7849. svr.stop();
  7850. t.join();
  7851. ASSERT_FALSE(svr.is_running());
  7852. });
  7853. svr.wait_until_ready();
  7854. Client cli("localhost", port);
  7855. UploadFormDataItems items = {
  7856. {"na\"me", "quoted name", "", ""},
  7857. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7858. "application/octet-stream"},
  7859. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7860. {"typed", "typed content", "",
  7861. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7862. };
  7863. auto res = cli.Post("/post", items);
  7864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7865. EXPECT_EQ(StatusCode::OK_200, res->status);
  7866. }
  7867. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7868. const UploadFormDataItems items = {
  7869. {"name1", "Content 1", "", ""},
  7870. {"name2", "Content 2", "file2.txt", "text/plain"},
  7871. };
  7872. Server svr;
  7873. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7874. const ContentReader &content_reader) {
  7875. ASSERT_TRUE(req.is_multipart_form_data());
  7876. std::vector<FormData> received;
  7877. content_reader(
  7878. [&](const FormData &file) {
  7879. received.push_back(file);
  7880. return true;
  7881. },
  7882. [&](const char *data, size_t data_length) {
  7883. received.back().content.append(data, data_length);
  7884. return true;
  7885. });
  7886. ASSERT_EQ(2U, received.size());
  7887. EXPECT_EQ("name1", received[0].name);
  7888. EXPECT_EQ("Content 1", received[0].content);
  7889. EXPECT_EQ("name2", received[1].name);
  7890. EXPECT_EQ("Content 2", received[1].content);
  7891. EXPECT_EQ("file2.txt", received[1].filename);
  7892. EXPECT_EQ("text/plain", received[1].content_type);
  7893. });
  7894. auto port = svr.bind_to_any_port("localhost");
  7895. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7896. auto se = detail::scope_exit([&] {
  7897. svr.stop();
  7898. t.join();
  7899. ASSERT_FALSE(svr.is_running());
  7900. });
  7901. svr.wait_until_ready();
  7902. Client cli("localhost", port);
  7903. // Whole-body serialization with a generated boundary
  7904. {
  7905. MultipartFormDataWriter writer;
  7906. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7907. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7908. writer.content_type());
  7909. auto body = writer.serialize(items);
  7910. EXPECT_EQ(body.size(), writer.content_length(items));
  7911. auto res = cli.Post("/post", body, writer.content_type());
  7912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7913. EXPECT_EQ(StatusCode::OK_200, res->status);
  7914. }
  7915. // Per-part framing with a custom boundary via a content provider
  7916. {
  7917. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7918. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7919. MultipartFormDataWriter writer("custom-boundary_123");
  7920. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7921. std::string body;
  7922. for (const auto &item : items) {
  7923. body += writer.item_begin(item);
  7924. body += item.content;
  7925. body += MultipartFormDataWriter::item_end();
  7926. }
  7927. body += writer.finish();
  7928. EXPECT_EQ(body.size(), writer.content_length(items));
  7929. auto res = cli.Post(
  7930. "/post", body.size(),
  7931. [&](size_t offset, size_t length, DataSink &sink) {
  7932. sink.write(body.data() + offset, length);
  7933. return true;
  7934. },
  7935. writer.content_type());
  7936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7937. EXPECT_EQ(StatusCode::OK_200, res->status);
  7938. }
  7939. }
  7940. TEST_F(ServerTest, PostContentReceiverGzip) {
  7941. cli_.set_compress(true);
  7942. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. ASSERT_EQ(StatusCode::OK_200, res->status);
  7945. ASSERT_EQ("content", res->body);
  7946. }
  7947. TEST_F(ServerTest, PutContentReceiver) {
  7948. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. ASSERT_EQ(StatusCode::OK_200, res->status);
  7951. ASSERT_EQ("content", res->body);
  7952. }
  7953. TEST_F(ServerTest, PatchContentReceiver) {
  7954. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. ASSERT_EQ(StatusCode::OK_200, res->status);
  7957. ASSERT_EQ("content", res->body);
  7958. }
  7959. template <typename ClientType>
  7960. void TestWithHeadersAndContentReceiver(
  7961. ClientType &cli,
  7962. std::function<Result(ClientType &, const std::string &, const Headers &,
  7963. const std::string &, const std::string &,
  7964. ContentReceiver, DownloadProgress)>
  7965. request_func) {
  7966. Headers headers;
  7967. headers.emplace("X-Custom-Header", "test-value");
  7968. std::string received_body;
  7969. auto res = request_func(
  7970. cli, "/content_receiver", headers, "content", "application/json",
  7971. [&](const char *data, size_t data_length) {
  7972. received_body.append(data, data_length);
  7973. return true;
  7974. },
  7975. nullptr);
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. EXPECT_EQ("content", received_body);
  7979. }
  7980. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7981. #ifdef CPPHTTPLIB_SSL_ENABLED
  7982. using ClientT = SSLClient;
  7983. #else
  7984. using ClientT = Client;
  7985. #endif
  7986. TestWithHeadersAndContentReceiver<ClientT>(
  7987. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7988. const std::string &body, const std::string &content_type,
  7989. ContentReceiver receiver, DownloadProgress progress) {
  7990. return cli.Post(path, headers, body, content_type, receiver, progress);
  7991. });
  7992. }
  7993. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7994. #ifdef CPPHTTPLIB_SSL_ENABLED
  7995. using ClientT = SSLClient;
  7996. #else
  7997. using ClientT = Client;
  7998. #endif
  7999. TestWithHeadersAndContentReceiver<ClientT>(
  8000. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8001. const std::string &body, const std::string &content_type,
  8002. ContentReceiver receiver, DownloadProgress progress) {
  8003. return cli.Put(path, headers, body, content_type, receiver, progress);
  8004. });
  8005. }
  8006. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8007. #ifdef CPPHTTPLIB_SSL_ENABLED
  8008. using ClientT = SSLClient;
  8009. #else
  8010. using ClientT = Client;
  8011. #endif
  8012. TestWithHeadersAndContentReceiver<ClientT>(
  8013. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8014. const std::string &body, const std::string &content_type,
  8015. ContentReceiver receiver, DownloadProgress progress) {
  8016. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8017. });
  8018. }
  8019. template <typename ClientType>
  8020. void TestWithHeadersAndContentReceiverWithProgress(
  8021. ClientType &cli,
  8022. std::function<Result(ClientType &, const std::string &, const Headers &,
  8023. const std::string &, const std::string &,
  8024. ContentReceiver, DownloadProgress)>
  8025. request_func) {
  8026. Headers headers;
  8027. headers.emplace("X-Test-Header", "progress-test");
  8028. std::string received_body;
  8029. auto progress_called = false;
  8030. auto res = request_func(
  8031. cli, "/content_receiver", headers, "content", "text/plain",
  8032. [&](const char *data, size_t data_length) {
  8033. received_body.append(data, data_length);
  8034. return true;
  8035. },
  8036. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8037. progress_called = true;
  8038. return true;
  8039. });
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. EXPECT_EQ("content", received_body);
  8043. EXPECT_TRUE(progress_called);
  8044. }
  8045. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8046. #ifdef CPPHTTPLIB_SSL_ENABLED
  8047. using ClientT = SSLClient;
  8048. #else
  8049. using ClientT = Client;
  8050. #endif
  8051. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8052. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8053. const std::string &body, const std::string &content_type,
  8054. ContentReceiver receiver, DownloadProgress progress) {
  8055. return cli.Post(path, headers, body, content_type, receiver, progress);
  8056. });
  8057. }
  8058. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8059. #ifdef CPPHTTPLIB_SSL_ENABLED
  8060. using ClientT = SSLClient;
  8061. #else
  8062. using ClientT = Client;
  8063. #endif
  8064. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8065. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8066. const std::string &body, const std::string &content_type,
  8067. ContentReceiver receiver, DownloadProgress progress) {
  8068. return cli.Put(path, headers, body, content_type, receiver, progress);
  8069. });
  8070. }
  8071. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8072. #ifdef CPPHTTPLIB_SSL_ENABLED
  8073. using ClientT = SSLClient;
  8074. #else
  8075. using ClientT = Client;
  8076. #endif
  8077. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8078. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8079. const std::string &body, const std::string &content_type,
  8080. ContentReceiver receiver, DownloadProgress progress) {
  8081. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8082. });
  8083. }
  8084. template <typename ClientType>
  8085. void TestWithHeadersAndContentReceiverError(
  8086. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8087. const Headers &, const std::string &,
  8088. const std::string &, ContentReceiver)>
  8089. request_func) {
  8090. Headers headers;
  8091. headers.emplace("X-Error-Test", "true");
  8092. std::string received_body;
  8093. auto receiver_failed = false;
  8094. auto res =
  8095. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8096. [&](const char *data, size_t data_length) {
  8097. received_body.append(data, data_length);
  8098. receiver_failed = true;
  8099. return false;
  8100. });
  8101. ASSERT_FALSE(res);
  8102. EXPECT_TRUE(receiver_failed);
  8103. }
  8104. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8105. #ifdef CPPHTTPLIB_SSL_ENABLED
  8106. using ClientT = SSLClient;
  8107. #else
  8108. using ClientT = Client;
  8109. #endif
  8110. TestWithHeadersAndContentReceiverError<ClientT>(
  8111. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8112. const std::string &body, const std::string &content_type,
  8113. ContentReceiver receiver) {
  8114. return cli.Post(path, headers, body, content_type, receiver);
  8115. });
  8116. }
  8117. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8118. #ifdef CPPHTTPLIB_SSL_ENABLED
  8119. using ClientT = SSLClient;
  8120. #else
  8121. using ClientT = Client;
  8122. #endif
  8123. TestWithHeadersAndContentReceiverError<ClientT>(
  8124. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8125. const std::string &body, const std::string &content_type,
  8126. ContentReceiver receiver) {
  8127. return cli.Put(path, headers, body, content_type, receiver);
  8128. });
  8129. }
  8130. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8131. #ifdef CPPHTTPLIB_SSL_ENABLED
  8132. using ClientT = SSLClient;
  8133. #else
  8134. using ClientT = Client;
  8135. #endif
  8136. TestWithHeadersAndContentReceiverError<ClientT>(
  8137. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8138. const std::string &body, const std::string &content_type,
  8139. ContentReceiver receiver) {
  8140. return cli.Patch(path, headers, body, content_type, receiver);
  8141. });
  8142. }
  8143. TEST_F(ServerTest, PostQueryStringAndBody) {
  8144. auto res =
  8145. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. ASSERT_EQ(StatusCode::OK_200, res->status);
  8148. }
  8149. TEST_F(ServerTest, HTTP2Magic) {
  8150. Request req;
  8151. req.method = "PRI";
  8152. req.path = "*";
  8153. req.body = "SM";
  8154. auto res = std::make_shared<Response>();
  8155. auto error = Error::Success;
  8156. auto ret = cli_.send(req, *res, error);
  8157. ASSERT_TRUE(ret);
  8158. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8159. }
  8160. TEST_F(ServerTest, KeepAlive) {
  8161. auto res = cli_.Get("/hi");
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ(StatusCode::OK_200, res->status);
  8164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8165. EXPECT_EQ("Hello World!", res->body);
  8166. res = cli_.Get("/hi");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::OK_200, res->status);
  8169. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8170. EXPECT_EQ("Hello World!", res->body);
  8171. res = cli_.Get("/hi");
  8172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8173. EXPECT_EQ(StatusCode::OK_200, res->status);
  8174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8175. EXPECT_EQ("Hello World!", res->body);
  8176. res = cli_.Get("/not-exist");
  8177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8178. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8179. res = cli_.Post("/empty", "", "text/plain");
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::OK_200, res->status);
  8182. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8183. EXPECT_EQ("empty", res->body);
  8184. EXPECT_EQ("close", res->get_header_value("Connection"));
  8185. res = cli_.Post(
  8186. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8187. "text/plain");
  8188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8189. EXPECT_EQ(StatusCode::OK_200, res->status);
  8190. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8191. EXPECT_EQ("empty", res->body);
  8192. cli_.set_keep_alive(false);
  8193. res = cli_.Get("/last-request");
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(StatusCode::OK_200, res->status);
  8196. EXPECT_EQ("close", res->get_header_value("Connection"));
  8197. }
  8198. TEST_F(ServerTest, TooManyRedirect) {
  8199. cli_.set_follow_location(true);
  8200. auto res = cli_.Get("/redirect/0");
  8201. ASSERT_TRUE(!res);
  8202. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8203. }
  8204. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8205. Request req;
  8206. req.method = "FOOBAR";
  8207. req.path = "/hi";
  8208. cli_.set_keep_alive(true);
  8209. auto res = cli_.send(req);
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8212. EXPECT_EQ("close", res->get_header_value("Connection"));
  8213. EXPECT_FALSE(cli_.is_socket_open());
  8214. }
  8215. TEST_F(ServerTest, CustomRouteReadsBody) {
  8216. const std::string xml =
  8217. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8218. Request req;
  8219. req.method = "PROPFIND";
  8220. req.path = "/dav/dir";
  8221. req.set_header("Depth", "1");
  8222. req.body = xml;
  8223. auto res = cli_.send(req);
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8226. EXPECT_EQ(xml, res->body);
  8227. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8228. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8229. }
  8230. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8231. Request req;
  8232. req.method = "PROPFIND";
  8233. req.path = "/dav/42";
  8234. auto res = cli_.send(req);
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8237. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8238. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8239. }
  8240. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8241. Request req;
  8242. req.method = "PROPFIND";
  8243. req.path = "/dav-re/123";
  8244. auto res = cli_.send(req);
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8247. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8248. }
  8249. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8250. Request req;
  8251. req.method = "MKCOL";
  8252. req.path = "/dav-mkcol";
  8253. auto res = cli_.send(req);
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::Created_201, res->status);
  8256. }
  8257. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8258. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8259. Request req;
  8260. req.method = "REPORT";
  8261. req.path = "/dav-report";
  8262. req.body = xml;
  8263. auto res = cli_.send(req);
  8264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8265. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8266. EXPECT_EQ(xml, res->body);
  8267. }
  8268. // A content reader route must fire even when the request carries no body,
  8269. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8270. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8271. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8272. Request req;
  8273. req.method = "REPORT";
  8274. req.path = "/dav-report";
  8275. auto res = cli_.send(req);
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8278. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8279. }
  8280. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8281. Request req;
  8282. req.method = "PROPFIND";
  8283. req.path = "/not-dav";
  8284. auto res = cli_.send(req);
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8287. }
  8288. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8289. Request req;
  8290. req.method = "UNLOCK";
  8291. req.path = "/dav/dir";
  8292. cli_.set_keep_alive(true);
  8293. auto res = cli_.send(req);
  8294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8295. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8296. EXPECT_EQ("close", res->get_header_value("Connection"));
  8297. EXPECT_FALSE(cli_.is_socket_open());
  8298. }
  8299. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8300. // The mount point serves this path, but only for GET and HEAD.
  8301. auto get_res = cli_.Get("/dir/index.html");
  8302. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8303. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8304. Request req;
  8305. req.method = "PROPFIND";
  8306. req.path = "/dir/index.html";
  8307. auto res = cli_.send(req);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8310. }
  8311. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8312. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8313. cli_.set_keep_alive(true);
  8314. for (auto i = 0; i < 2; i++) {
  8315. Request req;
  8316. req.method = "PROPFIND";
  8317. req.path = "/dav/dir";
  8318. req.body = xml;
  8319. auto res = cli_.send(req);
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8322. EXPECT_EQ(xml, res->body);
  8323. EXPECT_TRUE(cli_.is_socket_open());
  8324. }
  8325. // A built-in method must still be served on the same connection.
  8326. cli_.set_keep_alive(false);
  8327. auto res = cli_.Get("/hi");
  8328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8329. EXPECT_EQ(StatusCode::OK_200, res->status);
  8330. EXPECT_EQ("close", res->get_header_value("Connection"));
  8331. }
  8332. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8333. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8334. Request req;
  8335. req.method = "PROPFIND";
  8336. req.path = "/dav/dir";
  8337. req.set_header("Expect", "100-continue");
  8338. req.body = xml;
  8339. auto res = cli_.send(req);
  8340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8341. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8342. EXPECT_EQ(xml, res->body);
  8343. }
  8344. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8345. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8346. TEST_F(ServerTest, Gzip) {
  8347. Headers headers;
  8348. headers.emplace("Accept-Encoding", "gzip, deflate");
  8349. auto res = cli_.Get("/compress", headers);
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8353. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8354. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8355. "7890123456789012345678901234567890",
  8356. res->body);
  8357. EXPECT_EQ(StatusCode::OK_200, res->status);
  8358. }
  8359. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8360. Headers headers;
  8361. headers.emplace("Accept-Encoding", "gzip, deflate");
  8362. auto res = cli_.Get("/compress-with-charset", headers);
  8363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8364. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8365. EXPECT_EQ("application/json; charset=utf-8",
  8366. res->get_header_value("Content-Type"));
  8367. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8368. "7890123456789012345678901234567890",
  8369. res->body);
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. }
  8372. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8373. Headers headers;
  8374. headers.emplace("Accept-Encoding", "");
  8375. auto res = cli_.Get("/compress", headers);
  8376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8377. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8379. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8380. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8381. "7890123456789012345678901234567890",
  8382. res->body);
  8383. EXPECT_EQ(StatusCode::OK_200, res->status);
  8384. }
  8385. TEST_F(ServerTest, GzipWithContentReceiver) {
  8386. Headers headers;
  8387. headers.emplace("Accept-Encoding", "gzip, deflate");
  8388. std::string body;
  8389. auto res = cli_.Get("/compress", headers,
  8390. [&](const char *data, uint64_t data_length) {
  8391. EXPECT_EQ(100U, data_length);
  8392. body.append(data, data_length);
  8393. return true;
  8394. });
  8395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8396. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8398. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8400. "7890123456789012345678901234567890",
  8401. body);
  8402. EXPECT_EQ(StatusCode::OK_200, res->status);
  8403. }
  8404. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8405. Headers headers;
  8406. headers.emplace("Accept-Encoding", "gzip, deflate");
  8407. cli_.set_decompress(false);
  8408. auto res = cli_.Get("/compress", headers);
  8409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8410. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8411. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8412. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8413. EXPECT_EQ(33U, res->body.size());
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. }
  8416. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8417. Headers headers;
  8418. headers.emplace("Accept-Encoding", "");
  8419. std::string body;
  8420. auto res = cli_.Get("/compress", headers,
  8421. [&](const char *data, uint64_t data_length) {
  8422. EXPECT_EQ(100U, data_length);
  8423. body.append(data, data_length);
  8424. return true;
  8425. });
  8426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8427. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8428. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8429. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8430. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8431. "7890123456789012345678901234567890",
  8432. body);
  8433. EXPECT_EQ(StatusCode::OK_200, res->status);
  8434. }
  8435. TEST_F(ServerTest, NoGzip) {
  8436. Headers headers;
  8437. headers.emplace("Accept-Encoding", "gzip, deflate");
  8438. auto res = cli_.Get("/nocompress", headers);
  8439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8440. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8441. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8442. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8443. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8444. "7890123456789012345678901234567890",
  8445. res->body);
  8446. EXPECT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8449. Headers headers;
  8450. headers.emplace("Accept-Encoding", "gzip, deflate");
  8451. std::string body;
  8452. auto res = cli_.Get("/nocompress", headers,
  8453. [&](const char *data, uint64_t data_length) {
  8454. EXPECT_EQ(100U, data_length);
  8455. body.append(data, data_length);
  8456. return true;
  8457. });
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8460. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8461. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8462. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8463. "7890123456789012345678901234567890",
  8464. body);
  8465. EXPECT_EQ(StatusCode::OK_200, res->status);
  8466. }
  8467. TEST_F(ServerTest, MultipartFormDataGzip) {
  8468. UploadFormDataItems items = {
  8469. {"key1", "test", "", ""},
  8470. {"key2", "--abcdefg123", "", ""},
  8471. };
  8472. cli_.set_compress(true);
  8473. auto res = cli_.Post("/compress-multipart", items);
  8474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8475. EXPECT_EQ(StatusCode::OK_200, res->status);
  8476. }
  8477. #endif
  8478. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8479. // Static file compression is opt-in, so these run their own server rather than
  8480. // flipping it on for the shared ServerTest fixture, which would silently
  8481. // rewrite what every other static file test is asserting.
  8482. class StaticFileCompressionTest : public ::testing::Test {
  8483. protected:
  8484. void TearDown() override {
  8485. if (t_.joinable()) {
  8486. svr_.stop();
  8487. t_.join();
  8488. }
  8489. }
  8490. int start(const std::function<void(Server &)> &configure = nullptr) {
  8491. // Serves the same tree as a directory of build-time compressed assets
  8492. // would be served: the mount point names the coding the files are already
  8493. // stored in. Registered before "/" so it is the one that matches.
  8494. svr_.set_mount_point("/pre-encoded", "./www",
  8495. {{"Content-Encoding", "gzip"}});
  8496. svr_.set_mount_point("/", "./www");
  8497. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8498. res.set_file_content("./www/dir/index.html", "text/html");
  8499. });
  8500. svr_.Get("/pre-encoded-file-content",
  8501. [](const Request & /*req*/, Response &res) {
  8502. res.set_header("Content-Encoding", "gzip");
  8503. res.set_file_content("./www/dir/index.html", "text/html");
  8504. });
  8505. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8506. res.set_content_provider(
  8507. 6, "text/plain",
  8508. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8509. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8510. return true;
  8511. });
  8512. });
  8513. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8514. res.set_content_provider(
  8515. 1000, "text/plain",
  8516. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8517. if (offset < 100) {
  8518. std::string data(100, 'A');
  8519. sink.write(data.data(), data.size());
  8520. return true;
  8521. }
  8522. std::this_thread::sleep_for(std::chrono::seconds(2));
  8523. std::string data(900, 'B');
  8524. sink.write(data.data(), data.size());
  8525. return true;
  8526. });
  8527. });
  8528. if (configure) { configure(svr_); }
  8529. auto port = svr_.bind_to_any_port(HOST);
  8530. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8531. svr_.wait_until_ready();
  8532. return port;
  8533. }
  8534. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8535. // Every file under ./www except 1MB.txt is smaller than the default
  8536. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8537. // it out of the way.
  8538. static void enable_without_floor(Server &svr) {
  8539. svr.set_static_file_compression(true);
  8540. svr.set_static_file_compression_min_length(0);
  8541. }
  8542. Server svr_;
  8543. std::thread t_;
  8544. };
  8545. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8546. auto port = start();
  8547. Client cli(HOST, port);
  8548. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8550. EXPECT_EQ(StatusCode::OK_200, res->status);
  8551. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8552. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8553. EXPECT_EQ(1048576U, res->body.size());
  8554. }
  8555. TEST_F(StaticFileCompressionTest, MountPoint) {
  8556. auto port = start(enable);
  8557. Client cli(HOST, port);
  8558. cli.set_decompress(false);
  8559. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8561. EXPECT_EQ(StatusCode::OK_200, res->status);
  8562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8563. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8564. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8565. // The response stays self-delimiting: a length, not a chunked body.
  8566. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8567. EXPECT_EQ(std::to_string(res->body.size()),
  8568. res->get_header_value("Content-Length"));
  8569. EXPECT_LT(res->body.size(), 1048576U);
  8570. EXPECT_FALSE(res->body.empty());
  8571. }
  8572. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8573. auto port = start(enable);
  8574. Client cli(HOST, port);
  8575. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8577. EXPECT_EQ(StatusCode::OK_200, res->status);
  8578. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8579. EXPECT_EQ(1048576U, res->body.size());
  8580. }
  8581. TEST_F(StaticFileCompressionTest, FileContent) {
  8582. auto port = start(enable_without_floor);
  8583. Client cli(HOST, port);
  8584. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8586. EXPECT_EQ(StatusCode::OK_200, res->status);
  8587. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8588. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8589. EXPECT_EQ(104U, res->body.size());
  8590. }
  8591. // A handler that serves an already-encoded file names the coding itself. The
  8592. // file-backed path decided its coding from Accept-Encoding and the content
  8593. // type alone, so it compressed the stored bytes a second time and appended a
  8594. // second Content-Encoding field line.
  8595. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8596. auto port = start(enable_without_floor);
  8597. Client cli(HOST, port);
  8598. cli.set_decompress(false);
  8599. auto res = cli.Get("/pre-encoded-file-content",
  8600. Headers{{"Accept-Encoding", "gzip"}});
  8601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8602. EXPECT_EQ(StatusCode::OK_200, res->status);
  8603. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8604. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8605. // Vary belongs to a coding the server chose, and it chose none here.
  8606. EXPECT_FALSE(res->has_header("Vary"));
  8607. // The file travels exactly as it is stored on disk.
  8608. EXPECT_EQ(104U, res->body.size());
  8609. }
  8610. // The 1MB file clears the default floor, so this one runs the configuration a
  8611. // deployment would actually have.
  8612. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8613. auto port = start(enable);
  8614. Client cli(HOST, port);
  8615. cli.set_decompress(false);
  8616. auto res =
  8617. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8619. EXPECT_EQ(StatusCode::OK_200, res->status);
  8620. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8621. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8622. EXPECT_FALSE(res->has_header("Vary"));
  8623. EXPECT_EQ(1048576U, res->body.size());
  8624. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8625. }
  8626. TEST_F(StaticFileCompressionTest, Head) {
  8627. auto port = start(enable);
  8628. Client cli(HOST, port);
  8629. cli.set_decompress(false);
  8630. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8631. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8632. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8634. EXPECT_EQ(StatusCode::OK_200, res->status);
  8635. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8636. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8637. // HEAD still reports the size a GET would return.
  8638. EXPECT_EQ(get->get_header_value("Content-Length"),
  8639. res->get_header_value("Content-Length"));
  8640. EXPECT_TRUE(res->body.empty());
  8641. }
  8642. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8643. auto port = start(enable);
  8644. Client cli(HOST, port);
  8645. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8646. {"Accept-Encoding", "gzip"}});
  8647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8648. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8649. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8650. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8651. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8652. EXPECT_EQ("cd", res->body);
  8653. }
  8654. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8655. auto port = start(enable);
  8656. Client cli(HOST, port);
  8657. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8659. EXPECT_EQ(StatusCode::OK_200, res->status);
  8660. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8661. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8662. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8663. }
  8664. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8665. auto port = start(enable);
  8666. Client cli(HOST, port);
  8667. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8669. EXPECT_EQ(StatusCode::OK_200, res->status);
  8670. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8671. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8672. EXPECT_TRUE(res->body.empty());
  8673. }
  8674. TEST_F(StaticFileCompressionTest, MinLength) {
  8675. auto port = start(enable);
  8676. Client cli(HOST, port);
  8677. // 104 bytes, well under the default floor. Compressing it would add the
  8678. // gzip header and trailer to a body that already fits in one packet.
  8679. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8683. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8684. }
  8685. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8686. auto port = start([](Server &svr) {
  8687. svr.set_static_file_compression(true);
  8688. svr.set_static_file_compression_min_length(1);
  8689. });
  8690. Client cli(HOST, port);
  8691. cli.set_decompress(false);
  8692. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8694. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8695. // A 9-byte file comes back larger than it went in, because gzip's header and
  8696. // trailer outweigh anything deflate can save. That is the end of the range
  8697. // the floor exists to keep out.
  8698. EXPECT_GT(res->body.size(), 9U);
  8699. }
  8700. TEST_F(StaticFileCompressionTest, MaxLength) {
  8701. auto port = start([](Server &svr) {
  8702. svr.set_static_file_compression(true);
  8703. svr.set_static_file_compression_min_length(0);
  8704. svr.set_static_file_compression_max_length(1024);
  8705. });
  8706. Client cli(HOST, port);
  8707. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8708. // defines `small` as a macro on Windows.
  8709. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8710. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8711. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8712. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8713. // Under it: compressed.
  8714. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8715. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8716. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8717. }
  8718. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8719. auto port = start(enable_without_floor);
  8720. Client cli(HOST, port);
  8721. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8722. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8723. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8724. auto identity_etag = identity->get_header_value("ETag");
  8725. ASSERT_FALSE(identity_etag.empty());
  8726. auto gzipped =
  8727. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8728. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8729. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8730. auto gzip_etag = gzipped->get_header_value("ETag");
  8731. ASSERT_FALSE(gzip_etag.empty());
  8732. // Two representations, two validators.
  8733. EXPECT_NE(identity_etag, gzip_etag);
  8734. // Each one revalidates against the request that would produce it...
  8735. auto fresh =
  8736. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8737. {"If-None-Match", gzip_etag}});
  8738. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8739. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8740. auto fresh_identity =
  8741. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8742. {"If-None-Match", identity_etag}});
  8743. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8744. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8745. // ...and not against the other representation.
  8746. auto crossed =
  8747. cli.Get("/dir/index.html",
  8748. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8749. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8750. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8751. }
  8752. // The opt-in covers responses the server reads off disk itself. A caller's own
  8753. // known-length provider keeps its Content-Length and, more importantly, keeps
  8754. // delivering incrementally: routing it through a compressor would hold every
  8755. // write back until zlib's window filled.
  8756. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8757. auto port = start(enable);
  8758. Client cli(HOST, port);
  8759. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8761. EXPECT_EQ(StatusCode::OK_200, res->status);
  8762. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8763. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8764. EXPECT_EQ("aaabbb", res->body);
  8765. }
  8766. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8767. auto port = start(enable);
  8768. Client cli(HOST, port);
  8769. cli.set_read_timeout(1, 0);
  8770. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8771. Headers{{"Accept-Encoding", "gzip"}});
  8772. ASSERT_TRUE(handle.is_valid());
  8773. // The provider writes 100 bytes and then stalls for longer than the read
  8774. // timeout. Those first bytes have to arrive anyway: run the response through
  8775. // a compressor and zlib holds them until its window fills, so the read would
  8776. // come back empty instead.
  8777. char buf[256];
  8778. auto n = handle.read(buf, sizeof(buf));
  8779. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8780. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8781. }
  8782. #endif
  8783. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8784. TEST_F(ServerTest, Brotli) {
  8785. Headers headers;
  8786. headers.emplace("Accept-Encoding", "br");
  8787. auto res = cli_.Get("/compress", headers);
  8788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8789. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8790. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8791. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8792. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8793. "7890123456789012345678901234567890",
  8794. res->body);
  8795. EXPECT_EQ(StatusCode::OK_200, res->status);
  8796. }
  8797. #endif
  8798. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8799. TEST_F(ServerTest, Zstd) {
  8800. Headers headers;
  8801. headers.emplace("Accept-Encoding", "zstd");
  8802. auto res = cli_.Get("/compress", headers);
  8803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8804. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8805. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8806. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8807. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8808. "7890123456789012345678901234567890",
  8809. res->body);
  8810. EXPECT_EQ(StatusCode::OK_200, res->status);
  8811. }
  8812. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8813. Headers headers;
  8814. headers.emplace("Accept-Encoding", "");
  8815. auto res = cli_.Get("/compress", headers);
  8816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8817. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8818. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8819. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8820. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8821. "7890123456789012345678901234567890",
  8822. res->body);
  8823. EXPECT_EQ(StatusCode::OK_200, res->status);
  8824. }
  8825. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8826. Headers headers;
  8827. headers.emplace("Accept-Encoding", "zstd");
  8828. std::string body;
  8829. auto res = cli_.Get("/compress", headers,
  8830. [&](const char *data, uint64_t data_length) {
  8831. EXPECT_EQ(100U, data_length);
  8832. body.append(data, data_length);
  8833. return true;
  8834. });
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8838. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8839. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8840. "7890123456789012345678901234567890",
  8841. body);
  8842. EXPECT_EQ(StatusCode::OK_200, res->status);
  8843. }
  8844. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8845. Headers headers;
  8846. headers.emplace("Accept-Encoding", "zstd");
  8847. cli_.set_decompress(false);
  8848. auto res = cli_.Get("/compress", headers);
  8849. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8850. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8851. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8852. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8854. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8855. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8856. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8857. EXPECT_EQ(StatusCode::OK_200, res->status);
  8858. ASSERT_EQ(26U, res->body.size());
  8859. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8860. 0);
  8861. }
  8862. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8863. Headers headers;
  8864. headers.emplace("Accept-Encoding", "");
  8865. std::string body;
  8866. auto res = cli_.Get("/compress", headers,
  8867. [&](const char *data, uint64_t data_length) {
  8868. EXPECT_EQ(100U, data_length);
  8869. body.append(data, data_length);
  8870. return true;
  8871. });
  8872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8873. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8874. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8875. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8876. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8877. "7890123456789012345678901234567890",
  8878. body);
  8879. EXPECT_EQ(StatusCode::OK_200, res->status);
  8880. }
  8881. TEST_F(ServerTest, NoZstd) {
  8882. Headers headers;
  8883. headers.emplace("Accept-Encoding", "zstd");
  8884. auto res = cli_.Get("/nocompress", headers);
  8885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8886. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8887. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8888. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8889. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8890. "7890123456789012345678901234567890",
  8891. res->body);
  8892. EXPECT_EQ(StatusCode::OK_200, res->status);
  8893. }
  8894. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8895. Headers headers;
  8896. headers.emplace("Accept-Encoding", "zstd");
  8897. std::string body;
  8898. auto res = cli_.Get("/nocompress", headers,
  8899. [&](const char *data, uint64_t data_length) {
  8900. EXPECT_EQ(100U, data_length);
  8901. body.append(data, data_length);
  8902. return true;
  8903. });
  8904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8905. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8906. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8907. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8908. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8909. "7890123456789012345678901234567890",
  8910. body);
  8911. EXPECT_EQ(StatusCode::OK_200, res->status);
  8912. }
  8913. // TODO: How to enable zstd ??
  8914. TEST_F(ServerTest, MultipartFormDataZstd) {
  8915. UploadFormDataItems items = {
  8916. {"key1", "test", "", ""},
  8917. {"key2", "--abcdefg123", "", ""},
  8918. };
  8919. Headers headers;
  8920. headers.emplace("Accept-Encoding", "zstd");
  8921. cli_.set_compress(true);
  8922. auto res = cli_.Post("/compress-multipart", headers, items);
  8923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8924. EXPECT_EQ(StatusCode::OK_200, res->status);
  8925. }
  8926. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8927. Headers headers;
  8928. headers.emplace("Accept-Encoding", "zstd");
  8929. cli_.set_compress(true);
  8930. auto res = cli_.Put(
  8931. "/put", headers, 3,
  8932. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8933. sink.os << "PUT";
  8934. return true;
  8935. },
  8936. "text/plain");
  8937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8938. EXPECT_EQ(StatusCode::OK_200, res->status);
  8939. EXPECT_EQ("PUT", res->body);
  8940. }
  8941. // Pre-compression logging tests
  8942. TEST_F(ServerTest, PreCompressionLogging) {
  8943. // Test data for compression (matches the actual /compress endpoint content)
  8944. const std::string test_content =
  8945. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8946. "3456789012345678901234567890";
  8947. // Variables to capture logging data
  8948. std::string pre_compression_body;
  8949. std::string pre_compression_content_type;
  8950. std::string pre_compression_content_encoding;
  8951. std::string post_compression_body;
  8952. std::string post_compression_content_type;
  8953. std::string post_compression_content_encoding;
  8954. // Set up pre-compression logger
  8955. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8956. const Response &res) {
  8957. pre_compression_body = res.body;
  8958. pre_compression_content_type = res.get_header_value("Content-Type");
  8959. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8960. });
  8961. // Set up post-compression logger
  8962. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8963. post_compression_body = res.body;
  8964. post_compression_content_type = res.get_header_value("Content-Type");
  8965. post_compression_content_encoding =
  8966. res.get_header_value("Content-Encoding");
  8967. });
  8968. // Test with gzip compression
  8969. Headers headers;
  8970. headers.emplace("Accept-Encoding", "gzip");
  8971. auto res = cli_.Get("/compress", headers);
  8972. // Verify response was compressed
  8973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8974. EXPECT_EQ(StatusCode::OK_200, res->status);
  8975. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8976. // Verify pre-compression logger captured uncompressed content
  8977. EXPECT_EQ(test_content, pre_compression_body);
  8978. EXPECT_EQ("text/plain", pre_compression_content_type);
  8979. EXPECT_TRUE(pre_compression_content_encoding
  8980. .empty()); // No encoding header before compression
  8981. // Verify post-compression logger captured compressed content
  8982. EXPECT_NE(test_content,
  8983. post_compression_body); // Should be different after compression
  8984. EXPECT_EQ("text/plain", post_compression_content_type);
  8985. EXPECT_EQ("gzip", post_compression_content_encoding);
  8986. // Verify compressed content is smaller
  8987. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8988. }
  8989. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8990. const std::string test_content =
  8991. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8992. "3456789012345678901234567890";
  8993. std::string pre_compression_body;
  8994. std::string post_compression_body;
  8995. svr_.set_pre_compression_logger(
  8996. [&](const Request & /*req*/, const Response &res) {
  8997. pre_compression_body = res.body;
  8998. });
  8999. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9000. post_compression_body = res.body;
  9001. });
  9002. Headers headers;
  9003. headers.emplace("Accept-Encoding", "br");
  9004. auto res = cli_.Get("/compress", headers);
  9005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9006. EXPECT_EQ(StatusCode::OK_200, res->status);
  9007. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9008. // Verify pre-compression content is uncompressed
  9009. EXPECT_EQ(test_content, pre_compression_body);
  9010. // Verify post-compression content is compressed
  9011. EXPECT_NE(test_content, post_compression_body);
  9012. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9013. }
  9014. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9015. const std::string test_content =
  9016. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9017. "3456789012345678901234567890";
  9018. std::string pre_compression_body;
  9019. std::string post_compression_body;
  9020. svr_.set_pre_compression_logger(
  9021. [&](const Request & /*req*/, const Response &res) {
  9022. pre_compression_body = res.body;
  9023. });
  9024. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9025. post_compression_body = res.body;
  9026. });
  9027. // Request without compression (use /nocompress endpoint)
  9028. Headers headers;
  9029. auto res = cli_.Get("/nocompress", headers);
  9030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9031. EXPECT_EQ(StatusCode::OK_200, res->status);
  9032. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9033. // Pre-compression logger should not be called when no compression is applied
  9034. EXPECT_TRUE(
  9035. pre_compression_body.empty()); // Pre-compression logger not called
  9036. EXPECT_EQ(
  9037. test_content,
  9038. post_compression_body); // Post-compression logger captures final content
  9039. }
  9040. TEST_F(ServerTest, LoggerSeesContentLength) {
  9041. size_t logged_content_length = 0;
  9042. std::string logged_content_length_header;
  9043. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9044. logged_content_length = res.content_length_;
  9045. logged_content_length_header = res.get_header_value("Content-Length");
  9046. });
  9047. auto res = cli_.Get("/nocompress");
  9048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9049. EXPECT_EQ(StatusCode::OK_200, res->status);
  9050. EXPECT_EQ(res->body.size(), logged_content_length);
  9051. EXPECT_EQ(std::to_string(logged_content_length),
  9052. logged_content_length_header);
  9053. }
  9054. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9055. const std::string test_content =
  9056. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9057. "3456789012345678901234567890";
  9058. std::string pre_compression_body;
  9059. bool pre_logger_called = false;
  9060. // Set only pre-compression logger
  9061. svr_.set_pre_compression_logger(
  9062. [&](const Request & /*req*/, const Response &res) {
  9063. pre_compression_body = res.body;
  9064. pre_logger_called = true;
  9065. });
  9066. Headers headers;
  9067. headers.emplace("Accept-Encoding", "gzip");
  9068. auto res = cli_.Get("/compress", headers);
  9069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9070. EXPECT_EQ(StatusCode::OK_200, res->status);
  9071. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9072. // Verify pre-compression logger was called
  9073. EXPECT_TRUE(pre_logger_called);
  9074. EXPECT_EQ(test_content, pre_compression_body);
  9075. }
  9076. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9077. {
  9078. // Test with Expect: 100-continue header - success case
  9079. // Server returns 100 Continue, client sends body, server returns 200 OK
  9080. Request req;
  9081. req.method = "POST";
  9082. req.path = "/post-large";
  9083. req.set_header("Expect", "100-continue");
  9084. req.body = LARGE_DATA;
  9085. Response res;
  9086. auto error = Error::Success;
  9087. cli_.set_keep_alive(true);
  9088. auto ret = cli_.send(req, res, error);
  9089. EXPECT_TRUE(ret);
  9090. EXPECT_EQ(StatusCode::OK_200, res.status);
  9091. EXPECT_EQ(LARGE_DATA, res.body);
  9092. }
  9093. {
  9094. // Test with Expect: 100-continue header - error case
  9095. // Client should not send the body when server returns an error
  9096. Request req;
  9097. req.method = "POST";
  9098. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9099. req.set_header("Expect", "100-continue");
  9100. req.body = LARGE_DATA;
  9101. Response res;
  9102. auto error = Error::Success;
  9103. auto start = std::chrono::high_resolution_clock::now();
  9104. cli_.set_keep_alive(true);
  9105. auto ret = cli_.send(req, res, error);
  9106. auto end = std::chrono::high_resolution_clock::now();
  9107. auto elapsed =
  9108. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9109. .count();
  9110. // With Expect: 100-continue, request completes successfully but with error
  9111. EXPECT_TRUE(ret);
  9112. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9113. EXPECT_EQ("close", res.get_header_value("Connection"));
  9114. EXPECT_FALSE(cli_.is_socket_open());
  9115. EXPECT_LE(elapsed, 2000);
  9116. }
  9117. {
  9118. // Send an extra GET request to ensure error recovery without hanging
  9119. Request req;
  9120. req.method = "GET";
  9121. req.path = "/hi";
  9122. auto start = std::chrono::high_resolution_clock::now();
  9123. auto res = cli_.send(req);
  9124. auto end = std::chrono::high_resolution_clock::now();
  9125. auto elapsed =
  9126. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9127. .count();
  9128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9129. EXPECT_EQ(StatusCode::OK_200, res->status);
  9130. EXPECT_EQ("Hello World!", res->body);
  9131. EXPECT_LE(elapsed, 500);
  9132. }
  9133. }
  9134. TEST(ZstdDecompressor, ChunkedDecompression) {
  9135. std::string data;
  9136. for (size_t i = 0; i < 32 * 1024; ++i) {
  9137. data.push_back(static_cast<char>('a' + i % 26));
  9138. }
  9139. std::string compressed_data;
  9140. {
  9141. httplib::detail::zstd_compressor compressor;
  9142. bool result = compressor.compress(
  9143. data.data(), data.size(),
  9144. /*last=*/true,
  9145. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9146. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9147. compressed_data_size);
  9148. return true;
  9149. });
  9150. ASSERT_TRUE(result);
  9151. }
  9152. std::string decompressed_data;
  9153. {
  9154. httplib::detail::zstd_decompressor decompressor;
  9155. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9156. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9157. size_t chunk_size = 130;
  9158. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9159. chunk_begin += chunk_size) {
  9160. size_t current_chunk_size =
  9161. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9162. bool result = decompressor.decompress(
  9163. compressed_data.data() + chunk_begin, current_chunk_size,
  9164. [&](const char *decompressed_data_chunk,
  9165. size_t decompressed_data_chunk_size) {
  9166. decompressed_data.insert(decompressed_data.size(),
  9167. decompressed_data_chunk,
  9168. decompressed_data_chunk_size);
  9169. return true;
  9170. });
  9171. ASSERT_TRUE(result);
  9172. }
  9173. }
  9174. ASSERT_EQ(data, decompressed_data);
  9175. }
  9176. TEST(ZstdDecompressor, Decompress) {
  9177. std::string original_text = "Compressed with ZSTD";
  9178. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9179. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9180. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9181. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9182. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9183. std::string decompressed_data;
  9184. {
  9185. httplib::detail::zstd_decompressor decompressor;
  9186. bool result = decompressor.decompress(
  9187. compressed_data.data(), compressed_data.size(),
  9188. [&](const char *decompressed_data_chunk,
  9189. size_t decompressed_data_chunk_size) {
  9190. decompressed_data.insert(decompressed_data.size(),
  9191. decompressed_data_chunk,
  9192. decompressed_data_chunk_size);
  9193. return true;
  9194. });
  9195. ASSERT_TRUE(result);
  9196. }
  9197. ASSERT_EQ(original_text, decompressed_data);
  9198. }
  9199. #endif
  9200. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9201. // separate chunks so that the server sees each part in its own read(). Used to
  9202. // place a read boundary at a specific offset of a request body.
  9203. static bool send_request_in_parts(time_t read_timeout_sec,
  9204. const std::vector<std::string> &parts,
  9205. std::string *resp = nullptr,
  9206. int port = PORT) {
  9207. auto error = Error::Success;
  9208. auto client_sock = detail::create_client_socket(
  9209. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9210. /*connection_timeout_sec=*/5, 0,
  9211. /*read_timeout_sec=*/5, 0,
  9212. /*write_timeout_sec=*/5, 0, std::string(), error);
  9213. if (client_sock == INVALID_SOCKET) { return false; }
  9214. auto ret = detail::process_client_socket(
  9215. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9216. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9217. for (size_t i = 0; i < parts.size(); i++) {
  9218. const auto &part = parts[i];
  9219. if (part.size() !=
  9220. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9221. return false;
  9222. }
  9223. if (i + 1 < parts.size()) {
  9224. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9225. }
  9226. }
  9227. char buf[512];
  9228. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9229. while (line_reader.getline()) {
  9230. if (resp) { *resp += line_reader.ptr(); }
  9231. }
  9232. return true;
  9233. });
  9234. detail::close_socket(client_sock);
  9235. return ret;
  9236. }
  9237. // Sends a raw request to a server listening at HOST:PORT.
  9238. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9239. std::string *resp = nullptr, int port = PORT) {
  9240. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9241. }
  9242. #ifdef CPPHTTPLIB_SSL_ENABLED
  9243. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9245. ASSERT_TRUE(svr.is_valid());
  9246. svr.set_read_timeout(1, 0);
  9247. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9248. auto se = detail::scope_exit([&] {
  9249. svr.stop();
  9250. t.join();
  9251. ASSERT_FALSE(svr.is_running());
  9252. });
  9253. svr.wait_until_ready();
  9254. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9255. // keeps each wait well within the read timeout. The server gives up a
  9256. // second in, so the bytes sent after that fail.
  9257. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9258. parts.resize(26, std::string(1, '\0'));
  9259. EXPECT_FALSE(send_request_in_parts(5, parts));
  9260. }
  9261. #endif
  9262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9263. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9264. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9265. const std::vector<std::string> &parts,
  9266. std::string *resp = nullptr,
  9267. int port = PORT) {
  9268. auto error = Error::Success;
  9269. auto sock = detail::create_client_socket(
  9270. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9271. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9272. /*write_timeout_sec=*/5, 0, std::string(), error);
  9273. if (sock == INVALID_SOCKET) { return false; }
  9274. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9275. auto ctx = SSL_CTX_new(TLS_client_method());
  9276. auto ssl = SSL_new(ctx);
  9277. auto ssl_se = detail::scope_exit([&] {
  9278. SSL_free(ssl);
  9279. SSL_CTX_free(ctx);
  9280. });
  9281. SSL_set_fd(ssl, static_cast<int>(sock));
  9282. if (SSL_connect(ssl) != 1) { return false; }
  9283. for (size_t i = 0; i < parts.size(); i++) {
  9284. const auto &part = parts[i];
  9285. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9286. static_cast<int>(part.size())) {
  9287. return false;
  9288. }
  9289. if (i + 1 < parts.size()) {
  9290. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9291. }
  9292. }
  9293. char buf[512];
  9294. int n;
  9295. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9296. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9297. }
  9298. return true;
  9299. }
  9300. #endif
  9301. // The request line, then a header value a byte at a time.
  9302. static std::vector<std::string> slow_request_head_parts() {
  9303. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9304. parts.resize(26, "a");
  9305. parts.emplace_back("\r\n\r\n");
  9306. return parts;
  9307. }
  9308. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9309. // within the one-second read timeout. The server gives up a second in, before
  9310. // the head is complete.
  9311. static void
  9312. expect_slow_request_head_dropped(Server &svr,
  9313. const std::function<std::string()> &send) {
  9314. std::atomic<bool> handled(false);
  9315. svr.Get("/", [&](const Request &, Response &res) {
  9316. handled = true;
  9317. res.set_content("ok", "text/plain");
  9318. });
  9319. svr.set_read_timeout(1, 0);
  9320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9321. auto se = detail::scope_exit([&] {
  9322. svr.stop();
  9323. t.join();
  9324. ASSERT_FALSE(svr.is_running());
  9325. });
  9326. svr.wait_until_ready();
  9327. auto resp = send();
  9328. EXPECT_FALSE(handled);
  9329. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9330. }
  9331. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9332. Server svr;
  9333. expect_slow_request_head_dropped(svr, [] {
  9334. std::string resp;
  9335. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9336. return resp;
  9337. });
  9338. }
  9339. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9340. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9342. ASSERT_TRUE(svr.is_valid());
  9343. expect_slow_request_head_dropped(svr, [] {
  9344. std::string resp;
  9345. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9346. return resp;
  9347. });
  9348. }
  9349. #endif
  9350. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9351. Server svr;
  9352. std::string header_value;
  9353. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9354. header_value = req.get_header_value("foo");
  9355. res.set_content("ok", "text/plain");
  9356. });
  9357. thread t = thread([&] { svr.listen(HOST, PORT); });
  9358. auto se = detail::scope_exit([&] {
  9359. svr.stop();
  9360. t.join();
  9361. ASSERT_FALSE(svr.is_running());
  9362. });
  9363. svr.wait_until_ready();
  9364. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9365. // like characters are not treated the same - use vertical tab and escape.
  9366. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9367. "foo: \t \v bar \x1B\t \r\n"
  9368. "Connection: close\r\n"
  9369. "\r\n";
  9370. std::string res;
  9371. ASSERT_TRUE(send_request(5, req, &res));
  9372. EXPECT_EQ(header_value, "");
  9373. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9374. }
  9375. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9376. Server svr;
  9377. std::string received;
  9378. svr.Get("/order", [&](const Request &req, Response &res) {
  9379. received = entries_to_string(req.headers);
  9380. res.set_content("ok", "text/plain");
  9381. });
  9382. auto port = svr.bind_to_any_port(HOST);
  9383. thread t = thread([&] { svr.listen_after_bind(); });
  9384. auto se = detail::scope_exit([&] {
  9385. svr.stop();
  9386. t.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. const std::string req = "GET /order HTTP/1.1\r\n"
  9391. "Host: localhost\r\n"
  9392. "X-First: 1\r\n"
  9393. "X-Dup: a\r\n"
  9394. "X-Second: 2\r\n"
  9395. "X-Dup: b\r\n"
  9396. "Connection: close\r\n"
  9397. "\r\n";
  9398. std::string res;
  9399. ASSERT_TRUE(send_request(5, req, &res, port));
  9400. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9401. EXPECT_EQ(
  9402. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9403. received);
  9404. }
  9405. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9406. Server svr;
  9407. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9408. res.set_header("Set-Cookie", "first=1");
  9409. res.set_header("X-Between", "y");
  9410. res.set_header("Set-Cookie", "second=2");
  9411. res.set_content("ok", "text/plain");
  9412. });
  9413. auto port = svr.bind_to_any_port(HOST);
  9414. thread t = thread([&] { svr.listen_after_bind(); });
  9415. auto se = detail::scope_exit([&] {
  9416. svr.stop();
  9417. t.join();
  9418. ASSERT_FALSE(svr.is_running());
  9419. });
  9420. svr.wait_until_ready();
  9421. Client cli(HOST, port);
  9422. auto res = cli.Get("/cookies");
  9423. ASSERT_TRUE(res);
  9424. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9425. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9426. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9427. }
  9428. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9429. Server svr;
  9430. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9431. auto i = new int(0);
  9432. res.set_header("Trailer", "X-Safe, X-Reflected");
  9433. res.set_chunked_content_provider(
  9434. "text/plain",
  9435. [i](size_t /*offset*/, DataSink &sink) {
  9436. if (*i == 0) {
  9437. sink.os << "body";
  9438. } else {
  9439. Headers trailer;
  9440. // A valid trailer that must survive.
  9441. trailer.emplace("X-Safe", "safe");
  9442. // Attacker-controlled value carrying CR/LF (response splitting).
  9443. trailer.emplace("X-Reflected",
  9444. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9445. // Attacker-controlled name carrying CR/LF.
  9446. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9447. sink.done_with_trailer(trailer);
  9448. }
  9449. (*i)++;
  9450. return true;
  9451. },
  9452. [i](bool /*success*/) { delete i; });
  9453. });
  9454. thread t = thread([&] { svr.listen(HOST, PORT); });
  9455. auto se = detail::scope_exit([&] {
  9456. svr.stop();
  9457. t.join();
  9458. ASSERT_FALSE(svr.is_running());
  9459. });
  9460. svr.wait_until_ready();
  9461. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9462. "Host: " + HOST +
  9463. "\r\n"
  9464. "Connection: close\r\n"
  9465. "\r\n";
  9466. std::string res;
  9467. ASSERT_TRUE(send_request(5, req, &res));
  9468. // The injected fields must not appear anywhere in the raw response.
  9469. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9470. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9471. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9472. // Invalid trailers are dropped entirely, matching set_header().
  9473. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9474. // The valid trailer still passes through.
  9475. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9476. }
  9477. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9478. Server svr;
  9479. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9480. // res.headers is a public field an application can populate directly,
  9481. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9482. // A valid header that must survive.
  9483. res.headers.emplace("X-Safe", "safe");
  9484. // Attacker-controlled value carrying CR/LF (response splitting).
  9485. res.headers.emplace("X-Reflected",
  9486. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9487. // Attacker-controlled name carrying CR/LF.
  9488. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9489. res.set_content("body", "text/plain");
  9490. });
  9491. thread t = thread([&] { svr.listen(HOST, PORT); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. t.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.wait_until_ready();
  9498. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9499. "Host: " + HOST +
  9500. "\r\n"
  9501. "Connection: close\r\n"
  9502. "\r\n";
  9503. std::string res;
  9504. ASSERT_TRUE(send_request(5, req, &res));
  9505. // The injected fields must not appear anywhere in the raw response.
  9506. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9507. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9508. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9509. // Invalid headers are dropped entirely, matching set_header().
  9510. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9511. // The valid header still passes through.
  9512. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9513. }
  9514. // Forward declaration: in split builds split.py strips `inline` and moves the
  9515. // definition into httplib.cc, so detail::write_request_line is not visible from
  9516. // the public httplib.h. Re-declaring it here lets the tests link against the
  9517. // symbol in both header-only and split builds.
  9518. namespace httplib {
  9519. namespace detail {
  9520. ssize_t write_request_line(Stream &strm, const std::string &method,
  9521. const std::string &path);
  9522. } // namespace detail
  9523. } // namespace httplib
  9524. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9525. // A well-formed target is written verbatim.
  9526. {
  9527. detail::BufferStream strm;
  9528. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9529. EXPECT_GT(n, 0);
  9530. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9531. }
  9532. // A target carrying CR/LF, SP or other control octets must be rejected
  9533. // before anything reaches the wire, otherwise it splits the request line and
  9534. // injects a header or a whole request.
  9535. const std::string evil_targets[] = {
  9536. "/a\r\nInjected: pwned",
  9537. "/a\rInjected",
  9538. "/a\nInjected",
  9539. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9540. "/a b",
  9541. "/a\tb",
  9542. "/a\x7f",
  9543. };
  9544. for (const auto &evil : evil_targets) {
  9545. detail::BufferStream strm;
  9546. auto n = detail::write_request_line(strm, "GET", evil);
  9547. EXPECT_LT(n, 0);
  9548. EXPECT_TRUE(strm.get_buffer().empty());
  9549. }
  9550. }
  9551. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9552. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9553. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9554. // target reaches write_request. The client must fail cleanly with
  9555. // Error::Write instead of putting a request-line-less, header-injecting
  9556. // request on the wire.
  9557. Server svr;
  9558. svr.Get("/a", [](const Request &, Response &res) {
  9559. res.set_content("ok", "text/plain");
  9560. });
  9561. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9562. auto se = detail::scope_exit([&] {
  9563. svr.stop();
  9564. thread.join();
  9565. ASSERT_FALSE(svr.is_running());
  9566. });
  9567. svr.wait_until_ready();
  9568. {
  9569. Client cli(HOST, PORT);
  9570. cli.set_path_encode(false);
  9571. // The request is rejected before anything is written, so the connection
  9572. // stays silent and the subsequent response read would otherwise block for
  9573. // the full default read timeout. Shorten it -- the assertion is on the
  9574. // error, not the timeout.
  9575. cli.set_read_timeout(1, 0);
  9576. auto res = cli.Get("/a\r\nInjected: pwned");
  9577. EXPECT_FALSE(res);
  9578. EXPECT_EQ(Error::Write, res.error());
  9579. }
  9580. }
  9581. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9582. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9583. // including extension methods.
  9584. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9585. for (const auto &method : good_methods) {
  9586. detail::BufferStream strm;
  9587. auto n = detail::write_request_line(strm, method, "/");
  9588. EXPECT_GT(n, 0);
  9589. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9590. }
  9591. // A method carrying CR/LF would split the request line and smuggle a whole
  9592. // request ahead of the real one. A space or an empty method corrupts the
  9593. // request line. All must be rejected before anything reaches the wire.
  9594. const std::string evil_methods[] = {
  9595. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9596. "GET\r\nInjected: pwned",
  9597. "GET\r",
  9598. "GET\n",
  9599. "GE T",
  9600. "",
  9601. };
  9602. for (const auto &evil : evil_methods) {
  9603. detail::BufferStream strm;
  9604. auto n = detail::write_request_line(strm, evil, "/");
  9605. EXPECT_LT(n, 0);
  9606. EXPECT_TRUE(strm.get_buffer().empty());
  9607. }
  9608. }
  9609. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9610. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9611. // through Client::send must fail with Error::Write and no request, neither
  9612. // the smuggled one nor the real one, may reach the server.
  9613. Server svr;
  9614. std::atomic<int> request_count(0);
  9615. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9616. request_count++;
  9617. res.status = StatusCode::OK_200;
  9618. return Server::HandlerResponse::Handled;
  9619. });
  9620. auto port = svr.bind_to_any_port(HOST);
  9621. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9622. auto se = detail::scope_exit([&] {
  9623. svr.stop();
  9624. thread.join();
  9625. ASSERT_FALSE(svr.is_running());
  9626. });
  9627. svr.wait_until_ready();
  9628. {
  9629. Client cli(HOST, port);
  9630. const std::string evil_methods[] = {
  9631. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9632. "GE T",
  9633. "",
  9634. };
  9635. for (const auto &evil : evil_methods) {
  9636. Request req;
  9637. req.method = evil;
  9638. req.path = "/";
  9639. auto res = cli.send(req);
  9640. EXPECT_FALSE(res);
  9641. EXPECT_EQ(Error::Write, res.error());
  9642. }
  9643. auto handle =
  9644. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9645. EXPECT_FALSE(handle.is_valid());
  9646. EXPECT_EQ(Error::Write, handle.error);
  9647. // A valid request on the same client still goes through.
  9648. auto res = cli.Get("/");
  9649. ASSERT_TRUE(res);
  9650. EXPECT_EQ(StatusCode::OK_200, res->status);
  9651. }
  9652. EXPECT_EQ(1, request_count.load());
  9653. }
  9654. // Sends a raw request and verifies that there isn't a crash or exception.
  9655. static void test_raw_request(const std::string &req,
  9656. std::string *out = nullptr) {
  9657. Server svr;
  9658. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9659. res.set_content("ok", "text/plain");
  9660. });
  9661. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9662. res.set_content("ok", "text/plain");
  9663. });
  9664. svr.Get("/header_field_value_check",
  9665. [&](const Request & /*req*/, Response &res) {
  9666. res.set_content("ok", "text/plain");
  9667. });
  9668. svr.CustomRoute("PROPFIND", "/dav",
  9669. [&](const Request & /*req*/, Response &res) {
  9670. res.status = StatusCode::MultiStatus_207;
  9671. });
  9672. // Server read timeout must be longer than the client read timeout for the
  9673. // bug to reproduce, probably to force the server to process a request
  9674. // without a trailing blank line.
  9675. const time_t client_read_timeout_sec = 1;
  9676. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9677. bool listen_thread_ok = false;
  9678. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9679. auto se = detail::scope_exit([&] {
  9680. svr.stop();
  9681. t.join();
  9682. ASSERT_FALSE(svr.is_running());
  9683. EXPECT_TRUE(listen_thread_ok);
  9684. });
  9685. svr.wait_until_ready();
  9686. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9687. }
  9688. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9689. // A certain header line causes an exception if the header property is parsed
  9690. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9691. test_raw_request(
  9692. "GET /hi HTTP/1.1\r\n"
  9693. " : "
  9694. " "
  9695. " ");
  9696. }
  9697. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9698. // A certain header line causes an exception if the header property *name* is
  9699. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9700. // greedy matcher and requires backtracking when there are a lot of ":"
  9701. // characters.
  9702. // This occurs with libc++ but not libstdc++.
  9703. test_raw_request(
  9704. "GET /hi HTTP/1.1\r\n"
  9705. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9706. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9707. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9708. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9709. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9710. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9711. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9712. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9713. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9714. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9715. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9716. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9717. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9718. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9719. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9720. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9722. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9723. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9724. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9725. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9726. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9727. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9728. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9729. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9730. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9731. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9732. "&&&%%%");
  9733. }
  9734. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9735. // Make sure this doesn't crash the server.
  9736. // In a previous version of the header line regex, the "\r" rendered the line
  9737. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9738. // a new position where the leading white space ended and the field value
  9739. // began.
  9740. // The crash occurs with libc++ but not libstdc++.
  9741. test_raw_request("GET /hi HTTP/1.1\r\n"
  9742. "a:" +
  9743. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9744. "\r\n"
  9745. "\r\n");
  9746. }
  9747. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9748. const char *rejected[] = {
  9749. // RFC 9112 §3: one SP between the parts, and nothing else
  9750. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9751. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9752. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9753. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9754. // A request-target has no fragment
  9755. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9756. // An HTTP/1.1 request needs a Host
  9757. "GET /hi HTTP/1.1\r\n\r\n",
  9758. };
  9759. for (auto request : rejected) {
  9760. std::string out;
  9761. test_raw_request(request, &out);
  9762. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9763. }
  9764. std::string out;
  9765. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9766. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9767. }
  9768. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9769. // RFC 9112 §6.1
  9770. const char *requests[] = {
  9771. "PUT /put_hi HTTP/1.1\r\n"
  9772. "Host: localhost\r\n"
  9773. "Content-Length: 0\r\n"
  9774. "Transfer-Encoding: chunked\r\n"
  9775. "\r\n"
  9776. "0\r\n\r\n",
  9777. "PUT /put_hi HTTP/1.0\r\n"
  9778. "Connection: keep-alive\r\n"
  9779. "Transfer-Encoding: chunked\r\n"
  9780. "\r\n"
  9781. "0\r\n\r\n",
  9782. };
  9783. for (auto request : requests) {
  9784. std::string out;
  9785. test_raw_request(request, &out);
  9786. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9787. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9788. }
  9789. }
  9790. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9791. std::string out;
  9792. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9793. "Content-Type: text/plain\r\n"
  9794. "Transfer-Encoding: chunked\r\n"
  9795. "\r\n"
  9796. "nothex\r\n",
  9797. &out);
  9798. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9799. }
  9800. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9801. std::string out;
  9802. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9803. "Content-Type: text/plain\r\n"
  9804. "Transfer-Encoding: chunked\r\n"
  9805. "\r\n"
  9806. "3\r\n"
  9807. "xyz\r\n"
  9808. "NaN\r\n",
  9809. &out);
  9810. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9811. }
  9812. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9813. std::string out;
  9814. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9815. "Content-Type: text/plain\r\n"
  9816. "Transfer-Encoding: chunked\r\n"
  9817. "\r\n"
  9818. // Length is too large for 64 bits.
  9819. "1ffffffffffffffff\r\n"
  9820. "xyz\r\n",
  9821. &out);
  9822. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9823. }
  9824. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9825. test_raw_request("GET /hi HTTP/1.1\r\n"
  9826. "Content-Type: text/plain\r\n\r");
  9827. }
  9828. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9829. std::string out;
  9830. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9831. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9832. }
  9833. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9834. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9835. std::string out;
  9836. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9837. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9838. }
  9839. }
  9840. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9841. std::string out;
  9842. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9843. "Host: localhost\r\n"
  9844. "Connection: close\r\n\r\n",
  9845. &out);
  9846. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9847. }
  9848. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9849. Server svr;
  9850. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9851. EXPECT_TRUE(!req.remote_addr.empty());
  9852. });
  9853. thread t = thread([&] { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. });
  9859. svr.wait_until_ready();
  9860. // Send an invalid request line to trigger Bad Request
  9861. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9862. std::string out;
  9863. ASSERT_TRUE(send_request(5, bad_req, &out));
  9864. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9865. }
  9866. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9867. // answered right away rather than blocking on a read that waits for EOF.
  9868. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9869. std::string out;
  9870. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9871. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9872. }
  9873. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9874. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9875. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9876. for (const auto *method : methods) {
  9877. Server svr;
  9878. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9879. EXPECT_FALSE(svr.is_valid()) << method;
  9880. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9881. }
  9882. }
  9883. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9884. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9885. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9886. for (const auto *method : methods) {
  9887. Server svr;
  9888. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9889. EXPECT_FALSE(svr.is_valid()) << method;
  9890. }
  9891. }
  9892. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9893. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9894. "COPY", "MOVE", "LOCK",
  9895. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9896. Server svr;
  9897. for (const auto *method : methods) {
  9898. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9899. }
  9900. EXPECT_TRUE(svr.is_valid());
  9901. }
  9902. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9903. Server svr;
  9904. svr.CustomRoute("POST", "/x",
  9905. [](const Request &, Response &, const ContentReader &) {});
  9906. EXPECT_FALSE(svr.is_valid());
  9907. }
  9908. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9909. Server svr;
  9910. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9911. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9912. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9913. EXPECT_FALSE(svr.is_valid());
  9914. }
  9915. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9916. Server svr;
  9917. auto captured = Error::Success;
  9918. svr.set_error_logger(
  9919. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9920. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9921. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9922. }
  9923. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9924. std::string out;
  9925. std::string request(
  9926. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9927. test_raw_request(request, &out);
  9928. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9929. }
  9930. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9931. std::string out;
  9932. std::string request(
  9933. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9934. test_raw_request(request, &out);
  9935. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9936. }
  9937. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9938. std::string out;
  9939. std::string request(
  9940. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9941. test_raw_request(request, &out);
  9942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9943. }
  9944. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9945. std::string out;
  9946. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9947. "Host: localhost\r\n"
  9948. "Test: \r\n\r\n",
  9949. &out);
  9950. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9951. }
  9952. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9953. Server svr;
  9954. std::string x_custom;
  9955. std::string cookie;
  9956. std::string xff;
  9957. std::string x_unicode;
  9958. std::string x_iis;
  9959. svr.Get("/check", [&](const Request &req, Response &res) {
  9960. x_custom = req.get_header_value("X-Custom");
  9961. cookie = req.get_header_value("Cookie");
  9962. xff = req.get_header_value("X-Forwarded-For");
  9963. x_unicode = req.get_header_value("X-Unicode");
  9964. x_iis = req.get_header_value("X-IIS");
  9965. res.set_content("ok", "text/plain");
  9966. });
  9967. thread t = thread([&] { svr.listen(HOST, PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. t.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. });
  9973. svr.wait_until_ready();
  9974. const std::string req = "GET /check HTTP/1.1\r\n"
  9975. "Host: localhost\r\n"
  9976. "X-Custom: a%0D%0AInjected: b\r\n"
  9977. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9978. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9979. "X-Unicode: %E3%81%82\r\n"
  9980. "X-IIS: %u00E9\r\n"
  9981. "Connection: close\r\n"
  9982. "\r\n";
  9983. std::string res;
  9984. ASSERT_TRUE(send_request(5, req, &res));
  9985. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9986. // Every value must be returned verbatim (wire form), with no decoding.
  9987. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9988. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9989. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9990. EXPECT_EQ("%E3%81%82", x_unicode);
  9991. EXPECT_EQ("%u00E9", x_iis);
  9992. }
  9993. // Applications that previously relied on automatic percent-decoding can
  9994. // reproduce the old behavior by explicitly calling decode_path_component()
  9995. // or, for RFC 3986 conformance, decode_uri_component().
  9996. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9997. Server svr;
  9998. std::string decoded;
  9999. svr.Get("/check", [&](const Request &req, Response &res) {
  10000. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10001. res.set_content("ok", "text/plain");
  10002. });
  10003. thread t = thread([&] { svr.listen(HOST, PORT); });
  10004. auto se = detail::scope_exit([&] {
  10005. svr.stop();
  10006. t.join();
  10007. ASSERT_FALSE(svr.is_running());
  10008. });
  10009. svr.wait_until_ready();
  10010. const std::string req = "GET /check HTTP/1.1\r\n"
  10011. "Host: localhost\r\n"
  10012. "X-Custom: hello%20world\r\n"
  10013. "Connection: close\r\n"
  10014. "\r\n";
  10015. std::string res;
  10016. ASSERT_TRUE(send_request(5, req, &res));
  10017. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10018. EXPECT_EQ("hello world", decoded);
  10019. }
  10020. // Regression test for #2033. Browsers send Referer values that include
  10021. // percent-encoded characters such as %0A inside the URL. Decoding the
  10022. // header value would either trip the post-decode CR/LF/NUL guard (the
  10023. // original bug, returning 400) or, after that guard was relaxed, silently
  10024. // store a literal LF — both unacceptable. The wire form must round-trip.
  10025. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10026. Server svr;
  10027. std::string referer;
  10028. svr.Get("/check", [&](const Request &req, Response &res) {
  10029. referer = req.get_header_value("Referer");
  10030. res.set_content("ok", "text/plain");
  10031. });
  10032. thread t = thread([&] { svr.listen(HOST, PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. t.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.wait_until_ready();
  10039. const std::string req = "GET /check HTTP/1.1\r\n"
  10040. "Host: localhost\r\n"
  10041. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10042. "Connection: close\r\n"
  10043. "\r\n";
  10044. std::string res;
  10045. ASSERT_TRUE(send_request(5, req, &res));
  10046. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10047. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10048. }
  10049. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10050. Server svr;
  10051. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10052. res.set_header("Cache-Control", "no-cache");
  10053. res.set_chunked_content_provider(
  10054. "text/event-stream", [](size_t offset, DataSink &sink) {
  10055. std::string s = "data:";
  10056. s += std::to_string(offset);
  10057. s += "\n\n";
  10058. auto ret = sink.write(s.data(), s.size());
  10059. EXPECT_TRUE(ret);
  10060. std::this_thread::sleep_for(std::chrono::seconds(1));
  10061. return true;
  10062. });
  10063. });
  10064. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10065. svr.wait_until_ready();
  10066. Client client(HOST, PORT);
  10067. const Headers headers = {{"Accept", "text/event-stream"}};
  10068. auto get_thread = std::thread([&client, &headers]() {
  10069. auto res = client.Get(
  10070. "/events", headers,
  10071. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10072. });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. get_thread.join();
  10076. listen_thread.join();
  10077. ASSERT_FALSE(svr.is_running());
  10078. });
  10079. // Give GET time to get a few messages.
  10080. std::this_thread::sleep_for(std::chrono::seconds(2));
  10081. }
  10082. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10083. httplib::Server svr;
  10084. svr.Post("/hi",
  10085. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10086. res.status = StatusCode::OK_200;
  10087. });
  10088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10089. svr.wait_until_ready();
  10090. Client cli(HOST, PORT);
  10091. auto res = cli.Post("/hi", "data", "text/plain");
  10092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10093. EXPECT_EQ(StatusCode::OK_200, res->status);
  10094. svr.stop();
  10095. thread.join();
  10096. ASSERT_FALSE(svr.is_running());
  10097. res = cli.Post("/hi", "data", "text/plain");
  10098. ASSERT_FALSE(res);
  10099. }
  10100. TEST(ServerStopTest, ListenFailure) {
  10101. Server svr;
  10102. auto t = thread([&]() {
  10103. auto ret = svr.listen("????", PORT);
  10104. EXPECT_FALSE(ret);
  10105. });
  10106. svr.wait_until_ready();
  10107. svr.stop();
  10108. t.join();
  10109. }
  10110. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10111. TEST(ServerStopTest, Decommision) {
  10112. Server svr;
  10113. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10114. for (int i = 0; i < 4; i++) {
  10115. auto is_even = !(i % 2);
  10116. std::thread t{[&] {
  10117. try {
  10118. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10119. if (is_even) {
  10120. throw std::runtime_error("Some thing that happens to go wrong.");
  10121. }
  10122. svr.listen(HOST, PORT);
  10123. } catch (...) { svr.decommission(); }
  10124. }};
  10125. svr.wait_until_ready();
  10126. // Server is up
  10127. {
  10128. Client cli(HOST, PORT);
  10129. auto res = cli.Get("/hi");
  10130. if (is_even) {
  10131. EXPECT_FALSE(res);
  10132. } else {
  10133. EXPECT_TRUE(res);
  10134. EXPECT_EQ("hi...", res->body);
  10135. }
  10136. }
  10137. svr.stop();
  10138. t.join();
  10139. // Server is down...
  10140. {
  10141. Client cli(HOST, PORT);
  10142. auto res = cli.Get("/hi");
  10143. EXPECT_FALSE(res);
  10144. }
  10145. }
  10146. }
  10147. #endif
  10148. // Helper function for string body upload progress tests
  10149. template <typename SetupHandler, typename ClientCall>
  10150. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10151. ClientCall &&client_call,
  10152. const string &body) {
  10153. Server svr;
  10154. setup_handler(svr);
  10155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10156. auto se = detail::scope_exit([&] {
  10157. svr.stop();
  10158. t.join();
  10159. });
  10160. svr.wait_until_ready();
  10161. Client cli(HOST, PORT);
  10162. vector<uint64_t> progress_values;
  10163. bool progress_called = false;
  10164. auto res =
  10165. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10166. progress_values.push_back(current);
  10167. progress_called = true;
  10168. return true;
  10169. });
  10170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10171. EXPECT_EQ(200, res->status);
  10172. EXPECT_TRUE(progress_called);
  10173. }
  10174. TEST(UploadProgressTest, PostStringBodyBasic) {
  10175. TestStringBodyUploadProgress(
  10176. [](Server &svr) {
  10177. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10178. res.set_content("received", "text/plain");
  10179. });
  10180. },
  10181. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10182. return cli.Post("/test", body, "text/plain", progress_callback);
  10183. },
  10184. "test data for upload progress");
  10185. }
  10186. TEST(UploadProgressTest, PutStringBodyBasic) {
  10187. TestStringBodyUploadProgress(
  10188. [](Server &svr) {
  10189. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10190. res.set_content("put received", "text/plain");
  10191. });
  10192. },
  10193. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10194. return cli.Put("/test", body, "text/plain", progress_callback);
  10195. },
  10196. "put test data for upload progress");
  10197. }
  10198. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10199. TestStringBodyUploadProgress(
  10200. [](Server &svr) {
  10201. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10202. res.set_content("patch received", "text/plain");
  10203. });
  10204. },
  10205. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10206. return cli.Patch("/test", body, "text/plain", progress_callback);
  10207. },
  10208. "patch test data for upload progress");
  10209. }
  10210. // Helper function for content provider upload progress tests
  10211. template <typename SetupHandler, typename ClientCall>
  10212. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10213. ClientCall &&client_call) {
  10214. Server svr;
  10215. setup_handler(svr);
  10216. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10217. auto se = detail::scope_exit([&] {
  10218. svr.stop();
  10219. t.join();
  10220. });
  10221. svr.wait_until_ready();
  10222. Client cli(HOST, PORT);
  10223. vector<uint64_t> progress_values;
  10224. auto res =
  10225. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10226. progress_values.push_back(current);
  10227. return true;
  10228. });
  10229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10230. EXPECT_EQ(200, res->status);
  10231. EXPECT_FALSE(progress_values.empty());
  10232. }
  10233. TEST(UploadProgressTest, PostContentProviderProgress) {
  10234. TestContentProviderUploadProgress(
  10235. [](Server &svr) {
  10236. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10237. res.set_content("provider received", "text/plain");
  10238. });
  10239. },
  10240. [](Client &cli, UploadProgress progress_callback) {
  10241. return cli.Post(
  10242. "/test", 9,
  10243. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10244. sink.os << "test data";
  10245. return true;
  10246. },
  10247. "text/plain", progress_callback);
  10248. });
  10249. }
  10250. // Helper function for multipart upload progress tests
  10251. template <typename SetupHandler, typename ClientCall>
  10252. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10253. ClientCall &&client_call,
  10254. const string &endpoint) {
  10255. Server svr;
  10256. setup_handler(svr);
  10257. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10258. auto se = detail::scope_exit([&] {
  10259. svr.stop();
  10260. t.join();
  10261. });
  10262. svr.wait_until_ready();
  10263. Client cli(HOST, PORT);
  10264. vector<uint64_t> progress_values;
  10265. UploadFormDataItems items = {
  10266. {"field1", "value1", "", ""},
  10267. {"field2", "longer value for progress tracking test", "", ""},
  10268. {"file1", "file content data for upload progress", "test.txt",
  10269. "text/plain"}};
  10270. auto res = client_call(cli, endpoint, items,
  10271. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10272. progress_values.push_back(current);
  10273. return true;
  10274. });
  10275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10276. EXPECT_EQ(200, res->status);
  10277. EXPECT_FALSE(progress_values.empty());
  10278. }
  10279. TEST(UploadProgressTest, PostMultipartProgress) {
  10280. TestMultipartUploadProgress(
  10281. [](Server &svr) {
  10282. svr.Post("/multipart", [](const Request &req, Response &res) {
  10283. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10284. res.set_content("multipart received", "text/plain");
  10285. });
  10286. },
  10287. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10288. UploadProgress progress_callback) {
  10289. return cli.Post(endpoint, items, progress_callback);
  10290. },
  10291. "/multipart");
  10292. }
  10293. // Helper function for basic download progress tests
  10294. template <typename SetupHandler, typename ClientCall>
  10295. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10296. ClientCall &&client_call, const string &endpoint,
  10297. size_t expected_content_size) {
  10298. Server svr;
  10299. setup_handler(svr);
  10300. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10301. auto se = detail::scope_exit([&] {
  10302. svr.stop();
  10303. t.join();
  10304. });
  10305. svr.wait_until_ready();
  10306. Client cli(HOST, PORT);
  10307. vector<uint64_t> progress_values;
  10308. auto res = client_call(cli, endpoint,
  10309. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10310. progress_values.push_back(current);
  10311. return true;
  10312. });
  10313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10314. EXPECT_EQ(200, res->status);
  10315. EXPECT_FALSE(progress_values.empty());
  10316. EXPECT_EQ(expected_content_size, res->body.size());
  10317. }
  10318. TEST(DownloadProgressTest, GetBasic) {
  10319. TestBasicDownloadProgress(
  10320. [](Server &svr) {
  10321. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10322. string content(1000, 'D');
  10323. res.set_content(content, "text/plain");
  10324. });
  10325. },
  10326. [](Client &cli, const string &endpoint,
  10327. DownloadProgress progress_callback) {
  10328. return cli.Get(endpoint, progress_callback);
  10329. },
  10330. "/download", 1000u);
  10331. }
  10332. // Helper function for content receiver download progress tests
  10333. template <typename SetupHandler, typename ClientCall>
  10334. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10335. ClientCall &&client_call,
  10336. const string &endpoint,
  10337. size_t expected_content_size) {
  10338. Server svr;
  10339. setup_handler(svr);
  10340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10341. auto se = detail::scope_exit([&] {
  10342. svr.stop();
  10343. t.join();
  10344. });
  10345. svr.wait_until_ready();
  10346. Client cli(HOST, PORT);
  10347. vector<uint64_t> progress_values;
  10348. string received_body;
  10349. auto res = client_call(
  10350. cli, endpoint,
  10351. [&](const char *data, size_t data_length) -> bool {
  10352. received_body.append(data, data_length);
  10353. return true;
  10354. },
  10355. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10356. progress_values.push_back(current);
  10357. return true;
  10358. });
  10359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10360. EXPECT_EQ(200, res->status);
  10361. EXPECT_FALSE(progress_values.empty());
  10362. EXPECT_EQ(expected_content_size, received_body.size());
  10363. EXPECT_TRUE(res->body.empty());
  10364. }
  10365. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10366. TestContentReceiverDownloadProgress(
  10367. [](Server &svr) {
  10368. svr.Get("/download-receiver",
  10369. [](const Request & /*req*/, Response &res) {
  10370. string content(2000, 'R');
  10371. res.set_content(content, "text/plain");
  10372. });
  10373. },
  10374. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10375. DownloadProgress progress_callback) {
  10376. return cli.Get(endpoint, content_receiver, progress_callback);
  10377. },
  10378. "/download-receiver", 2000u);
  10379. }
  10380. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10381. // A provider reaching a pass with nothing to hand over - an empty buffer
  10382. // popped off a queue, say - must not be taken to mean the body is finished.
  10383. // It used to end the loop with the terminating chunk unwritten while the
  10384. // server still considered the response complete, so the peer waited for an
  10385. // end that never arrived.
  10386. Server svr;
  10387. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10388. auto step = std::make_shared<int>(0);
  10389. res.set_chunked_content_provider("text/plain",
  10390. [step](size_t /*offset*/, DataSink &sink) {
  10391. switch ((*step)++) {
  10392. case 0: sink.write("", 0); break;
  10393. case 1: sink.write("hello", 5); break;
  10394. default: sink.done(); break;
  10395. }
  10396. return true;
  10397. });
  10398. });
  10399. auto port = svr.bind_to_any_port(HOST);
  10400. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10401. auto listen_se = detail::scope_exit([&] {
  10402. svr.stop();
  10403. listen_thread.join();
  10404. ASSERT_FALSE(svr.is_running());
  10405. });
  10406. svr.wait_until_ready();
  10407. Client cli(HOST, port);
  10408. // Without the fix the body is never terminated, so bound the wait rather
  10409. // than letting the test hang on the default read timeout.
  10410. cli.set_read_timeout(5, 0);
  10411. auto res = cli.Get("/stream");
  10412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10413. EXPECT_EQ(StatusCode::OK_200, res->status);
  10414. EXPECT_EQ("hello", res->body);
  10415. }
  10416. TEST(StreamingTest, NoContentLengthStreaming) {
  10417. Server svr;
  10418. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10419. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10420. if (offset < 6) {
  10421. sink.os << (offset < 3 ? "a" : "b");
  10422. } else {
  10423. sink.done();
  10424. }
  10425. return true;
  10426. });
  10427. });
  10428. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10429. auto listen_se = detail::scope_exit([&] {
  10430. svr.stop();
  10431. listen_thread.join();
  10432. ASSERT_FALSE(svr.is_running());
  10433. });
  10434. svr.wait_until_ready();
  10435. Client client(HOST, PORT);
  10436. auto get_thread = std::thread([&client]() {
  10437. std::string s;
  10438. auto res =
  10439. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10440. s += std::string(data, len);
  10441. return true;
  10442. });
  10443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10444. EXPECT_EQ(StatusCode::OK_200, res->status);
  10445. EXPECT_EQ("aaabbb", s);
  10446. });
  10447. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10448. // Give GET time to get a few messages.
  10449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10450. }
  10451. TEST(MountTest, Unmount) {
  10452. Server svr;
  10453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10454. auto se = detail::scope_exit([&] {
  10455. svr.stop();
  10456. listen_thread.join();
  10457. ASSERT_FALSE(svr.is_running());
  10458. });
  10459. svr.wait_until_ready();
  10460. Client cli("localhost", PORT);
  10461. svr.set_mount_point("/mount2", "./www2");
  10462. auto res = cli.Get("/");
  10463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10465. res = cli.Get("/mount2/dir/test.html");
  10466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10467. EXPECT_EQ(StatusCode::OK_200, res->status);
  10468. svr.set_mount_point("/", "./www");
  10469. res = cli.Get("/dir/");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. EXPECT_EQ(StatusCode::OK_200, res->status);
  10472. svr.remove_mount_point("/");
  10473. res = cli.Get("/dir/");
  10474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10476. svr.remove_mount_point("/mount2");
  10477. res = cli.Get("/mount2/dir/test.html");
  10478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10480. }
  10481. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10482. Server svr;
  10483. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10484. svr.Get("/api/hello", [](const Request &, Response &res) {
  10485. res.set_content("api", "text/plain");
  10486. });
  10487. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10488. auto se = detail::scope_exit([&] {
  10489. svr.stop();
  10490. listen_thread.join();
  10491. ASSERT_FALSE(svr.is_running());
  10492. });
  10493. svr.wait_until_ready();
  10494. Client cli(HOST, PORT);
  10495. auto res = cli.Get("/dir/test.html");
  10496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10497. EXPECT_EQ(StatusCode::OK_200, res->status);
  10498. res = cli.Get("/api/hello");
  10499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10500. EXPECT_EQ(StatusCode::OK_200, res->status);
  10501. EXPECT_EQ("api", res->body);
  10502. }
  10503. TEST(MountTest, PathSegmentBoundary) {
  10504. Server svr;
  10505. svr.set_mount_point("/mount2", "./www2");
  10506. svr.set_mount_point("/", "./www");
  10507. auto port = svr.bind_to_any_port(HOST);
  10508. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10509. auto se = detail::scope_exit([&] {
  10510. svr.stop();
  10511. listen_thread.join();
  10512. ASSERT_FALSE(svr.is_running());
  10513. });
  10514. svr.wait_until_ready();
  10515. Client cli(HOST, port);
  10516. auto res = cli.Get("/mount2/dir/test.html");
  10517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10518. EXPECT_EQ(StatusCode::OK_200, res->status);
  10519. // "/mount2" must not match part-way through a path segment.
  10520. res = cli.Get("/mount2dir/test.html");
  10521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10523. // A mount point ending in '/' keeps matching every path below it.
  10524. res = cli.Get("/dir/test.html");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::OK_200, res->status);
  10527. }
  10528. TEST(MountTest, Redicect) {
  10529. Server svr;
  10530. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10531. auto se = detail::scope_exit([&] {
  10532. svr.stop();
  10533. listen_thread.join();
  10534. ASSERT_FALSE(svr.is_running());
  10535. });
  10536. svr.set_mount_point("/", "./www");
  10537. svr.wait_until_ready();
  10538. Client cli("localhost", PORT);
  10539. auto res = cli.Get("/dir/");
  10540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10541. EXPECT_EQ(StatusCode::OK_200, res->status);
  10542. res = cli.Get("/dir");
  10543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10544. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10545. res = cli.Get("/file");
  10546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10547. EXPECT_EQ(StatusCode::OK_200, res->status);
  10548. res = cli.Get("/file/");
  10549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10551. cli.set_follow_location(true);
  10552. res = cli.Get("/dir");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. }
  10556. TEST(MountTest, MultibytesPathName) {
  10557. Server svr;
  10558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10559. auto se = detail::scope_exit([&] {
  10560. svr.stop();
  10561. listen_thread.join();
  10562. ASSERT_FALSE(svr.is_running());
  10563. });
  10564. svr.set_mount_point("/", "./www");
  10565. svr.wait_until_ready();
  10566. Client cli("localhost", PORT);
  10567. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10569. EXPECT_EQ(StatusCode::OK_200, res->status);
  10570. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10571. }
  10572. #ifdef _WIN32
  10573. // Issue #2435: mmap::open() must succeed even when another handle holds
  10574. // the file open for writing (e.g. an active log file).
  10575. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10576. const char *path = "mmap_concurrent_writer_test.txt";
  10577. const char *content = "hello";
  10578. {
  10579. std::ofstream f(path, std::ios::binary);
  10580. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10581. }
  10582. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10583. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10584. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10585. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10586. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10587. detail::mmap m(path);
  10588. ASSERT_TRUE(m.is_open());
  10589. EXPECT_EQ(strlen(content), m.size());
  10590. char buf[8];
  10591. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10592. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10593. }
  10594. #endif
  10595. #ifndef _WIN32
  10596. // A directory or a device has no size to serve.
  10597. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10598. const char *path = "./mmap_not_regular_test_dir";
  10599. ASSERT_EQ(0, ::mkdir(path, 0755));
  10600. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10601. for (auto p : {path, "/dev/null"}) {
  10602. detail::mmap m(p);
  10603. EXPECT_FALSE(m.is_open()) << p;
  10604. EXPECT_EQ(0U, m.size()) << p;
  10605. }
  10606. Server svr;
  10607. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10608. res.set_file_content("/dev/null");
  10609. });
  10610. auto port = svr.bind_to_any_port(HOST);
  10611. thread t = thread([&] { svr.listen_after_bind(); });
  10612. auto se = detail::scope_exit([&] {
  10613. svr.stop();
  10614. t.join();
  10615. });
  10616. svr.wait_until_ready();
  10617. auto res = Client(HOST, port).Get("/null");
  10618. ASSERT_TRUE(res);
  10619. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10620. }
  10621. #endif
  10622. #ifdef __linux__
  10623. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10624. TEST(MmapTest, FileIsNotMapped) {
  10625. const char *path = "mmap_not_mapped_test.txt";
  10626. {
  10627. std::ofstream f(path, std::ios::binary);
  10628. f << "hello";
  10629. }
  10630. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10631. detail::mmap m(path);
  10632. ASSERT_TRUE(m.is_open());
  10633. std::ifstream maps("/proc/self/maps");
  10634. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10635. std::istreambuf_iterator<char>());
  10636. EXPECT_EQ(std::string::npos, mappings.find(path));
  10637. }
  10638. #endif
  10639. TEST(KeepAliveTest, ReadTimeout) {
  10640. Server svr;
  10641. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10642. std::this_thread::sleep_for(std::chrono::seconds(2));
  10643. res.set_content("a", "text/plain");
  10644. });
  10645. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10646. res.set_content("b", "text/plain");
  10647. });
  10648. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10649. auto se = detail::scope_exit([&] {
  10650. svr.stop();
  10651. listen_thread.join();
  10652. ASSERT_FALSE(svr.is_running());
  10653. });
  10654. svr.wait_until_ready();
  10655. Client cli("localhost", PORT);
  10656. cli.set_keep_alive(true);
  10657. cli.set_read_timeout(std::chrono::seconds(1));
  10658. auto resa = cli.Get("/a");
  10659. ASSERT_FALSE(resa);
  10660. EXPECT_EQ(Error::Read, resa.error());
  10661. auto resb = cli.Get("/b");
  10662. ASSERT_TRUE(resb);
  10663. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10664. EXPECT_EQ("b", resb->body);
  10665. }
  10666. TEST(KeepAliveTest, MaxCount) {
  10667. size_t keep_alive_max_count = 3;
  10668. Server svr;
  10669. svr.set_keep_alive_max_count(keep_alive_max_count);
  10670. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10671. res.set_content("Hello World!", "text/plain");
  10672. });
  10673. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10674. auto se = detail::scope_exit([&] {
  10675. svr.stop();
  10676. listen_thread.join();
  10677. ASSERT_FALSE(svr.is_running());
  10678. });
  10679. svr.wait_until_ready();
  10680. Client cli(HOST, PORT);
  10681. cli.set_keep_alive(true);
  10682. for (size_t i = 0; i < 5; i++) {
  10683. auto result = cli.Get("/hi");
  10684. ASSERT_TRUE(result);
  10685. EXPECT_EQ(StatusCode::OK_200, result->status);
  10686. if (i == keep_alive_max_count - 1) {
  10687. EXPECT_EQ("close", result->get_header_value("Connection"));
  10688. } else {
  10689. EXPECT_FALSE(result->has_header("Connection"));
  10690. }
  10691. }
  10692. }
  10693. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10694. // can pull the next one into the server's buffer. The server must serve it
  10695. // without waiting for the socket to become readable again. The keep-alive
  10696. // timeout outlasts the client's read timeout, so a request left waiting for it
  10697. // shows up as a missing response.
  10698. static void serve_pipelining_routes(Server &svr,
  10699. const std::function<void(int)> &client) {
  10700. svr.set_keep_alive_timeout(5);
  10701. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10702. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10703. });
  10704. svr.Post("/echo", [](const Request &req, Response &res) {
  10705. res.set_content("echo " + req.body, "text/plain");
  10706. });
  10707. auto port = svr.bind_to_any_port(HOST);
  10708. thread t = thread([&] { svr.listen_after_bind(); });
  10709. auto se = detail::scope_exit([&] {
  10710. svr.stop();
  10711. t.join();
  10712. });
  10713. svr.wait_until_ready();
  10714. client(port);
  10715. }
  10716. static std::string
  10717. send_pipelined_requests(const std::vector<std::string> &parts) {
  10718. Server svr;
  10719. std::string res;
  10720. serve_pipelining_routes(svr, [&](int port) {
  10721. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10722. });
  10723. return res;
  10724. }
  10725. static void expect_in_order(const std::string &res,
  10726. const std::vector<std::string> &bodies) {
  10727. size_t pos = 0;
  10728. for (const auto &body : bodies) {
  10729. pos = res.find(body, pos);
  10730. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10731. pos += body.size();
  10732. }
  10733. }
  10734. TEST(KeepAliveTest, PipelinedRequests) {
  10735. auto res = send_pipelined_requests(
  10736. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10737. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10738. "Content-Length: 4\r\n\r\nbody"
  10739. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10740. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10741. }
  10742. // The second request starts in the server's buffer and ends on the socket.
  10743. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10744. auto res =
  10745. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10746. "GET /hi/2 HTTP/1.1\r\nHo",
  10747. "st: localhost\r\nConnection: close\r\n\r\n"});
  10748. expect_in_order(res, {"hi 1", "hi 2"});
  10749. }
  10750. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10751. // CRLF after a body does not turn into a 400 for the next request.
  10752. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10753. auto res = send_pipelined_requests(
  10754. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10755. "Content-Length: 4\r\n\r\nbody\r\n"
  10756. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10757. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10758. expect_in_order(res, {"echo body", "hi 2"});
  10759. }
  10760. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10761. // must not be served as the next request.
  10762. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10763. auto res = send_pipelined_requests(
  10764. {"INVALID REQUEST LINE\r\n\r\n"
  10765. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10766. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10767. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10768. }
  10769. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10770. // Over TLS, the next request is held by the TLS library as already decrypted
  10771. // data rather than on the socket.
  10772. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10774. std::string res;
  10775. serve_pipelining_routes(svr, [&](int port) {
  10776. // One part, so all three requests arrive in one TLS record
  10777. EXPECT_TRUE(send_ssl_request_in_parts(
  10778. 2,
  10779. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10780. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10781. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10782. &res, port));
  10783. });
  10784. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10785. }
  10786. #endif
  10787. TEST(KeepAliveTest, Issue1041) {
  10788. Server svr;
  10789. svr.set_keep_alive_timeout(3);
  10790. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10791. res.set_content("Hello World!", "text/plain");
  10792. });
  10793. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. listen_thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. Client cli(HOST, PORT);
  10801. cli.set_keep_alive(true);
  10802. auto result = cli.Get("/hi");
  10803. ASSERT_TRUE(result);
  10804. EXPECT_EQ(StatusCode::OK_200, result->status);
  10805. std::this_thread::sleep_for(std::chrono::seconds(5));
  10806. result = cli.Get("/hi");
  10807. ASSERT_TRUE(result);
  10808. EXPECT_EQ(StatusCode::OK_200, result->status);
  10809. }
  10810. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10811. Server svr;
  10812. svr.set_keep_alive_max_count(0);
  10813. std::set<int> remote_ports;
  10814. svr.Get("/hi", [&](const Request &req, Response &res) {
  10815. remote_ports.insert(req.remote_port);
  10816. res.set_content("hi", "text/plain");
  10817. });
  10818. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10819. auto se = detail::scope_exit([&] {
  10820. svr.stop();
  10821. listen_thread.join();
  10822. ASSERT_FALSE(svr.is_running());
  10823. });
  10824. svr.wait_until_ready();
  10825. Client cli(HOST, PORT);
  10826. cli.set_keep_alive(true);
  10827. for (int i = 0; i < 3; i++) {
  10828. auto res = cli.Get("/hi");
  10829. ASSERT_TRUE(res);
  10830. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10831. }
  10832. // All three over one connection
  10833. EXPECT_EQ(1u, remote_ports.size());
  10834. }
  10835. TEST(KeepAliveTest, Issue1959) {
  10836. Server svr;
  10837. svr.set_keep_alive_timeout(5);
  10838. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10839. res.set_content("a", "text/plain");
  10840. });
  10841. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10842. auto se = detail::scope_exit([&] {
  10843. if (!svr.is_running()) return;
  10844. svr.stop();
  10845. listen_thread.join();
  10846. ASSERT_FALSE(svr.is_running());
  10847. });
  10848. svr.wait_until_ready();
  10849. Client cli("localhost", PORT);
  10850. cli.set_keep_alive(true);
  10851. using namespace std::chrono;
  10852. auto start = steady_clock::now();
  10853. cli.Get("/a");
  10854. svr.stop();
  10855. listen_thread.join();
  10856. auto end = steady_clock::now();
  10857. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10858. EXPECT_LT(elapsed, 5000);
  10859. }
  10860. #ifdef CPPHTTPLIB_SSL_ENABLED
  10861. TEST(KeepAliveTest, SSLClientReconnection) {
  10862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10863. ASSERT_TRUE(svr.is_valid());
  10864. svr.set_keep_alive_timeout(1);
  10865. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10866. res.set_content("Hello World!", "text/plain");
  10867. });
  10868. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10869. auto se = detail::scope_exit([&] {
  10870. svr.stop();
  10871. listen_thread.join();
  10872. ASSERT_FALSE(svr.is_running());
  10873. });
  10874. svr.wait_until_ready();
  10875. SSLClient cli(HOST, PORT);
  10876. cli.enable_server_certificate_verification(false);
  10877. cli.set_keep_alive(true);
  10878. auto result = cli.Get("/hi");
  10879. ASSERT_TRUE(result);
  10880. EXPECT_EQ(StatusCode::OK_200, result->status);
  10881. result = cli.Get("/hi");
  10882. ASSERT_TRUE(result);
  10883. EXPECT_EQ(StatusCode::OK_200, result->status);
  10884. std::this_thread::sleep_for(std::chrono::seconds(2));
  10885. // Recoonect
  10886. result = cli.Get("/hi");
  10887. ASSERT_TRUE(result);
  10888. EXPECT_EQ(StatusCode::OK_200, result->status);
  10889. result = cli.Get("/hi");
  10890. ASSERT_TRUE(result);
  10891. EXPECT_EQ(StatusCode::OK_200, result->status);
  10892. }
  10893. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10895. ASSERT_TRUE(svr.is_valid());
  10896. svr.set_keep_alive_timeout(1);
  10897. std::string content = "reconnect";
  10898. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10899. res.set_content("Hello World!", "text/plain");
  10900. });
  10901. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10902. auto se = detail::scope_exit([&] {
  10903. svr.stop();
  10904. listen_thread.join();
  10905. ASSERT_FALSE(svr.is_running());
  10906. });
  10907. svr.wait_until_ready();
  10908. SSLClient cli(HOST, PORT);
  10909. cli.enable_server_certificate_verification(false);
  10910. cli.set_keep_alive(true);
  10911. auto result = cli.Post(
  10912. "/hi", content.size(),
  10913. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10914. sink.write(content.c_str(), content.size());
  10915. return true;
  10916. },
  10917. "text/plain");
  10918. ASSERT_TRUE(result);
  10919. EXPECT_EQ(200, result->status);
  10920. std::this_thread::sleep_for(std::chrono::seconds(2));
  10921. // Recoonect
  10922. result = cli.Post(
  10923. "/hi", content.size(),
  10924. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10925. sink.write(content.c_str(), content.size());
  10926. return true;
  10927. },
  10928. "text/plain");
  10929. ASSERT_TRUE(result);
  10930. EXPECT_EQ(200, result->status);
  10931. result = cli.Post(
  10932. "/hi", content.size(),
  10933. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10934. sink.write(content.c_str(), content.size());
  10935. return true;
  10936. },
  10937. "text/plain");
  10938. ASSERT_TRUE(result);
  10939. EXPECT_EQ(200, result->status);
  10940. }
  10941. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10942. using namespace httplib::tls;
  10943. {
  10944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10945. ASSERT_TRUE(svr.is_valid());
  10946. svr.Get("/sni", [&](const Request &req, Response &res) {
  10947. std::string expected = req.sni();
  10948. EXPECT_EQ(expected, req.get_param_value("expected"));
  10949. res.set_content("ok", "text/plain");
  10950. });
  10951. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10952. auto se = detail::scope_exit([&] {
  10953. svr.stop();
  10954. listen_thread.join();
  10955. ASSERT_FALSE(svr.is_running());
  10956. });
  10957. svr.wait_until_ready();
  10958. {
  10959. SSLClient cli("localhost", PORT);
  10960. cli.enable_server_certificate_verification(false);
  10961. auto res = cli.Get("/sni?expected=localhost");
  10962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10963. }
  10964. {
  10965. SSLClient cli("::1", PORT);
  10966. cli.enable_server_certificate_verification(false);
  10967. auto res = cli.Get("/sni?expected=");
  10968. // NOTE: This may fail if the server is listening on IPv4 only
  10969. // (e.g., when localhost resolves to 127.0.0.1 only)
  10970. if (res) {
  10971. EXPECT_EQ(StatusCode::OK_200, res->status);
  10972. } else {
  10973. EXPECT_EQ(Error::Connection, res.error());
  10974. }
  10975. }
  10976. }
  10977. }
  10978. #endif
  10979. TEST(ClientProblemDetectionTest, ContentProvider) {
  10980. Server svr;
  10981. size_t content_length = 1024 * 1024;
  10982. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10983. res.set_content_provider(
  10984. content_length, "text/plain",
  10985. [&](size_t offset, size_t length, DataSink &sink) {
  10986. auto out_len = std::min(length, static_cast<size_t>(1024));
  10987. std::string out(out_len, '@');
  10988. sink.write(out.data(), out_len);
  10989. return offset < 4096;
  10990. },
  10991. [](bool success) { ASSERT_FALSE(success); });
  10992. });
  10993. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10994. res.set_content_provider(
  10995. 0, "text/plain",
  10996. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10997. EXPECT_TRUE(false);
  10998. return true;
  10999. },
  11000. [](bool success) { ASSERT_FALSE(success); });
  11001. });
  11002. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11003. auto se = detail::scope_exit([&] {
  11004. svr.stop();
  11005. listen_thread.join();
  11006. ASSERT_FALSE(svr.is_running());
  11007. });
  11008. svr.wait_until_ready();
  11009. Client cli("localhost", PORT);
  11010. {
  11011. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11012. size_t /*data_length*/) { return false; });
  11013. ASSERT_FALSE(res);
  11014. }
  11015. {
  11016. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11017. size_t /*data_length*/) { return false; });
  11018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11019. }
  11020. }
  11021. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11022. // A provider that reports success without writing anything and without
  11023. // calling done() used to be handed the same offset and length again on every
  11024. // pass, so it spun for as long as the peer stayed connected.
  11025. Server svr;
  11026. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11027. res.set_content("ok", "text/plain");
  11028. });
  11029. auto port = svr.bind_to_any_port(HOST);
  11030. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11031. auto se = detail::scope_exit([&] {
  11032. svr.stop();
  11033. listen_thread.join();
  11034. ASSERT_FALSE(svr.is_running());
  11035. });
  11036. svr.wait_until_ready();
  11037. std::atomic<int> call_count{0};
  11038. Client cli(HOST, port);
  11039. auto res = cli.Post(
  11040. "/", 1024,
  11041. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11042. // Give up after enough passes to show the spin, so that losing the
  11043. // check below fails this test instead of hanging it.
  11044. return ++call_count < 100;
  11045. },
  11046. "text/plain");
  11047. ASSERT_FALSE(res);
  11048. EXPECT_EQ(Error::Write, res.error());
  11049. EXPECT_EQ(1, call_count.load());
  11050. }
  11051. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11052. // A writer only has to assign `write`. The other three used to be left as
  11053. // empty std::functions, so a provider calling one threw
  11054. // std::bad_function_call out of the thread running it and took the whole
  11055. // process down.
  11056. DataSink sink;
  11057. std::string written;
  11058. sink.write = [&](const char *data, size_t data_len) {
  11059. written.append(data, data_len);
  11060. return true;
  11061. };
  11062. EXPECT_TRUE(sink.is_writable());
  11063. sink.done();
  11064. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11065. EXPECT_TRUE(written.empty());
  11066. }
  11067. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11068. // A sink that cannot carry trailers still has to finish.
  11069. DataSink sink;
  11070. auto done_count = 0;
  11071. sink.done = [&]() { done_count++; };
  11072. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11073. EXPECT_EQ(1, done_count);
  11074. }
  11075. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11076. Server svr;
  11077. const std::string body(4096, 'x');
  11078. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11079. res.set_content_provider(body.size(), "text/plain",
  11080. [&](size_t offset, size_t length, DataSink &sink) {
  11081. sink.write(body.data() + offset, length);
  11082. sink.done();
  11083. return true;
  11084. });
  11085. });
  11086. auto port = svr.bind_to_any_port(HOST);
  11087. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11088. auto se = detail::scope_exit([&] {
  11089. svr.stop();
  11090. listen_thread.join();
  11091. ASSERT_FALSE(svr.is_running());
  11092. });
  11093. svr.wait_until_ready();
  11094. Client cli(HOST, port);
  11095. auto res = cli.Get("/");
  11096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11097. EXPECT_EQ(StatusCode::OK_200, res->status);
  11098. EXPECT_EQ(body, res->body);
  11099. }
  11100. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11101. Server svr;
  11102. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11103. res.set_content_provider(
  11104. 1024, "text/plain",
  11105. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11106. sink.write("hello", 5);
  11107. sink.done(); // short of the 1024 bytes the response promised
  11108. return true;
  11109. });
  11110. });
  11111. auto port = svr.bind_to_any_port(HOST);
  11112. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11113. auto se = detail::scope_exit([&] {
  11114. svr.stop();
  11115. listen_thread.join();
  11116. ASSERT_FALSE(svr.is_running());
  11117. });
  11118. svr.wait_until_ready();
  11119. Client cli(HOST, port);
  11120. cli.set_read_timeout(5, 0);
  11121. // The response is short of its Content-Length, so the client cannot read a
  11122. // complete body. What matters is that this returns at all: a no-op done()
  11123. // would leave the writer looping over a provider that never makes progress.
  11124. auto res = cli.Get("/");
  11125. EXPECT_FALSE(res);
  11126. }
  11127. // Read as the next response by a peer that sees it after a framed body.
  11128. static const std::string smuggled_response =
  11129. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11130. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11131. Server svr;
  11132. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11133. res.set_content_provider(
  11134. 5, "text/plain",
  11135. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11136. auto data = "AAAAA" + smuggled_response;
  11137. sink.write(data.data(), data.size());
  11138. return true;
  11139. });
  11140. });
  11141. thread t = thread([&] { svr.listen(HOST, PORT); });
  11142. auto se = detail::scope_exit([&] {
  11143. svr.stop();
  11144. t.join();
  11145. ASSERT_FALSE(svr.is_running());
  11146. });
  11147. svr.wait_until_ready();
  11148. std::string resp;
  11149. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11150. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11151. resp.clear();
  11152. ASSERT_TRUE(send_request(
  11153. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11154. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11155. }
  11156. TEST(NoContentTest, BodyIsNotSent) {
  11157. Server svr;
  11158. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11159. res.status = StatusCode::NoContent_204;
  11160. res.set_content(smuggled_response, "text/plain");
  11161. });
  11162. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11163. res.status = StatusCode::NotModified_304;
  11164. res.set_chunked_content_provider(
  11165. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11166. sink.write(smuggled_response.data(), smuggled_response.size());
  11167. sink.done();
  11168. return true;
  11169. });
  11170. });
  11171. thread t = thread([&] { svr.listen(HOST, PORT); });
  11172. auto se = detail::scope_exit([&] {
  11173. svr.stop();
  11174. t.join();
  11175. ASSERT_FALSE(svr.is_running());
  11176. });
  11177. svr.wait_until_ready();
  11178. for (auto path : {"/204", "/304"}) {
  11179. std::string resp;
  11180. ASSERT_TRUE(send_request(
  11181. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11182. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11183. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11184. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11185. }
  11186. }
  11187. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11188. Server svr;
  11189. std::atomic<bool> smuggled(false);
  11190. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11191. res.set_content("ok", "text/plain");
  11192. });
  11193. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11194. smuggled = true;
  11195. });
  11196. auto port = svr.bind_to_any_port(HOST);
  11197. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11198. auto se = detail::scope_exit([&] {
  11199. svr.stop();
  11200. listen_thread.join();
  11201. ASSERT_FALSE(svr.is_running());
  11202. });
  11203. svr.wait_until_ready();
  11204. // What follows the body would be read as the next request.
  11205. Client cli(HOST, port);
  11206. auto res = cli.Post(
  11207. "/", 5,
  11208. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11209. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11210. sink.write(data.data(), data.size());
  11211. return true;
  11212. },
  11213. "text/plain");
  11214. ASSERT_FALSE(res);
  11215. EXPECT_EQ(Error::Write, res.error());
  11216. EXPECT_FALSE(smuggled);
  11217. }
  11218. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11219. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11220. // The compressed path builds the whole body before connecting, so this
  11221. // fails client-side and never reaches a server.
  11222. Client cli(HOST, PORT);
  11223. cli.set_compress(true);
  11224. auto res = cli.Post(
  11225. "/", 1024,
  11226. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11227. sink.write("hello", 5);
  11228. sink.done(); // short of the 1024 bytes the request announced
  11229. return true;
  11230. },
  11231. "text/plain");
  11232. ASSERT_FALSE(res);
  11233. EXPECT_EQ(Error::Write, res.error());
  11234. }
  11235. #endif
  11236. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11237. Server svr;
  11238. svr.set_error_handler([](Request const &, Response &res) -> void {
  11239. res.set_chunked_content_provider(
  11240. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11241. sink.os << "hello";
  11242. sink.os << "world";
  11243. sink.done();
  11244. return true;
  11245. });
  11246. });
  11247. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11248. auto se = detail::scope_exit([&] {
  11249. svr.stop();
  11250. listen_thread.join();
  11251. ASSERT_FALSE(svr.is_running());
  11252. });
  11253. svr.wait_until_ready();
  11254. Client cli("localhost", PORT);
  11255. auto res = cli.Get("/");
  11256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11257. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11258. EXPECT_EQ("helloworld", res->body);
  11259. }
  11260. // A body set after a content provider must replace it, not be sent through it.
  11261. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11262. Server svr;
  11263. svr.set_mount_point("/", "./www");
  11264. svr.set_file_request_handler([](const Request &req, Response &res) {
  11265. if (req.path == "/dir/test.html") {
  11266. res.status = StatusCode::Forbidden_403;
  11267. res.set_content(std::string(5000, 'D'), "text/plain");
  11268. } else if (req.path == "/file") {
  11269. res.status = StatusCode::Forbidden_403;
  11270. res.body = "Denied";
  11271. }
  11272. });
  11273. auto port = svr.bind_to_any_port(HOST);
  11274. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11275. auto se = detail::scope_exit([&] {
  11276. svr.stop();
  11277. t.join();
  11278. ASSERT_FALSE(svr.is_running());
  11279. });
  11280. svr.wait_until_ready();
  11281. Client cli(HOST, port);
  11282. {
  11283. auto res = cli.Get("/dir/test.html");
  11284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11285. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11286. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11287. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11288. }
  11289. {
  11290. auto res = cli.Get("/file");
  11291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11292. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11293. EXPECT_EQ("Denied", res->body);
  11294. }
  11295. {
  11296. auto res = cli.Get("/dir/index.html");
  11297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11298. EXPECT_EQ(StatusCode::OK_200, res->status);
  11299. EXPECT_EQ(0U, res->body.find("<html>"));
  11300. }
  11301. }
  11302. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11303. Server svr;
  11304. std::vector<bool> released;
  11305. std::mutex released_mutex;
  11306. auto releaser = [&](bool success) {
  11307. std::lock_guard<std::mutex> guard(released_mutex);
  11308. released.push_back(success);
  11309. };
  11310. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11311. return sink.write(&"hello"[offset], length);
  11312. };
  11313. svr.Get("/sized", [&](const Request &, Response &res) {
  11314. res.status = StatusCode::NotFound_404;
  11315. res.set_content_provider(5, "text/plain", provider, releaser);
  11316. });
  11317. svr.Get("/chunked", [&](const Request &, Response &res) {
  11318. res.status = StatusCode::ServiceUnavailable_503;
  11319. res.set_chunked_content_provider(
  11320. "text/plain",
  11321. [](size_t, DataSink &sink) {
  11322. sink.os << "chunk";
  11323. sink.done();
  11324. return true;
  11325. },
  11326. releaser);
  11327. });
  11328. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11329. res.set_content_provider(5, "text/plain", provider, releaser);
  11330. throw std::runtime_error("after the provider");
  11331. });
  11332. svr.set_error_handler([](const Request &req, Response &res) {
  11333. // Leave the exception handler's content to it.
  11334. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11335. res.set_content(std::string(1000, 'E'), "text/html");
  11336. return Server::HandlerResponse::Handled;
  11337. });
  11338. svr.set_exception_handler(
  11339. [](const Request &, Response &res, std::exception_ptr) {
  11340. res.status = StatusCode::InternalServerError_500;
  11341. res.set_content(std::string(1000, 'X'), "text/html");
  11342. });
  11343. auto port = svr.bind_to_any_port(HOST);
  11344. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11345. auto se = detail::scope_exit([&] {
  11346. svr.stop();
  11347. t.join();
  11348. ASSERT_FALSE(svr.is_running());
  11349. });
  11350. svr.wait_until_ready();
  11351. Client cli(HOST, port);
  11352. {
  11353. auto res = cli.Get("/sized");
  11354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11356. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11357. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11358. }
  11359. {
  11360. auto res = cli.Get("/chunked");
  11361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11362. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11363. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11364. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11365. }
  11366. {
  11367. auto res = cli.Get("/throw");
  11368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11369. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11370. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11371. }
  11372. std::lock_guard<std::mutex> guard(released_mutex);
  11373. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11374. }
  11375. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11376. Server svr;
  11377. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11378. return sink.write(&"abc"[offset], length);
  11379. };
  11380. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11381. res.set_file_content("./www/dir/test.html");
  11382. res.set_content("body", "text/plain");
  11383. });
  11384. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11385. res.set_content(std::string(100, 'B'), "text/plain");
  11386. res.set_file_content("./www/dir/test.html");
  11387. });
  11388. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11389. res.set_content(std::string(100, 'B'), "text/plain");
  11390. res.set_content_provider(3, "text/plain", abc);
  11391. });
  11392. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11393. res.set_content_provider(3, "text/plain", abc);
  11394. res.set_content(std::string(100, 'B'), "text/plain");
  11395. });
  11396. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11397. res.set_content_provider(3, "text/plain", abc);
  11398. res.body = "direct";
  11399. });
  11400. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11401. res.set_file_content("./www/dir/test.html");
  11402. res.body = "direct";
  11403. });
  11404. auto port = svr.bind_to_any_port(HOST);
  11405. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11406. auto se = detail::scope_exit([&] {
  11407. svr.stop();
  11408. t.join();
  11409. ASSERT_FALSE(svr.is_running());
  11410. });
  11411. svr.wait_until_ready();
  11412. Client cli(HOST, port);
  11413. auto expect_body = [&](const char *path, const std::string &body) {
  11414. // Uncompressed, so Content-Length can be compared with the body.
  11415. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11416. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11417. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11418. EXPECT_EQ(body, res->body) << path;
  11419. EXPECT_EQ(std::to_string(body.size()),
  11420. res->get_header_value("Content-Length"))
  11421. << path;
  11422. };
  11423. expect_body("/file-then-body", "body");
  11424. expect_body("/body-then-file", "test.html");
  11425. expect_body("/body-then-provider", "abc");
  11426. expect_body("/provider-then-body", std::string(100, 'B'));
  11427. expect_body("/provider-then-direct-body", "direct");
  11428. expect_body("/file-then-direct-body", "direct");
  11429. // Ranges are checked against the body, not the dropped provider.
  11430. {
  11431. auto res = cli.Get("/provider-then-direct-body",
  11432. Headers{{make_range_header({{1, 2}})}});
  11433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11434. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11435. EXPECT_EQ("ir", res->body);
  11436. }
  11437. {
  11438. auto res = cli.Get("/file-then-direct-body",
  11439. Headers{{make_range_header({{7, 8}})}});
  11440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11441. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11442. }
  11443. }
  11444. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11445. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11446. const char *path = "./truncated_while_served.txt";
  11447. const size_t size = 32 * 1024 * 1024;
  11448. {
  11449. std::ofstream f(path, std::ios::binary);
  11450. f << std::string(size, 'x');
  11451. }
  11452. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11453. // Over TLS, where the bytes are encrypted in this process rather than
  11454. // copied by send().
  11455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11456. svr.Get("/file", [&](const Request &, Response &res) {
  11457. res.set_file_content(path, "text/plain");
  11458. });
  11459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11460. auto se = detail::scope_exit([&] {
  11461. svr.stop();
  11462. thread.join();
  11463. ASSERT_FALSE(svr.is_running());
  11464. });
  11465. svr.wait_until_ready();
  11466. // The file shrinks once the first bytes are in, as a rewrite in place
  11467. // would, and reading the mapping past its new end used to raise SIGBUS.
  11468. SSLClient cli(HOST, PORT);
  11469. cli.enable_server_certificate_verification(false);
  11470. size_t received = 0;
  11471. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11472. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11473. received += len;
  11474. return true;
  11475. });
  11476. EXPECT_FALSE(res);
  11477. EXPECT_LT(received, size);
  11478. }
  11479. #endif
  11480. // Forward declaration (see the base64_encode note).
  11481. namespace httplib {
  11482. namespace detail {
  11483. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11484. const std::string &content_type,
  11485. EncodingType encoding);
  11486. } // namespace detail
  11487. } // namespace httplib
  11488. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11489. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11490. ASSERT_TRUE(mm->is_open());
  11491. Response res;
  11492. detail::set_file_content_provider(res, mm, "text/html",
  11493. detail::EncodingType::None);
  11494. std::string out;
  11495. DataSink sink;
  11496. sink.write = [&](const char *d, size_t l) {
  11497. out.append(d, l);
  11498. return true;
  11499. };
  11500. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11501. EXPECT_EQ("test.html", out);
  11502. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11503. EXPECT_EQ("test.html", out);
  11504. }
  11505. TEST(LongPollingTest, ClientCloseDetection) {
  11506. Server svr;
  11507. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11508. res.set_chunked_content_provider(
  11509. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11510. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11511. sink.os << "hello";
  11512. auto count = 10;
  11513. while (count > 0 && sink.is_writable()) {
  11514. this_thread::sleep_for(chrono::milliseconds(10));
  11515. count--;
  11516. }
  11517. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11518. return true;
  11519. });
  11520. });
  11521. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11522. auto se = detail::scope_exit([&] {
  11523. svr.stop();
  11524. listen_thread.join();
  11525. ASSERT_FALSE(svr.is_running());
  11526. });
  11527. svr.wait_until_ready();
  11528. Client cli("localhost", PORT);
  11529. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11530. EXPECT_EQ("hello", string(data, data_length));
  11531. return false; // close the socket immediately.
  11532. });
  11533. ASSERT_FALSE(res);
  11534. }
  11535. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11536. Server svr;
  11537. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11538. res.set_chunked_content_provider(
  11539. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11540. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11541. sink.os << "hello";
  11542. EXPECT_TRUE(sink.os.good());
  11543. // Wait for the client to close the connection
  11544. auto count = 10;
  11545. while (count > 0 && sink.is_writable()) {
  11546. this_thread::sleep_for(chrono::milliseconds(10));
  11547. count--;
  11548. }
  11549. // After client disconnect, write repeatedly until the socket
  11550. // write actually fails (small writes may be absorbed by the
  11551. // kernel buffer)
  11552. std::string chunk(1024, 'x');
  11553. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11554. sink.os << chunk;
  11555. }
  11556. EXPECT_TRUE(sink.os.fail());
  11557. return true;
  11558. });
  11559. });
  11560. auto port = svr.bind_to_any_port("localhost");
  11561. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11562. auto se = detail::scope_exit([&] {
  11563. svr.stop();
  11564. listen_thread.join();
  11565. ASSERT_FALSE(svr.is_running());
  11566. });
  11567. svr.wait_until_ready();
  11568. Client cli("localhost", port);
  11569. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11570. EXPECT_EQ("hello", string(data, data_length));
  11571. return false; // close the socket immediately.
  11572. });
  11573. ASSERT_FALSE(res);
  11574. }
  11575. TEST(GetWithParametersTest, GetWithParameters) {
  11576. Server svr;
  11577. svr.Get("/", [&](const Request &req, Response &) {
  11578. EXPECT_EQ("world", req.get_param_value("hello"));
  11579. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11580. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11581. });
  11582. svr.Get("/params", [&](const Request &req, Response &) {
  11583. EXPECT_EQ("world", req.get_param_value("hello"));
  11584. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11585. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11586. });
  11587. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11588. EXPECT_EQ("resource-id", req.matches[1]);
  11589. EXPECT_EQ("foo", req.get_param_value("param1"));
  11590. EXPECT_EQ("bar", req.get_param_value("param2"));
  11591. });
  11592. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11593. EXPECT_EQ("user-id", req.path_params.at("id"));
  11594. EXPECT_EQ("foo", req.get_param_value("param1"));
  11595. EXPECT_EQ("bar", req.get_param_value("param2"));
  11596. });
  11597. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11598. auto se = detail::scope_exit([&] {
  11599. svr.stop();
  11600. listen_thread.join();
  11601. ASSERT_FALSE(svr.is_running());
  11602. });
  11603. svr.wait_until_ready();
  11604. {
  11605. Client cli(HOST, PORT);
  11606. Params params;
  11607. params.emplace("hello", "world");
  11608. params.emplace("hello2", "world2");
  11609. params.emplace("hello3", "world3");
  11610. auto res = cli.Get("/", params, Headers{});
  11611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11612. EXPECT_EQ(StatusCode::OK_200, res->status);
  11613. }
  11614. {
  11615. Client cli(HOST, PORT);
  11616. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11618. EXPECT_EQ(StatusCode::OK_200, res->status);
  11619. }
  11620. {
  11621. Client cli(HOST, PORT);
  11622. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11624. EXPECT_EQ(StatusCode::OK_200, res->status);
  11625. }
  11626. {
  11627. Client cli(HOST, PORT);
  11628. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11630. EXPECT_EQ(StatusCode::OK_200, res->status);
  11631. }
  11632. }
  11633. TEST(GetWithParametersTest, GetWithParameters2) {
  11634. Server svr;
  11635. svr.Get("/", [&](const Request &req, Response &res) {
  11636. auto text = req.get_param_value("hello");
  11637. res.set_content(text, "text/plain");
  11638. });
  11639. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11640. auto se = detail::scope_exit([&] {
  11641. svr.stop();
  11642. listen_thread.join();
  11643. ASSERT_FALSE(svr.is_running());
  11644. });
  11645. svr.wait_until_ready();
  11646. Client cli("localhost", PORT);
  11647. Params params;
  11648. params.emplace("hello", "world");
  11649. std::string body;
  11650. auto res = cli.Get("/", params, Headers{},
  11651. [&](const char *data, size_t data_length) {
  11652. body.append(data, data_length);
  11653. return true;
  11654. });
  11655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11656. EXPECT_EQ(StatusCode::OK_200, res->status);
  11657. EXPECT_EQ("world", body);
  11658. }
  11659. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11660. Server svr;
  11661. svr.Get("/search", [&](const Request &req, Response &res) {
  11662. auto q = req.get_param_value("q");
  11663. res.set_content(q, "text/plain");
  11664. });
  11665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11666. auto se = detail::scope_exit([&] {
  11667. svr.stop();
  11668. listen_thread.join();
  11669. ASSERT_FALSE(svr.is_running());
  11670. });
  11671. svr.wait_until_ready();
  11672. Client cli("localhost", PORT);
  11673. // Verify that Get(path, params) works without requiring Headers argument
  11674. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11676. EXPECT_EQ(StatusCode::OK_200, res->status);
  11677. EXPECT_EQ("cpp-httplib", res->body);
  11678. }
  11679. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11680. auto host = "httpbingo.org";
  11681. auto path = std::string{"/range/32"};
  11682. #ifdef CPPHTTPLIB_SSL_ENABLED
  11683. SSLClient cli(host);
  11684. #else
  11685. Client cli(host);
  11686. #endif
  11687. cli.set_default_headers({make_range_header({{1, 10}})});
  11688. cli.set_connection_timeout(5);
  11689. {
  11690. auto res = cli.Get(path);
  11691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11692. EXPECT_EQ("bcdefghijk", res->body);
  11693. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11694. }
  11695. {
  11696. auto res = cli.Get(path);
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. EXPECT_EQ("bcdefghijk", res->body);
  11699. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11700. }
  11701. }
  11702. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11703. Server svr;
  11704. svr.set_default_headers({{"Hello", "World"}});
  11705. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11706. res.set_content("ok", "text/plain");
  11707. });
  11708. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. listen_thread.join();
  11712. ASSERT_FALSE(svr.is_running());
  11713. });
  11714. svr.wait_until_ready();
  11715. Client cli("localhost", PORT);
  11716. auto res = cli.Get("/");
  11717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11718. EXPECT_EQ(StatusCode::OK_200, res->status);
  11719. EXPECT_EQ("ok", res->body);
  11720. EXPECT_EQ("World", res->get_header_value("Hello"));
  11721. }
  11722. #ifdef CPPHTTPLIB_SSL_ENABLED
  11723. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11725. ASSERT_TRUE(svr.is_valid());
  11726. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11727. std::this_thread::sleep_for(std::chrono::seconds(2));
  11728. res.set_content("a", "text/plain");
  11729. });
  11730. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11731. res.set_content("b", "text/plain");
  11732. });
  11733. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11734. auto se = detail::scope_exit([&] {
  11735. svr.stop();
  11736. listen_thread.join();
  11737. ASSERT_FALSE(svr.is_running());
  11738. });
  11739. svr.wait_until_ready();
  11740. SSLClient cli("localhost", PORT);
  11741. cli.enable_server_certificate_verification(false);
  11742. cli.set_keep_alive(true);
  11743. cli.set_read_timeout(std::chrono::seconds(1));
  11744. auto resa = cli.Get("/a");
  11745. ASSERT_TRUE(!resa);
  11746. EXPECT_EQ(Error::Read, resa.error());
  11747. auto resb = cli.Get("/b");
  11748. ASSERT_TRUE(resb);
  11749. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11750. EXPECT_EQ("b", resb->body);
  11751. }
  11752. // Closing an idle keep-alive connection sends close_notify and returns. The
  11753. // server must not wait for the client's close_notify: an idle client never
  11754. // sends one, so the worker would be held until the read timeout expires, and
  11755. // stop() would wait for it.
  11756. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11758. ASSERT_TRUE(svr.is_valid());
  11759. svr.set_keep_alive_timeout(1);
  11760. svr.set_read_timeout(10, 0);
  11761. svr.Get("/", [](const Request &, Response &res) {
  11762. res.set_content("ok", "text/plain");
  11763. });
  11764. auto port = svr.bind_to_any_port(HOST);
  11765. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11766. auto se = detail::scope_exit([&] {
  11767. if (listen_thread.joinable()) {
  11768. svr.stop();
  11769. listen_thread.join();
  11770. }
  11771. });
  11772. svr.wait_until_ready();
  11773. SSLClient cli(HOST, port);
  11774. cli.enable_server_certificate_verification(false);
  11775. cli.set_keep_alive(true);
  11776. auto res = cli.Get("/");
  11777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11778. EXPECT_EQ(StatusCode::OK_200, res->status);
  11779. // Stay idle past the keep-alive timeout so the server closes the connection.
  11780. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11781. auto start = std::chrono::steady_clock::now();
  11782. svr.stop();
  11783. listen_thread.join();
  11784. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11785. std::chrono::steady_clock::now() - start)
  11786. .count();
  11787. EXPECT_LT(elapsed, 3000);
  11788. }
  11789. #endif
  11790. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11791. protected:
  11792. ServerTestWithAI_PASSIVE()
  11793. : cli_(HOST, PORT)
  11794. #ifdef CPPHTTPLIB_SSL_ENABLED
  11795. ,
  11796. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11797. #endif
  11798. {
  11799. #ifdef CPPHTTPLIB_SSL_ENABLED
  11800. cli_.enable_server_certificate_verification(false);
  11801. #endif
  11802. }
  11803. virtual void SetUp() {
  11804. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11805. res.set_content("Hello World!", "text/plain");
  11806. });
  11807. t_ = thread(
  11808. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11809. svr_.wait_until_ready();
  11810. }
  11811. virtual void TearDown() {
  11812. svr_.stop();
  11813. t_.join();
  11814. }
  11815. #ifdef CPPHTTPLIB_SSL_ENABLED
  11816. SSLClient cli_;
  11817. SSLServer svr_;
  11818. #else
  11819. Client cli_;
  11820. Server svr_;
  11821. #endif
  11822. thread t_;
  11823. };
  11824. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11825. auto res = cli_.Get("/hi");
  11826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11827. EXPECT_EQ(StatusCode::OK_200, res->status);
  11828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11829. EXPECT_EQ("Hello World!", res->body);
  11830. }
  11831. class ServerUpDownTest : public ::testing::Test {
  11832. protected:
  11833. ServerUpDownTest() : cli_(HOST, PORT) {}
  11834. virtual void SetUp() {
  11835. t_ = thread([&]() {
  11836. svr_.bind_to_any_port(HOST);
  11837. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11838. ASSERT_TRUE(svr_.listen_after_bind());
  11839. });
  11840. svr_.wait_until_ready();
  11841. }
  11842. virtual void TearDown() {
  11843. svr_.stop();
  11844. t_.join();
  11845. }
  11846. Client cli_;
  11847. Server svr_;
  11848. thread t_;
  11849. };
  11850. TEST_F(ServerUpDownTest, QuickStartStop) {
  11851. // Should not crash, especially when run with
  11852. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11853. }
  11854. class PayloadMaxLengthTest : public ::testing::Test {
  11855. protected:
  11856. PayloadMaxLengthTest()
  11857. : cli_(HOST, PORT)
  11858. #ifdef CPPHTTPLIB_SSL_ENABLED
  11859. ,
  11860. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11861. #endif
  11862. {
  11863. #ifdef CPPHTTPLIB_SSL_ENABLED
  11864. cli_.enable_server_certificate_verification(false);
  11865. #endif
  11866. }
  11867. virtual void SetUp() {
  11868. svr_.set_payload_max_length(8);
  11869. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11870. res.set_content("test", "text/plain");
  11871. });
  11872. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11873. svr_.wait_until_ready();
  11874. }
  11875. virtual void TearDown() {
  11876. svr_.stop();
  11877. t_.join();
  11878. }
  11879. #ifdef CPPHTTPLIB_SSL_ENABLED
  11880. SSLClient cli_;
  11881. SSLServer svr_;
  11882. #else
  11883. Client cli_;
  11884. Server svr_;
  11885. #endif
  11886. thread t_;
  11887. };
  11888. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11889. auto res = cli_.Post("/test", "123456789", "text/plain");
  11890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11891. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11892. res = cli_.Post("/test", "12345678", "text/plain");
  11893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11894. EXPECT_EQ(StatusCode::OK_200, res->status);
  11895. }
  11896. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11897. // Test chunked encoding with payload exceeding the 8-byte limit
  11898. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11899. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11901. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11902. }
  11903. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11904. // Test chunked encoding with payload within the 8-byte limit
  11905. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11906. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11908. EXPECT_EQ(StatusCode::OK_200, res->status);
  11909. }
  11910. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11911. // Test using send_request to send chunked data exceeding payload limit
  11912. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11913. "Host: " +
  11914. std::string(HOST) + ":" + std::to_string(PORT) +
  11915. "\r\n"
  11916. "Transfer-Encoding: chunked\r\n"
  11917. "Connection: close\r\n"
  11918. "\r\n"
  11919. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11920. "0123456789\r\n"
  11921. "0\r\n" // End chunk
  11922. "\r\n";
  11923. std::string response;
  11924. bool result = send_request(1, chunked_request, &response);
  11925. if (!result) {
  11926. // If send_request fails, it might be because the server closed the
  11927. // connection due to payload limit enforcement, which is acceptable
  11928. SUCCEED()
  11929. << "Server rejected oversized chunked request (connection closed)";
  11930. } else {
  11931. // If we got a response, check if it's an error response or connection was
  11932. // closed early Short response length indicates connection was closed due to
  11933. // payload limit
  11934. if (response.length() <= 10) {
  11935. SUCCEED() << "Server closed connection for oversized chunked request";
  11936. } else {
  11937. // Check for error status codes
  11938. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11939. response.find("Payload Too Large") != std::string::npos ||
  11940. response.find("400") != std::string::npos);
  11941. }
  11942. }
  11943. }
  11944. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11945. // Test request without Content-Length header exceeding payload limit
  11946. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11947. "Host: " +
  11948. std::string(HOST) + ":" +
  11949. std::to_string(PORT) +
  11950. "\r\n"
  11951. "Connection: close\r\n"
  11952. "\r\n";
  11953. // Add payload exceeding the 8-byte limit
  11954. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11955. request_without_content_length += large_payload;
  11956. std::string response;
  11957. bool result = send_request(1, request_without_content_length, &response);
  11958. if (!result) {
  11959. // If send_request fails, server likely closed connection due to payload
  11960. // limit
  11961. SUCCEED() << "Server rejected oversized request without Content-Length "
  11962. "(connection closed)";
  11963. } else {
  11964. // Check if server responded with error or closed connection early
  11965. if (response.length() <= 10) {
  11966. SUCCEED() << "Server closed connection for oversized request without "
  11967. "Content-Length";
  11968. } else {
  11969. // Check for error status codes
  11970. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11971. response.find("Payload Too Large") != std::string::npos ||
  11972. response.find("400") != std::string::npos);
  11973. }
  11974. }
  11975. }
  11976. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11977. // Test request without Content-Length header within payload limit
  11978. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11979. "Host: " +
  11980. std::string(HOST) + ":" +
  11981. std::to_string(PORT) +
  11982. "\r\n"
  11983. "Connection: close\r\n"
  11984. "\r\n";
  11985. // Add payload within the 8-byte limit
  11986. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11987. request_without_content_length += small_payload;
  11988. std::string response;
  11989. bool result = send_request(1, request_without_content_length, &response);
  11990. // For requests without Content-Length, the server may have different behavior
  11991. // The key is that it should not reject due to payload limit for small
  11992. // payloads
  11993. if (result) {
  11994. // Check for any HTTP response (success or error, but not connection closed)
  11995. if (response.length() > 10) {
  11996. SUCCEED()
  11997. << "Server processed request without Content-Length within limit";
  11998. } else {
  11999. // Short response might indicate connection closed, which is acceptable
  12000. SUCCEED() << "Server closed connection for request without "
  12001. "Content-Length (acceptable behavior)";
  12002. }
  12003. } else {
  12004. // Connection failure might be due to protocol requirements
  12005. SUCCEED() << "Connection issue with request without Content-Length "
  12006. "(environment-specific)";
  12007. }
  12008. }
  12009. class LargePayloadMaxLengthTest : public ::testing::Test {
  12010. protected:
  12011. LargePayloadMaxLengthTest()
  12012. : cli_(HOST, PORT)
  12013. #ifdef CPPHTTPLIB_SSL_ENABLED
  12014. ,
  12015. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12016. #endif
  12017. {
  12018. #ifdef CPPHTTPLIB_SSL_ENABLED
  12019. cli_.enable_server_certificate_verification(false);
  12020. #endif
  12021. }
  12022. virtual void SetUp() {
  12023. // Set 10MB payload limit
  12024. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12025. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12026. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12027. res.set_content("Large payload test", "text/plain");
  12028. });
  12029. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12030. svr_.wait_until_ready();
  12031. }
  12032. virtual void TearDown() {
  12033. svr_.stop();
  12034. t_.join();
  12035. }
  12036. #ifdef CPPHTTPLIB_SSL_ENABLED
  12037. SSLClient cli_;
  12038. SSLServer svr_;
  12039. #else
  12040. Client cli_;
  12041. Server svr_;
  12042. #endif
  12043. thread t_;
  12044. };
  12045. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12046. // Test chunked encoding with payload within 10MB limit
  12047. std::string medium_payload(5 * 1024 * 1024,
  12048. 'A'); // 5MB payload, within 10MB limit
  12049. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12051. EXPECT_EQ(StatusCode::OK_200, res->status);
  12052. }
  12053. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12054. // Test chunked encoding with payload exceeding 10MB limit
  12055. std::string large_payload(12 * 1024 * 1024,
  12056. 'B'); // 12MB payload, exceeds 10MB limit
  12057. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12058. // Server may either return 413 or close the connection
  12059. if (res) {
  12060. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12061. } else {
  12062. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12063. }
  12064. }
  12065. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12066. // Test request without Content-Length header within 10MB limit
  12067. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12068. "Host: " +
  12069. std::string(HOST) + ":" +
  12070. std::to_string(PORT) +
  12071. "\r\n"
  12072. "Connection: close\r\n"
  12073. "\r\n";
  12074. // Add 1MB payload (within 10MB limit)
  12075. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12076. request_without_content_length += medium_payload;
  12077. std::string response;
  12078. bool result = send_request(5, request_without_content_length, &response);
  12079. if (result) {
  12080. // Should get a proper HTTP response for payloads within limit
  12081. if (response.length() > 10) {
  12082. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12083. "10MB limit";
  12084. } else {
  12085. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12086. "Content-Length)";
  12087. }
  12088. } else {
  12089. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12090. }
  12091. }
  12092. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12093. // Test request without Content-Length header exceeding 10MB limit
  12094. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12095. "Host: " +
  12096. std::string(HOST) + ":" +
  12097. std::to_string(PORT) +
  12098. "\r\n"
  12099. "Connection: close\r\n"
  12100. "\r\n";
  12101. // Add 12MB payload (exceeds 10MB limit)
  12102. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12103. request_without_content_length += large_payload;
  12104. std::string response;
  12105. bool result = send_request(10, request_without_content_length, &response);
  12106. if (!result) {
  12107. // Server should close connection due to payload limit
  12108. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12109. "(connection closed)";
  12110. } else {
  12111. // Check for error response
  12112. if (response.length() <= 10) {
  12113. SUCCEED()
  12114. << "Server closed connection for 12MB request exceeding 10MB limit";
  12115. } else {
  12116. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12117. response.find("Payload Too Large") != std::string::npos ||
  12118. response.find("400") != std::string::npos);
  12119. }
  12120. }
  12121. }
  12122. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12123. Server svr;
  12124. svr.Get("/", [](const Request &, Response &res) {
  12125. // Claims far more than it sends, then drops the connection.
  12126. res.set_content_provider(size_t(1) << 41, "text/plain",
  12127. [](size_t, size_t, DataSink &sink) {
  12128. sink.write("abc", 3);
  12129. return false;
  12130. });
  12131. });
  12132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12133. auto se = detail::scope_exit([&] {
  12134. svr.stop();
  12135. thread.join();
  12136. ASSERT_FALSE(svr.is_running());
  12137. });
  12138. svr.wait_until_ready();
  12139. Client cli(HOST, PORT);
  12140. cli.set_payload_max_length(0);
  12141. EXPECT_FALSE(cli.Get("/"));
  12142. }
  12143. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12144. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12145. // path.
  12146. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12147. Server svr;
  12148. const size_t LIMIT = 64 * 1024; // 64KB
  12149. svr.set_payload_max_length(LIMIT);
  12150. size_t total = 0;
  12151. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12152. const ContentReader &content_reader) {
  12153. content_reader([&](const char * /*data*/, size_t len) {
  12154. total += len;
  12155. return true;
  12156. });
  12157. res.status = 200;
  12158. res.set_content("stream_ok", "text/plain");
  12159. });
  12160. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12161. auto se = detail::scope_exit([&] {
  12162. svr.stop();
  12163. thread.join();
  12164. ASSERT_FALSE(svr.is_running());
  12165. });
  12166. svr.wait_until_ready();
  12167. // Prepare 256KB raw data and gzip-compress it
  12168. std::string raw(256 * 1024, 'A');
  12169. std::string gz;
  12170. {
  12171. z_stream zs{};
  12172. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12173. Z_DEFAULT_STRATEGY);
  12174. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12175. zs.avail_in = static_cast<uInt>(raw.size());
  12176. char outbuf[4096];
  12177. int ret;
  12178. do {
  12179. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12180. zs.avail_out = sizeof(outbuf);
  12181. ret = deflate(&zs, Z_FINISH);
  12182. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12183. } while (ret != Z_STREAM_END);
  12184. deflateEnd(&zs);
  12185. }
  12186. Client cli(HOST, PORT);
  12187. cli.set_connection_timeout(std::chrono::seconds(5));
  12188. Headers headers = {{"Content-Encoding", "gzip"}};
  12189. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12190. "application/octet-stream");
  12191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12192. // Server must reject oversized decompressed payloads with 413.
  12193. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12194. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12195. EXPECT_LE(total, LIMIT);
  12196. }
  12197. #ifndef CPPHTTPLIB_SSL_ENABLED
  12198. // For a request with neither Content-Length nor Transfer-Encoding, the
  12199. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12200. // compressed wire bytes straight to the ContentReader without ever routing
  12201. // them through the decompressor, so payload_max_length_ only bounded the
  12202. // compressed size on the wire, not the decompressed size.
  12203. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12204. Server svr;
  12205. const size_t LIMIT = 64 * 1024; // 64KB
  12206. svr.set_payload_max_length(LIMIT);
  12207. size_t total = 0;
  12208. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12209. const ContentReader &content_reader) {
  12210. content_reader([&](const char * /*data*/, size_t len) {
  12211. total += len;
  12212. return true;
  12213. });
  12214. res.status = 200;
  12215. res.set_content("stream_ok", "text/plain");
  12216. });
  12217. auto port = svr.bind_to_any_port(HOST);
  12218. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12219. auto se = detail::scope_exit([&] {
  12220. svr.stop();
  12221. thread.join();
  12222. ASSERT_FALSE(svr.is_running());
  12223. });
  12224. svr.wait_until_ready();
  12225. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12226. // StreamingGzipDecompression test above.
  12227. std::string raw(256 * 1024, 'A');
  12228. std::string gz;
  12229. {
  12230. httplib::detail::gzip_compressor compressor;
  12231. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12232. [&](const char *chunk, size_t len) {
  12233. gz.append(chunk, len);
  12234. return true;
  12235. });
  12236. ASSERT_TRUE(result);
  12237. }
  12238. // Send the gzip body over raw TCP with neither Content-Length nor
  12239. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12240. // kicks in.
  12241. std::string req = "POST /stream HTTP/1.1\r\n"
  12242. "Host: " +
  12243. std::string(HOST) + ":" + std::to_string(port) +
  12244. "\r\n"
  12245. "Content-Encoding: gzip\r\n"
  12246. "Connection: close\r\n"
  12247. "\r\n" +
  12248. gz;
  12249. std::string response;
  12250. ASSERT_TRUE(send_request(5, req, &response, port));
  12251. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12252. EXPECT_LE(total, LIMIT);
  12253. }
  12254. #endif
  12255. #endif
  12256. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12257. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12258. // the payload must be passed through untouched instead of being rejected.
  12259. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12260. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12261. Server svr;
  12262. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12263. res.set_content(body, "image/jpeg");
  12264. res.set_header("Content-Encoding", "UTF-8");
  12265. });
  12266. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12267. res.set_content(body, "image/jpeg");
  12268. res.set_header("Content-Encoding", "identity");
  12269. });
  12270. svr.Post("/echo", [](const Request &req, Response &res) {
  12271. res.set_content(req.body, "image/jpeg");
  12272. });
  12273. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. t.join();
  12277. ASSERT_FALSE(svr.is_running());
  12278. });
  12279. svr.wait_until_ready();
  12280. Client cli(HOST, PORT);
  12281. {
  12282. auto res = cli.Get("/image");
  12283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12284. EXPECT_EQ(StatusCode::OK_200, res->status);
  12285. EXPECT_EQ(body, res->body);
  12286. }
  12287. {
  12288. auto res = cli.Get("/identity");
  12289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12290. EXPECT_EQ(StatusCode::OK_200, res->status);
  12291. EXPECT_EQ(body, res->body);
  12292. }
  12293. {
  12294. // The same applies to a request body reaching the server.
  12295. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12296. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12298. EXPECT_EQ(StatusCode::OK_200, res->status);
  12299. EXPECT_EQ(body, res->body);
  12300. }
  12301. }
  12302. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12303. // gzip-encoded response even when the build has no zlib support.
  12304. static const char GZIPPED_HELLO_WORLD[] = {
  12305. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12306. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12307. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12308. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12309. // A content coding is a whole token, not something the field value merely
  12310. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12311. // as "fibre" look like Brotli, and turned a multi-coding value like
  12312. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12313. // it was never meant to see.
  12314. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12315. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12316. Server svr;
  12317. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12318. res.set_content(body, "image/jpeg");
  12319. res.set_header("Content-Encoding", "fibre");
  12320. });
  12321. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12322. res.set_content(body, "image/jpeg");
  12323. res.set_header("Content-Encoding", "gzip, br");
  12324. });
  12325. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12326. res.set_content(body, "image/jpeg");
  12327. res.set_header("Content-Encoding", "x-zstd-ish");
  12328. });
  12329. auto port = svr.bind_to_any_port(HOST);
  12330. thread t = thread([&]() { svr.listen_after_bind(); });
  12331. auto se = detail::scope_exit([&] {
  12332. svr.stop();
  12333. t.join();
  12334. ASSERT_FALSE(svr.is_running());
  12335. });
  12336. svr.wait_until_ready();
  12337. Client cli(HOST, port);
  12338. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12339. auto res = cli.Get(path);
  12340. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12341. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12342. // Not a coding we recognize, so the payload comes back untouched
  12343. EXPECT_EQ(body, res->body) << path;
  12344. }
  12345. }
  12346. // A content coding cpp-httplib recognizes but was not built with must be
  12347. // reported as such. Handing the still-compressed payload back to the caller
  12348. // would silently corrupt it.
  12349. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12350. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12351. Server svr;
  12352. // "image/jpeg" keeps the server from applying a content coding of its own,
  12353. // so the hand-crafted Content-Encoding below survives.
  12354. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12355. res.set_content(gzipped, "image/jpeg");
  12356. res.set_header("Content-Encoding", "gzip");
  12357. });
  12358. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12359. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12360. res.set_content(gzipped, "image/jpeg");
  12361. res.set_header("Content-Encoding", "GZIP");
  12362. });
  12363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12364. auto se = detail::scope_exit([&] {
  12365. svr.stop();
  12366. t.join();
  12367. ASSERT_FALSE(svr.is_running());
  12368. });
  12369. svr.wait_until_ready();
  12370. Client cli(HOST, PORT);
  12371. {
  12372. auto res = cli.Get("/gzipped");
  12373. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12375. EXPECT_EQ("Hello World!", res->body);
  12376. #else
  12377. ASSERT_FALSE(res);
  12378. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12379. #endif
  12380. }
  12381. {
  12382. // open_stream() must behave the same way.
  12383. auto handle = cli.open_stream("GET", "/gzipped");
  12384. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12385. ASSERT_TRUE(handle.is_valid());
  12386. std::string received;
  12387. char buf[256];
  12388. ssize_t n;
  12389. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12390. received.append(buf, static_cast<size_t>(n));
  12391. }
  12392. EXPECT_EQ("Hello World!", received);
  12393. #else
  12394. EXPECT_FALSE(handle.is_valid());
  12395. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12396. #endif
  12397. }
  12398. {
  12399. // A differently-cased coding must not be mistaken for an unknown one, or
  12400. // the body would be handed back still compressed.
  12401. auto res = cli.Get("/gzipped-uppercase");
  12402. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12404. EXPECT_EQ("Hello World!", res->body);
  12405. #else
  12406. ASSERT_FALSE(res);
  12407. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12408. #endif
  12409. }
  12410. }
  12411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12412. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12413. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12414. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12415. // body a second time and appending a second Content-Encoding field line, so
  12416. // clients that decode one coding per listed value handed back raw gzip bytes.
  12417. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12418. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12419. Server svr;
  12420. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12421. // keeps the server from applying a coding of its own.
  12422. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12423. res.set_content(gzipped, "text/plain");
  12424. res.set_header("Content-Encoding", "gzip");
  12425. });
  12426. auto port = svr.bind_to_any_port(HOST);
  12427. thread t = thread([&]() { svr.listen_after_bind(); });
  12428. auto se = detail::scope_exit([&] {
  12429. svr.stop();
  12430. t.join();
  12431. ASSERT_FALSE(svr.is_running());
  12432. });
  12433. svr.wait_until_ready();
  12434. Client cli(HOST, port);
  12435. Headers headers = {{"Accept-Encoding", "gzip"}};
  12436. auto res = cli.Get("/pre-gzipped", headers);
  12437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12438. EXPECT_EQ(StatusCode::OK_200, res->status);
  12439. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12440. EXPECT_EQ("Hello World!", res->body);
  12441. }
  12442. // A chunked provider settles its coding where the headers are written and
  12443. // reuses it at write time. Both ends of that have to hold: a handler's own
  12444. // Content-Encoding suppresses the coding, and a response without one is still
  12445. // compressed as it always was.
  12446. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12447. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12448. const std::string plain = "Hello World! Hello World! Hello World!";
  12449. Server svr;
  12450. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12451. res.set_header("Content-Encoding", "gzip");
  12452. res.set_chunked_content_provider(
  12453. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12454. sink.write(gzipped.data(), gzipped.size());
  12455. sink.done();
  12456. return true;
  12457. });
  12458. });
  12459. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12460. res.set_chunked_content_provider(
  12461. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12462. sink.write(plain.data(), plain.size());
  12463. sink.done();
  12464. return true;
  12465. });
  12466. });
  12467. auto port = svr.bind_to_any_port(HOST);
  12468. thread t = thread([&]() { svr.listen_after_bind(); });
  12469. auto se = detail::scope_exit([&] {
  12470. svr.stop();
  12471. t.join();
  12472. ASSERT_FALSE(svr.is_running());
  12473. });
  12474. svr.wait_until_ready();
  12475. Client cli(HOST, port);
  12476. Headers headers = {{"Accept-Encoding", "gzip"}};
  12477. {
  12478. auto res = cli.Get("/pre-gzipped", headers);
  12479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12480. EXPECT_EQ(StatusCode::OK_200, res->status);
  12481. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12482. EXPECT_EQ("Hello World!", res->body);
  12483. }
  12484. {
  12485. auto res = cli.Get("/negotiated", headers);
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ(StatusCode::OK_200, res->status);
  12488. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12489. EXPECT_EQ(plain, res->body);
  12490. }
  12491. }
  12492. #endif
  12493. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12494. // the same message as the comma-joined one, so both have to be read the same
  12495. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12496. // single gzip coding, and a body the sender says was encoded twice was handed
  12497. // back after one pass, still compressed but presented as decoded.
  12498. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12499. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12500. Server svr;
  12501. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12502. res.set_content(body, "image/jpeg");
  12503. res.headers.emplace("Content-Encoding", "gzip");
  12504. res.headers.emplace("Content-Encoding", "gzip");
  12505. });
  12506. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12507. res.set_content(body, "image/jpeg");
  12508. res.set_header("Content-Encoding", "gzip, gzip");
  12509. });
  12510. auto port = svr.bind_to_any_port(HOST);
  12511. thread t = thread([&]() { svr.listen_after_bind(); });
  12512. auto se = detail::scope_exit([&] {
  12513. svr.stop();
  12514. t.join();
  12515. ASSERT_FALSE(svr.is_running());
  12516. });
  12517. svr.wait_until_ready();
  12518. Client cli(HOST, port);
  12519. // Two codings is not something cpp-httplib decodes, so both representations
  12520. // take the pass-through path rather than one of them being gunzipped once.
  12521. for (const char *path : {"/split", "/joined"}) {
  12522. auto res = cli.Get(path);
  12523. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12524. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12525. EXPECT_EQ(body, res->body) << path;
  12526. }
  12527. }
  12528. // Regression test for DoS vulnerability: a malicious server sending a response
  12529. // without Content-Length header must not cause unbounded memory consumption on
  12530. // the client side. The client should stop reading after a reasonable limit,
  12531. // similar to the server-side set_payload_max_length protection.
  12532. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12533. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12534. #ifndef _WIN32
  12535. signal(SIGPIPE, SIG_IGN);
  12536. #endif
  12537. auto server_thread = std::thread([] {
  12538. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12539. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12540. default_socket_options(srv);
  12541. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12542. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12543. sockaddr_in addr{};
  12544. addr.sin_family = AF_INET;
  12545. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12546. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12547. int opt = 1;
  12548. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12549. #ifdef _WIN32
  12550. reinterpret_cast<const char *>(&opt),
  12551. #else
  12552. &opt,
  12553. #endif
  12554. sizeof(opt));
  12555. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12556. ::listen(srv, 1);
  12557. sockaddr_in cli_addr{};
  12558. socklen_t cli_len = sizeof(cli_addr);
  12559. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12560. if (cli != INVALID_SOCKET) {
  12561. char buf[4096];
  12562. ::recv(cli, buf, sizeof(buf), 0);
  12563. // Malicious response: no Content-Length, no chunked encoding
  12564. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12565. "Connection: close\r\n"
  12566. "\r\n";
  12567. ::send(cli,
  12568. #ifdef _WIN32
  12569. static_cast<const char *>(response_header.c_str()),
  12570. static_cast<int>(response_header.size()),
  12571. #else
  12572. response_header.c_str(), response_header.size(),
  12573. #endif
  12574. 0);
  12575. // Send 10MB of data
  12576. std::string chunk(64 * 1024, 'A');
  12577. size_t total_sent = 0;
  12578. while (total_sent < MALICIOUS_DATA_SIZE) {
  12579. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12580. auto sent = ::send(cli,
  12581. #ifdef _WIN32
  12582. static_cast<const char *>(chunk.c_str()),
  12583. static_cast<int>(to_send),
  12584. #else
  12585. chunk.c_str(), to_send,
  12586. #endif
  12587. 0);
  12588. if (sent <= 0) break;
  12589. total_sent += static_cast<size_t>(sent);
  12590. }
  12591. detail::close_socket(cli);
  12592. }
  12593. detail::close_socket(srv);
  12594. });
  12595. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12596. size_t total_read = 0;
  12597. {
  12598. Client cli("127.0.0.1", PORT + 2);
  12599. cli.set_read_timeout(5, 0);
  12600. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12601. auto stream = cli.open_stream("GET", "/malicious");
  12602. ASSERT_TRUE(stream.is_valid());
  12603. char buffer[64 * 1024];
  12604. ssize_t n;
  12605. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12606. total_read += static_cast<size_t>(n);
  12607. }
  12608. } // StreamHandle and Client destroyed here, closing the socket
  12609. server_thread.join();
  12610. // With set_payload_max_length, the client must stop reading before consuming
  12611. // all 10MB. The read loop should be cut off at or near the configured limit.
  12612. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12613. << "Client read " << total_read << " bytes, exceeding the configured "
  12614. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12615. }
  12616. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12617. // the entire response body without truncation.
  12618. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12619. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12620. #ifndef _WIN32
  12621. signal(SIGPIPE, SIG_IGN);
  12622. #endif
  12623. auto server_thread = std::thread([] {
  12624. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12625. default_socket_options(srv);
  12626. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12627. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12628. sockaddr_in addr{};
  12629. addr.sin_family = AF_INET;
  12630. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12631. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12632. int opt = 1;
  12633. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12634. #ifdef _WIN32
  12635. reinterpret_cast<const char *>(&opt),
  12636. #else
  12637. &opt,
  12638. #endif
  12639. sizeof(opt));
  12640. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12641. ::listen(srv, 1);
  12642. sockaddr_in cli_addr{};
  12643. socklen_t cli_len = sizeof(cli_addr);
  12644. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12645. if (cli != INVALID_SOCKET) {
  12646. char buf[4096];
  12647. ::recv(cli, buf, sizeof(buf), 0);
  12648. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12649. "Connection: close\r\n"
  12650. "\r\n";
  12651. ::send(cli,
  12652. #ifdef _WIN32
  12653. static_cast<const char *>(response_header.c_str()),
  12654. static_cast<int>(response_header.size()),
  12655. #else
  12656. response_header.c_str(), response_header.size(),
  12657. #endif
  12658. 0);
  12659. std::string chunk(64 * 1024, 'A');
  12660. size_t total_sent = 0;
  12661. while (total_sent < DATA_SIZE) {
  12662. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12663. auto sent = ::send(cli,
  12664. #ifdef _WIN32
  12665. static_cast<const char *>(chunk.c_str()),
  12666. static_cast<int>(to_send),
  12667. #else
  12668. chunk.c_str(), to_send,
  12669. #endif
  12670. 0);
  12671. if (sent <= 0) break;
  12672. total_sent += static_cast<size_t>(sent);
  12673. }
  12674. #ifdef _WIN32
  12675. ::shutdown(cli, SD_SEND);
  12676. #else
  12677. ::shutdown(cli, SHUT_WR);
  12678. #endif
  12679. // Drain until the client closes its end, ensuring all data is delivered
  12680. char drain[1024];
  12681. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12682. detail::close_socket(cli);
  12683. }
  12684. detail::close_socket(srv);
  12685. });
  12686. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12687. size_t total_read = 0;
  12688. {
  12689. Client cli("127.0.0.1", PORT + 2);
  12690. cli.set_read_timeout(5, 0);
  12691. cli.set_payload_max_length(0); // 0 means no limit
  12692. auto stream = cli.open_stream("GET", "/data");
  12693. ASSERT_TRUE(stream.is_valid());
  12694. char buffer[64 * 1024];
  12695. ssize_t n;
  12696. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12697. total_read += static_cast<size_t>(n);
  12698. }
  12699. }
  12700. server_thread.join();
  12701. EXPECT_EQ(total_read, DATA_SIZE)
  12702. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12703. << " bytes without truncation, but only read " << total_read << " bytes.";
  12704. }
  12705. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12706. // enormous Content-Length must not cause the client to pre-allocate a huge
  12707. // response body buffer. The reservation is capped at payload_max_length_, and
  12708. // the read itself fails when the body exceeds the limit.
  12709. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12710. #ifndef _WIN32
  12711. signal(SIGPIPE, SIG_IGN);
  12712. #endif
  12713. auto server_thread = std::thread([] {
  12714. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12715. default_socket_options(srv);
  12716. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12717. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12718. sockaddr_in addr{};
  12719. addr.sin_family = AF_INET;
  12720. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12721. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12722. int opt = 1;
  12723. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12724. #ifdef _WIN32
  12725. reinterpret_cast<const char *>(&opt),
  12726. #else
  12727. &opt,
  12728. #endif
  12729. sizeof(opt));
  12730. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12731. ::listen(srv, 1);
  12732. sockaddr_in cli_addr{};
  12733. socklen_t cli_len = sizeof(cli_addr);
  12734. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12735. if (cli != INVALID_SOCKET) {
  12736. char buf[4096];
  12737. ::recv(cli, buf, sizeof(buf), 0);
  12738. // Malicious response: claim a 20GB body but send only a tiny payload.
  12739. std::string response = "HTTP/1.1 200 OK\r\n"
  12740. "Content-Length: 20000000000\r\n"
  12741. "\r\n"
  12742. "abc";
  12743. ::send(cli,
  12744. #ifdef _WIN32
  12745. static_cast<const char *>(response.c_str()),
  12746. static_cast<int>(response.size()),
  12747. #else
  12748. response.c_str(), response.size(),
  12749. #endif
  12750. 0);
  12751. detail::close_socket(cli);
  12752. }
  12753. detail::close_socket(srv);
  12754. });
  12755. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12756. {
  12757. Client cli("127.0.0.1", PORT + 2);
  12758. cli.set_read_timeout(5, 0);
  12759. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12760. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12761. // (server claims more bytes than payload_max_length permits), but it must
  12762. // not exhaust memory before getting there.
  12763. auto res = cli.Get("/malicious");
  12764. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12765. }
  12766. server_thread.join();
  12767. }
  12768. // Verify that content_receiver bypasses the default payload_max_length,
  12769. // allowing streaming downloads larger than 100MB without requiring an explicit
  12770. // set_payload_max_length call.
  12771. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12772. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12773. #ifndef _WIN32
  12774. signal(SIGPIPE, SIG_IGN);
  12775. #endif
  12776. auto server_thread = std::thread([] {
  12777. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12778. default_socket_options(srv);
  12779. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12780. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12781. sockaddr_in addr{};
  12782. addr.sin_family = AF_INET;
  12783. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12784. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12785. int opt = 1;
  12786. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12787. #ifdef _WIN32
  12788. reinterpret_cast<const char *>(&opt),
  12789. #else
  12790. &opt,
  12791. #endif
  12792. sizeof(opt));
  12793. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12794. ::listen(srv, 1);
  12795. sockaddr_in cli_addr{};
  12796. socklen_t cli_len = sizeof(cli_addr);
  12797. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12798. if (cli != INVALID_SOCKET) {
  12799. char buf[4096];
  12800. ::recv(cli, buf, sizeof(buf), 0);
  12801. // Response with Content-Length larger than default 100MB limit
  12802. auto content_length = std::to_string(DATA_SIZE);
  12803. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12804. "Content-Length: " +
  12805. content_length +
  12806. "\r\n"
  12807. "Connection: close\r\n"
  12808. "\r\n";
  12809. ::send(cli,
  12810. #ifdef _WIN32
  12811. static_cast<const char *>(response_header.c_str()),
  12812. static_cast<int>(response_header.size()),
  12813. #else
  12814. response_header.c_str(), response_header.size(),
  12815. #endif
  12816. 0);
  12817. std::string chunk(64 * 1024, 'A');
  12818. size_t total_sent = 0;
  12819. while (total_sent < DATA_SIZE) {
  12820. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12821. auto sent = ::send(cli,
  12822. #ifdef _WIN32
  12823. static_cast<const char *>(chunk.c_str()),
  12824. static_cast<int>(to_send),
  12825. #else
  12826. chunk.c_str(), to_send,
  12827. #endif
  12828. 0);
  12829. if (sent <= 0) break;
  12830. total_sent += static_cast<size_t>(sent);
  12831. }
  12832. detail::close_socket(cli);
  12833. }
  12834. detail::close_socket(srv);
  12835. });
  12836. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12837. size_t total_received = 0;
  12838. {
  12839. Client cli("127.0.0.1", PORT + 2);
  12840. cli.set_read_timeout(10, 0);
  12841. // Do NOT call set_payload_max_length — use the default 100MB limit
  12842. auto res =
  12843. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12844. total_received += data_length;
  12845. return true;
  12846. });
  12847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12848. EXPECT_EQ(StatusCode::OK_200, res->status);
  12849. }
  12850. server_thread.join();
  12851. EXPECT_EQ(total_received, DATA_SIZE)
  12852. << "With content_receiver, the client should read all " << DATA_SIZE
  12853. << " bytes despite the default 100MB payload_max_length, but only read "
  12854. << total_received << " bytes.";
  12855. }
  12856. // Verify that an explicit set_payload_max_length smaller than the response is
  12857. // enforced even when a content_receiver is used.
  12858. TEST(ClientVulnerabilityTest,
  12859. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12860. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12861. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12862. #ifndef _WIN32
  12863. signal(SIGPIPE, SIG_IGN);
  12864. #endif
  12865. auto server_thread = std::thread([] {
  12866. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12867. default_socket_options(srv);
  12868. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12869. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12870. sockaddr_in addr{};
  12871. addr.sin_family = AF_INET;
  12872. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12873. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12874. int opt = 1;
  12875. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12876. #ifdef _WIN32
  12877. reinterpret_cast<const char *>(&opt),
  12878. #else
  12879. &opt,
  12880. #endif
  12881. sizeof(opt));
  12882. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12883. ::listen(srv, 1);
  12884. sockaddr_in cli_addr{};
  12885. socklen_t cli_len = sizeof(cli_addr);
  12886. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12887. if (cli != INVALID_SOCKET) {
  12888. char buf[4096];
  12889. ::recv(cli, buf, sizeof(buf), 0);
  12890. auto content_length = std::to_string(DATA_SIZE);
  12891. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12892. "Content-Length: " +
  12893. content_length +
  12894. "\r\n"
  12895. "Connection: close\r\n"
  12896. "\r\n";
  12897. ::send(cli,
  12898. #ifdef _WIN32
  12899. static_cast<const char *>(response_header.c_str()),
  12900. static_cast<int>(response_header.size()),
  12901. #else
  12902. response_header.c_str(), response_header.size(),
  12903. #endif
  12904. 0);
  12905. std::string chunk(64 * 1024, 'A');
  12906. size_t total_sent = 0;
  12907. while (total_sent < DATA_SIZE) {
  12908. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12909. auto sent = ::send(cli,
  12910. #ifdef _WIN32
  12911. static_cast<const char *>(chunk.c_str()),
  12912. static_cast<int>(to_send),
  12913. #else
  12914. chunk.c_str(), to_send,
  12915. #endif
  12916. 0);
  12917. if (sent <= 0) break;
  12918. total_sent += static_cast<size_t>(sent);
  12919. }
  12920. detail::close_socket(cli);
  12921. }
  12922. detail::close_socket(srv);
  12923. });
  12924. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12925. size_t total_received = 0;
  12926. {
  12927. Client cli("127.0.0.1", PORT + 2);
  12928. cli.set_read_timeout(10, 0);
  12929. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12930. auto res =
  12931. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12932. total_received += data_length;
  12933. return true;
  12934. });
  12935. // Should fail because 200MB exceeds the explicit 150MB limit
  12936. EXPECT_FALSE(res);
  12937. }
  12938. server_thread.join();
  12939. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12940. << "Client with content_receiver should respect the explicit "
  12941. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12942. << total_received << " bytes.";
  12943. }
  12944. // Verify that an explicit set_payload_max_length larger than the response
  12945. // allows the content_receiver to read all data successfully.
  12946. TEST(ClientVulnerabilityTest,
  12947. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12948. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12949. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12950. #ifndef _WIN32
  12951. signal(SIGPIPE, SIG_IGN);
  12952. #endif
  12953. auto server_thread = std::thread([] {
  12954. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12955. default_socket_options(srv);
  12956. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12957. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12958. sockaddr_in addr{};
  12959. addr.sin_family = AF_INET;
  12960. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12961. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12962. int opt = 1;
  12963. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12964. #ifdef _WIN32
  12965. reinterpret_cast<const char *>(&opt),
  12966. #else
  12967. &opt,
  12968. #endif
  12969. sizeof(opt));
  12970. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12971. ::listen(srv, 1);
  12972. sockaddr_in cli_addr{};
  12973. socklen_t cli_len = sizeof(cli_addr);
  12974. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12975. if (cli != INVALID_SOCKET) {
  12976. char buf[4096];
  12977. ::recv(cli, buf, sizeof(buf), 0);
  12978. auto content_length = std::to_string(DATA_SIZE);
  12979. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12980. "Content-Length: " +
  12981. content_length +
  12982. "\r\n"
  12983. "Connection: close\r\n"
  12984. "\r\n";
  12985. ::send(cli,
  12986. #ifdef _WIN32
  12987. static_cast<const char *>(response_header.c_str()),
  12988. static_cast<int>(response_header.size()),
  12989. #else
  12990. response_header.c_str(), response_header.size(),
  12991. #endif
  12992. 0);
  12993. std::string chunk(64 * 1024, 'A');
  12994. size_t total_sent = 0;
  12995. while (total_sent < DATA_SIZE) {
  12996. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12997. auto sent = ::send(cli,
  12998. #ifdef _WIN32
  12999. static_cast<const char *>(chunk.c_str()),
  13000. static_cast<int>(to_send),
  13001. #else
  13002. chunk.c_str(), to_send,
  13003. #endif
  13004. 0);
  13005. if (sent <= 0) break;
  13006. total_sent += static_cast<size_t>(sent);
  13007. }
  13008. #ifdef _WIN32
  13009. ::shutdown(cli, SD_SEND);
  13010. #else
  13011. ::shutdown(cli, SHUT_WR);
  13012. #endif
  13013. char drain[1024];
  13014. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13015. detail::close_socket(cli);
  13016. }
  13017. detail::close_socket(srv);
  13018. });
  13019. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13020. size_t total_received = 0;
  13021. {
  13022. Client cli("127.0.0.1", PORT + 2);
  13023. cli.set_read_timeout(10, 0);
  13024. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13025. auto res =
  13026. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13027. total_received += data_length;
  13028. return true;
  13029. });
  13030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13031. EXPECT_EQ(StatusCode::OK_200, res->status);
  13032. }
  13033. server_thread.join();
  13034. EXPECT_EQ(total_received, DATA_SIZE)
  13035. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13036. << " bytes (larger than " << DATA_SIZE
  13037. << " bytes response), content_receiver should read all data, but only "
  13038. "read "
  13039. << total_received << " bytes.";
  13040. }
  13041. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13042. // Regression test for "zip bomb" attack on the client side: a malicious server
  13043. // sends a small gzip-compressed response that decompresses to a huge payload.
  13044. // The client must enforce payload_max_length on the decompressed size.
  13045. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13046. constexpr size_t DECOMPRESSED_SIZE =
  13047. 10 * 1024 * 1024; // 10MB after decompression
  13048. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13049. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13050. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13051. std::string compressed;
  13052. {
  13053. httplib::detail::gzip_compressor compressor;
  13054. bool ok =
  13055. compressor.compress(uncompressed.data(), uncompressed.size(),
  13056. /*last=*/true, [&](const char *buf, size_t len) {
  13057. compressed.append(buf, len);
  13058. return true;
  13059. });
  13060. ASSERT_TRUE(ok);
  13061. }
  13062. // Sanity: compressed data should be much smaller than the decompressed size
  13063. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13064. #ifndef _WIN32
  13065. signal(SIGPIPE, SIG_IGN);
  13066. #endif
  13067. // Set up the listening socket in the main thread so the server is guaranteed
  13068. // to be ready before the client connects (eliminates race condition).
  13069. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13070. default_socket_options(srv);
  13071. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13072. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13073. sockaddr_in addr{};
  13074. addr.sin_family = AF_INET;
  13075. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13076. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13077. int opt = 1;
  13078. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13079. #ifdef _WIN32
  13080. reinterpret_cast<const char *>(&opt),
  13081. #else
  13082. &opt,
  13083. #endif
  13084. sizeof(opt));
  13085. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13086. ASSERT_EQ(0, ::listen(srv, 1));
  13087. auto server_thread = std::thread([&compressed, srv] {
  13088. sockaddr_in cli_addr{};
  13089. socklen_t cli_len = sizeof(cli_addr);
  13090. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13091. if (cli != INVALID_SOCKET) {
  13092. // Read the full HTTP request (until \r\n\r\n)
  13093. char buf[4096];
  13094. size_t total = 0;
  13095. while (total < sizeof(buf)) {
  13096. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13097. if (n <= 0) break;
  13098. total += static_cast<size_t>(n);
  13099. // Check for end of headers
  13100. if (total >= 4) {
  13101. std::string req(buf, total);
  13102. if (req.find("\r\n\r\n") != std::string::npos) break;
  13103. }
  13104. }
  13105. // Malicious response: gzip-compressed body, no Content-Length
  13106. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13107. "Content-Encoding: gzip\r\n"
  13108. "Connection: close\r\n"
  13109. "\r\n";
  13110. ::send(cli,
  13111. #ifdef _WIN32
  13112. static_cast<const char *>(response_header.c_str()),
  13113. static_cast<int>(response_header.size()),
  13114. #else
  13115. response_header.c_str(), response_header.size(),
  13116. #endif
  13117. 0);
  13118. // Send the compressed payload (small on the wire, huge when decompressed)
  13119. size_t total_sent = 0;
  13120. while (total_sent < compressed.size()) {
  13121. auto to_send = std::min(compressed.size() - total_sent,
  13122. static_cast<size_t>(64 * 1024));
  13123. auto sent =
  13124. ::send(cli,
  13125. #ifdef _WIN32
  13126. static_cast<const char *>(compressed.c_str() + total_sent),
  13127. static_cast<int>(to_send),
  13128. #else
  13129. compressed.c_str() + total_sent, to_send,
  13130. #endif
  13131. 0);
  13132. if (sent <= 0) break;
  13133. total_sent += static_cast<size_t>(sent);
  13134. }
  13135. detail::close_socket(cli);
  13136. }
  13137. });
  13138. auto se = detail::scope_exit([&] {
  13139. detail::close_socket(srv);
  13140. server_thread.join();
  13141. });
  13142. size_t total_decompressed = 0;
  13143. {
  13144. Client cli("127.0.0.1", PORT + 3);
  13145. cli.set_read_timeout(5, 0);
  13146. cli.set_decompress(true);
  13147. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13148. auto stream = cli.open_stream("GET", "/zipbomb");
  13149. ASSERT_TRUE(stream.is_valid());
  13150. char buffer[64 * 1024];
  13151. ssize_t n;
  13152. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13153. total_decompressed += static_cast<size_t>(n);
  13154. }
  13155. }
  13156. // The decompressed size must be capped by payload_max_length. Without
  13157. // protection, the client would decompress the full 10MB from a tiny
  13158. // compressed payload, enabling a zip bomb DoS attack.
  13159. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13160. << "Client decompressed " << total_decompressed
  13161. << " bytes from a gzip response. The decompressed size should be "
  13162. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13163. }
  13164. #endif
  13165. TEST(HostAndPortPropertiesTest, NoSSL) {
  13166. httplib::Client cli("www.google.com", 1234);
  13167. ASSERT_EQ("www.google.com", cli.host());
  13168. ASSERT_EQ(1234, cli.port());
  13169. }
  13170. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13171. httplib::Client cli("www.google.com:1234");
  13172. ASSERT_EQ("www.google.com", cli.host());
  13173. ASSERT_EQ(1234, cli.port());
  13174. }
  13175. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13176. // Port number that overflows int — should not crash, client becomes invalid
  13177. httplib::Client cli("http://www.google.com:99999999999999999999");
  13178. ASSERT_FALSE(cli.is_valid());
  13179. }
  13180. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13181. // Port 99999 exceeds valid range (1-65535) — should not crash
  13182. httplib::Client cli("http://www.google.com:99999");
  13183. ASSERT_FALSE(cli.is_valid());
  13184. auto res = cli.Get("/");
  13185. EXPECT_FALSE(res);
  13186. EXPECT_EQ(Error::Connection, res.error());
  13187. }
  13188. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13189. httplib::Client cli("http://user:pass@localhost:1234");
  13190. ASSERT_FALSE(cli.is_valid());
  13191. EXPECT_FALSE(cli.Get("/"));
  13192. }
  13193. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13194. httplib::Client cli("http://www.google.com:80abc");
  13195. ASSERT_FALSE(cli.is_valid());
  13196. }
  13197. #ifdef CPPHTTPLIB_SSL_ENABLED
  13198. TEST(HostAndPortPropertiesTest, SSL) {
  13199. httplib::SSLClient cli("www.google.com");
  13200. ASSERT_EQ("www.google.com", cli.host());
  13201. ASSERT_EQ(443, cli.port());
  13202. }
  13203. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13204. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13205. std::string cert;
  13206. read_file(CA_CERT_FILE, cert);
  13207. httplib::SSLClient httplib_client("www.google.com");
  13208. // Load CA store first time
  13209. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13210. // Load CA store second time (update)
  13211. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13212. // Verify client is still valid and can make connections
  13213. httplib_client.enable_server_certificate_verification(true);
  13214. auto res = httplib_client.Get("/");
  13215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13216. // Google may return 200 or 301 depending on various factors
  13217. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13218. res->status == StatusCode::MovedPermanently_301);
  13219. }
  13220. TEST(SSLClientTest, ServerNameIndication_Online) {
  13221. auto host = "httpbingo.org";
  13222. auto path = std::string{"/get"};
  13223. SSLClient cli(host, 443);
  13224. auto res = cli.Get(path);
  13225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13226. ASSERT_EQ(StatusCode::OK_200, res->status);
  13227. }
  13228. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13229. // Use a site that will cause SSL verification failure due to self-signed cert
  13230. SSLClient cli("self-signed.badssl.com", 443);
  13231. cli.enable_server_certificate_verification(true);
  13232. auto res = cli.Get("/");
  13233. ASSERT_TRUE(!res);
  13234. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13235. // Verify backend error is captured for SSLServerVerification
  13236. // This occurs when certificate verification fails
  13237. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13238. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13239. EXPECT_NE(0UL, res.ssl_backend_error());
  13240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13241. // For OpenSSL, ssl_error is 0 for verification errors
  13242. EXPECT_EQ(0, res.ssl_error());
  13243. #if !defined(_WIN32) || \
  13244. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13245. // On non-Windows or when Windows Schannel is disabled, the error comes
  13246. // from OpenSSL's verification
  13247. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13248. res.ssl_backend_error());
  13249. #endif
  13250. #endif
  13251. }
  13252. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13253. // Use a site where hostname doesn't match the certificate
  13254. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13255. SSLClient cli("wrong.host.badssl.com", 443);
  13256. cli.enable_server_certificate_verification(true);
  13257. cli.enable_server_hostname_verification(true);
  13258. auto res = cli.Get("/");
  13259. ASSERT_TRUE(!res);
  13260. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13261. // Verify backend error is captured for hostname verification failure
  13262. EXPECT_NE(0UL, res.ssl_backend_error());
  13263. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13264. // For OpenSSL, ssl_error is 0 for verification errors
  13265. EXPECT_EQ(0, res.ssl_error());
  13266. #if !defined(_WIN32) || \
  13267. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13268. // On non-Windows or when Windows Schannel is disabled, the error comes
  13269. // from OpenSSL's hostname verification
  13270. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13271. res.ssl_backend_error());
  13272. #endif
  13273. #endif
  13274. }
  13275. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13276. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13277. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13278. SSLClient cli("www.google.com", 443);
  13279. cli.enable_server_certificate_verification(true);
  13280. auto res = cli.Get("/");
  13281. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13282. }
  13283. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13284. SSLClient cli("www.google.com", 443);
  13285. cli.enable_server_certificate_verification(true);
  13286. cli.enable_windows_certificate_verification(false);
  13287. auto res = cli.Get("/");
  13288. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13289. }
  13290. // The server sends an intermediate cross-signed by a root Windows trusts,
  13291. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13292. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13293. SSLClient cli("accounts.spotify.com", 443);
  13294. auto res = cli.Get("/");
  13295. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13296. << " ssl_backend_error=" << res.ssl_backend_error();
  13297. }
  13298. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13299. // policy status, which no backend reports for a self-signed certificate.
  13300. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13301. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13302. ASSERT_TRUE(svr.is_valid());
  13303. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13304. auto se = detail::scope_exit([&] {
  13305. svr.stop();
  13306. t.join();
  13307. ASSERT_FALSE(svr.is_running());
  13308. });
  13309. svr.wait_until_ready();
  13310. SSLClient cli("127.0.0.1", PORT);
  13311. cli.set_connection_timeout(30);
  13312. auto res = cli.Get("/");
  13313. ASSERT_FALSE(res);
  13314. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13315. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13316. }
  13317. #endif
  13318. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13319. Client cli("https://google.com");
  13320. auto res = cli.Get("/");
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13323. }
  13324. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13325. SSLClient cli("google.com");
  13326. cli.set_ca_cert_path(CA_CERT_FILE);
  13327. auto res = cli.Get("/");
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13330. }
  13331. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13332. SSLClient cli("google.com");
  13333. cli.enable_server_certificate_verification(true);
  13334. cli.set_ca_cert_path("hello");
  13335. auto res = cli.Get("/");
  13336. ASSERT_TRUE(!res);
  13337. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13338. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13339. // should be set
  13340. EXPECT_EQ(0, res.ssl_error());
  13341. // Verify backend error is captured for SSLLoadingCerts
  13342. // This error occurs when loading CA certificates fails
  13343. EXPECT_NE(0UL, res.ssl_backend_error());
  13344. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13345. // OpenSSL specific error codes:
  13346. // > openssl errstr 0x80000002
  13347. // error:80000002:system library::No such file or directory
  13348. // > openssl errstr 0xA000126
  13349. // error:0A000126:SSL routines::unexpected eof while reading
  13350. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13351. res.ssl_backend_error() == 0xA000126);
  13352. #endif
  13353. }
  13354. TEST(SSLClientTest, ServerCertificateVerification4) {
  13355. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13356. ASSERT_TRUE(svr.is_valid());
  13357. svr.Get("/test", [&](const Request &, Response &res) {
  13358. res.set_content("test", "text/plain");
  13359. svr.stop();
  13360. ASSERT_TRUE(true);
  13361. });
  13362. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13363. auto se = detail::scope_exit([&] {
  13364. t.join();
  13365. ASSERT_FALSE(svr.is_running());
  13366. });
  13367. svr.wait_until_ready();
  13368. SSLClient cli("127.0.0.1", PORT);
  13369. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13370. cli.enable_server_certificate_verification(true);
  13371. cli.set_connection_timeout(30);
  13372. auto res = cli.Get("/test");
  13373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13374. ASSERT_EQ(StatusCode::OK_200, res->status);
  13375. }
  13376. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13377. std::string cert;
  13378. read_file(CA_CERT_FILE, cert);
  13379. SSLClient cli("google.com");
  13380. cli.load_ca_cert_store(cert.data(), cert.size());
  13381. const auto res = cli.Get("/");
  13382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13383. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13384. }
  13385. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13386. // clang-format off
  13387. static constexpr char cert[] =
  13388. "GlobalSign Root CA\n"
  13389. "==================\n"
  13390. "-----BEGIN CERTIFICATE-----\n"
  13391. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13392. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13393. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13394. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13395. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13396. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13397. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13398. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13399. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13400. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13401. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13402. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13403. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13404. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13405. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13406. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13407. "-----END CERTIFICATE-----\n";
  13408. // clang-format on
  13409. SSLClient cli("google.com");
  13410. cli.load_ca_cert_store(cert, sizeof(cert));
  13411. const auto res = cli.Get("/");
  13412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13413. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13414. }
  13415. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13416. SSLClient cli("www.youtube.com");
  13417. cli.set_ca_cert_path(CA_CERT_FILE);
  13418. cli.enable_server_certificate_verification(true);
  13419. cli.set_follow_location(true);
  13420. auto res = cli.Get("/");
  13421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13422. ASSERT_EQ(StatusCode::OK_200, res->status);
  13423. }
  13424. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13425. SSLClient cli("wWw.YouTube.Com");
  13426. cli.set_ca_cert_path(CA_CERT_FILE);
  13427. cli.enable_server_certificate_verification(true);
  13428. cli.enable_server_hostname_verification(true);
  13429. cli.set_follow_location(true);
  13430. auto res = cli.Get("/");
  13431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13432. ASSERT_EQ(StatusCode::OK_200, res->status);
  13433. }
  13434. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13435. SSLClient cli("gOoGlE.COm");
  13436. cli.enable_server_certificate_verification(true);
  13437. cli.enable_server_hostname_verification(true);
  13438. cli.set_follow_location(true);
  13439. auto res = cli.Get("/");
  13440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13441. ASSERT_EQ(StatusCode::OK_200, res->status);
  13442. }
  13443. TEST(SSLClientTest, Issue2004_Online) {
  13444. Client client("https://google.com");
  13445. client.set_follow_location(true);
  13446. auto res = client.Get("/");
  13447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13448. ASSERT_EQ(StatusCode::OK_200, res->status);
  13449. auto body = res->body;
  13450. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13451. }
  13452. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13453. // Create SSLClient with invalid cert/key to make is_valid() return false
  13454. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13455. "nonexistent_key.pem");
  13456. // is_valid() should be false due to cert loading failure
  13457. ASSERT_FALSE(cli.is_valid());
  13458. auto res = cli.Get("/");
  13459. ASSERT_FALSE(res);
  13460. EXPECT_EQ(Error::SSLConnection, res.error());
  13461. }
  13462. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13463. // Test for Issue #2251: SSL error not properly reported when client cert
  13464. // and key paths are swapped or mismatched
  13465. // This simulates the scenario where user accidentally swaps the cert and key
  13466. // files
  13467. // Using client cert file as private key and vice versa (completely wrong)
  13468. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13469. // Should fail validation due to cert/key mismatch
  13470. ASSERT_FALSE(cli.is_valid());
  13471. // Attempt to make a request should fail with proper error
  13472. auto res = cli.Get("/");
  13473. ASSERT_FALSE(res);
  13474. EXPECT_EQ(Error::SSLConnection, res.error());
  13475. // SSL error should be recorded in the Result object (this is the key fix for
  13476. // Issue #2251)
  13477. auto backend_error = res.ssl_backend_error();
  13478. EXPECT_NE(0u, backend_error);
  13479. }
  13480. // Tests cert/key mismatch detection at the TLS context level
  13481. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13482. // Test that using mismatched cert/key causes connection failure.
  13483. // We verify this at the SSLClient level rather than through internal
  13484. // TLS API functions.
  13485. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13486. cli.enable_server_certificate_verification(false);
  13487. cli.set_connection_timeout(2);
  13488. // The mismatch should cause a connection or handshake error
  13489. auto res = cli.Get("/test");
  13490. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13491. // Either way, the request should fail
  13492. EXPECT_FALSE(res);
  13493. }
  13494. #endif
  13495. #if 0
  13496. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13497. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13498. ASSERT_TRUE(cli != nullptr);
  13499. cli->set_address_family(AF_INET6);
  13500. cli->set_interface("en0");
  13501. auto res = cli->Get("/get");
  13502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13503. ASSERT_EQ(StatusCode::OK_200, res->status);
  13504. }
  13505. #endif
  13506. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13507. #ifdef CPPHTTPLIB_SSL_ENABLED
  13508. void ClientCertPresent(
  13509. const std::string &client_cert_file,
  13510. const std::string &client_private_key_file,
  13511. const std::string &client_encrypted_private_key_pass = std::string()) {
  13512. using namespace httplib::tls;
  13513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13514. CLIENT_CA_CERT_DIR);
  13515. ASSERT_TRUE(svr.is_valid());
  13516. svr.Get("/test", [&](const Request &req, Response &res) {
  13517. res.set_content("test", "text/plain");
  13518. auto cert = req.peer_cert();
  13519. ASSERT_TRUE(static_cast<bool>(cert));
  13520. std::string common_name = cert.subject_cn();
  13521. EXPECT_EQ("Common Name", common_name);
  13522. });
  13523. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13524. auto se = detail::scope_exit([&] {
  13525. svr.stop();
  13526. t.join();
  13527. ASSERT_FALSE(svr.is_running());
  13528. });
  13529. svr.wait_until_ready();
  13530. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13531. client_encrypted_private_key_pass);
  13532. cli.enable_server_certificate_verification(false);
  13533. cli.set_connection_timeout(30);
  13534. auto res = cli.Get("/test");
  13535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13536. ASSERT_EQ(StatusCode::OK_200, res->status);
  13537. }
  13538. TEST(SSLClientServerTest, ClientCertPresent) {
  13539. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13540. }
  13541. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13542. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13543. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13544. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13545. }
  13546. // PEM memory-based constructor tests (works with all TLS backends)
  13547. void PemMemoryClientCertPresent(
  13548. const std::string &client_cert_file,
  13549. const std::string &client_private_key_file,
  13550. const std::string &client_encrypted_private_key_pass = std::string()) {
  13551. // Read PEM files into memory
  13552. std::string server_cert_pem, server_key_pem;
  13553. std::string client_ca_pem;
  13554. std::string client_cert_pem, client_key_pem;
  13555. read_file(SERVER_CERT_FILE, server_cert_pem);
  13556. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13557. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13558. read_file(client_cert_file, client_cert_pem);
  13559. read_file(client_private_key_file, client_key_pem);
  13560. // Create server with PEM memory
  13561. SSLServer::PemMemory server_pem = {
  13562. server_cert_pem.c_str(),
  13563. server_cert_pem.size(),
  13564. server_key_pem.c_str(),
  13565. server_key_pem.size(),
  13566. client_ca_pem.c_str(),
  13567. client_ca_pem.size(),
  13568. nullptr // no password for server key
  13569. };
  13570. SSLServer svr(server_pem);
  13571. ASSERT_TRUE(svr.is_valid());
  13572. svr.Get("/test", [&](const Request &, Response &res) {
  13573. res.set_content("test", "text/plain");
  13574. });
  13575. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13576. auto se = detail::scope_exit([&] {
  13577. svr.stop();
  13578. t.join();
  13579. ASSERT_FALSE(svr.is_running());
  13580. });
  13581. svr.wait_until_ready();
  13582. // Create client with PEM memory
  13583. const char *password = client_encrypted_private_key_pass.empty()
  13584. ? nullptr
  13585. : client_encrypted_private_key_pass.c_str();
  13586. SSLClient::PemMemory client_pem = {
  13587. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13588. client_key_pem.size(), password};
  13589. SSLClient cli(HOST, PORT, client_pem);
  13590. cli.enable_server_certificate_verification(false);
  13591. cli.set_connection_timeout(30);
  13592. auto res = cli.Get("/test");
  13593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13594. ASSERT_EQ(StatusCode::OK_200, res->status);
  13595. }
  13596. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13597. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13598. }
  13599. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13600. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13601. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13602. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13603. }
  13604. TEST(SSLClientServerTest, ClientCertMissing) {
  13605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13606. CLIENT_CA_CERT_DIR);
  13607. ASSERT_TRUE(svr.is_valid());
  13608. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13609. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13610. auto se = detail::scope_exit([&] {
  13611. svr.stop();
  13612. t.join();
  13613. ASSERT_FALSE(svr.is_running());
  13614. });
  13615. svr.wait_until_ready();
  13616. SSLClient cli(HOST, PORT);
  13617. cli.set_connection_timeout(30);
  13618. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13619. // the chain check on Windows, so the result does not depend on the order.
  13620. cli.enable_server_hostname_verification(false);
  13621. auto res = cli.Get("/test");
  13622. ASSERT_TRUE(!res);
  13623. // When client cert is missing and server requires it, connection fails
  13624. // Error type depends on backend implementation
  13625. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13626. res.error() == Error::SSLConnection);
  13627. // Verify backend error is captured
  13628. // Note: This test may have different error codes depending on the exact
  13629. // verification failure
  13630. EXPECT_NE(0UL, res.ssl_backend_error());
  13631. }
  13632. TEST(SSLClientServerTest, TrustDirOptional) {
  13633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13634. ASSERT_TRUE(svr.is_valid());
  13635. svr.Get("/test", [&](const Request &, Response &res) {
  13636. res.set_content("test", "text/plain");
  13637. });
  13638. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13639. auto se = detail::scope_exit([&] {
  13640. svr.stop();
  13641. t.join();
  13642. ASSERT_FALSE(svr.is_running());
  13643. });
  13644. svr.wait_until_ready();
  13645. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13646. cli.enable_server_certificate_verification(false);
  13647. cli.set_connection_timeout(30);
  13648. auto res = cli.Get("/test");
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. ASSERT_EQ(StatusCode::OK_200, res->status);
  13651. }
  13652. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13653. class NoListenSSLServer : public SSLServer {
  13654. public:
  13655. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13656. const char *client_ca_cert_file_path,
  13657. const char *client_ca_cert_dir_path = nullptr)
  13658. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13659. client_ca_cert_dir_path),
  13660. stop_(false) {}
  13661. std::atomic_bool stop_;
  13662. private:
  13663. bool process_and_close_socket(socket_t /*sock*/) override {
  13664. // Don't create SSL context
  13665. while (!stop_.load()) {
  13666. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13667. }
  13668. return true;
  13669. }
  13670. };
  13671. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13672. CLIENT_CA_CERT_FILE);
  13673. ASSERT_TRUE(svr.is_valid());
  13674. svr.Get("/test", [&](const Request &, Response &res) {
  13675. res.set_content("test", "text/plain");
  13676. });
  13677. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13678. auto se = detail::scope_exit([&] {
  13679. svr.stop_ = true;
  13680. svr.stop();
  13681. t.join();
  13682. ASSERT_FALSE(svr.is_running());
  13683. });
  13684. svr.wait_until_ready();
  13685. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13686. cli.enable_server_certificate_verification(false);
  13687. cli.set_connection_timeout(1);
  13688. auto res = cli.Get("/test");
  13689. ASSERT_TRUE(!res);
  13690. EXPECT_EQ(Error::SSLConnection, res.error());
  13691. // Timeout results in WantRead error code (maps to backend-specific value)
  13692. EXPECT_NE(0, res.ssl_error());
  13693. }
  13694. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13695. // Test SSLServer with client certificate verification using the standard
  13696. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13697. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13698. CLIENT_CA_CERT_DIR);
  13699. ASSERT_TRUE(svr.is_valid());
  13700. svr.Get("/test", [&](const Request &req, Response &res) {
  13701. res.set_content("test", "text/plain");
  13702. auto cert = req.peer_cert();
  13703. ASSERT_TRUE(static_cast<bool>(cert));
  13704. auto common_name = cert.subject_cn();
  13705. EXPECT_EQ("Common Name", common_name);
  13706. });
  13707. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13708. auto se = detail::scope_exit([&] {
  13709. svr.stop();
  13710. t.join();
  13711. ASSERT_FALSE(svr.is_running());
  13712. });
  13713. svr.wait_until_ready();
  13714. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13715. cli.enable_server_certificate_verification(false);
  13716. cli.set_connection_timeout(30);
  13717. auto res = cli.Get("/test");
  13718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13719. ASSERT_EQ(StatusCode::OK_200, res->status);
  13720. }
  13721. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13722. // Verifies that wildcard matching and exact matching work consistently
  13723. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13724. using namespace httplib::tls;
  13725. // We need a running server to test against
  13726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13727. ASSERT_TRUE(svr.is_valid());
  13728. svr.Get("/test", [](const Request &, Response &res) {
  13729. res.set_content("ok", "text/plain");
  13730. });
  13731. thread t([&]() { svr.listen(HOST, PORT); });
  13732. auto se = detail::scope_exit([&] {
  13733. svr.stop();
  13734. t.join();
  13735. });
  13736. svr.wait_until_ready();
  13737. bool verify_callback_called = false;
  13738. bool verify_result_wrong = false;
  13739. SSLClient cli(HOST, PORT);
  13740. cli.enable_server_certificate_verification(true);
  13741. cli.set_ca_cert_path(CA_CERT_FILE);
  13742. cli.set_connection_timeout(5);
  13743. // Note: Test certificate has CN="Common Name", not "localhost"
  13744. bool verify_result_cn = false;
  13745. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13746. verify_callback_called = true;
  13747. if (!ctx.cert) return false;
  13748. // Test 1: "Common Name" should match (our test server cert CN)
  13749. verify_result_cn = ctx.check_hostname("Common Name");
  13750. // Test 2: wrong hostname should not match
  13751. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13752. return true; // Accept for the purpose of this test
  13753. });
  13754. auto res = cli.Get("/test");
  13755. // The request may succeed or fail depending on cert configuration
  13756. // but the callback should have been called
  13757. ASSERT_TRUE(verify_callback_called)
  13758. << "Verify callback should have been called";
  13759. // CN="Common Name" should match our test certificate
  13760. //
  13761. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13762. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13763. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13764. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13765. // <openssl/base.h>, which is included transitively when
  13766. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13767. #if defined(OPENSSL_IS_BORINGSSL)
  13768. EXPECT_FALSE(verify_result_cn)
  13769. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13770. #else
  13771. EXPECT_TRUE(verify_result_cn)
  13772. << "verify_hostname should match 'Common Name' (certificate CN)";
  13773. #endif
  13774. // Wrong hostname should not match
  13775. EXPECT_FALSE(verify_result_wrong)
  13776. << "verify_hostname should not match 'wronghost.example.com'";
  13777. }
  13778. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13779. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13780. // X509_check_ip behavior and must hold for every backend.
  13781. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13782. using namespace httplib::tls;
  13783. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13784. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13785. ASSERT_TRUE(svr.is_valid());
  13786. svr.Get("/test", [](const Request &, Response &res) {
  13787. res.set_content("ok", "text/plain");
  13788. });
  13789. thread t([&]() { svr.listen(HOST, PORT); });
  13790. auto se = detail::scope_exit([&] {
  13791. svr.stop();
  13792. t.join();
  13793. });
  13794. svr.wait_until_ready();
  13795. bool verify_callback_called = false;
  13796. bool ip_matched_via_cn = true;
  13797. SSLClient cli(HOST, PORT);
  13798. cli.enable_server_certificate_verification(true);
  13799. cli.set_ca_cert_path(CA_CERT_FILE);
  13800. cli.set_connection_timeout(5);
  13801. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13802. verify_callback_called = true;
  13803. if (!ctx.cert) return false;
  13804. // The IP appears only in the CN, so it must NOT be accepted.
  13805. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13806. return true; // Accept for the purpose of this test
  13807. });
  13808. cli.Get("/test");
  13809. ASSERT_TRUE(verify_callback_called)
  13810. << "Verify callback should have been called";
  13811. EXPECT_FALSE(ip_matched_via_cn)
  13812. << "An IP host must not be authenticated via the certificate CN";
  13813. }
  13814. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13815. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13816. using namespace httplib::tls;
  13817. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13818. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13819. ASSERT_TRUE(svr.is_valid());
  13820. svr.Get("/test", [](const Request &, Response &res) {
  13821. res.set_content("ok", "text/plain");
  13822. });
  13823. thread t([&]() { svr.listen(HOST, PORT); });
  13824. auto se = detail::scope_exit([&] {
  13825. svr.stop();
  13826. t.join();
  13827. });
  13828. svr.wait_until_ready();
  13829. bool verify_callback_called = false;
  13830. bool san_matched = false;
  13831. bool wrong_ipv6_matched = true;
  13832. bool cn_ipv6_matched = true;
  13833. SSLClient cli(HOST, PORT);
  13834. cli.enable_server_certificate_verification(true);
  13835. cli.set_ca_cert_path(CA_CERT_FILE);
  13836. cli.set_connection_timeout(5);
  13837. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13838. verify_callback_called = true;
  13839. if (!ctx.cert) return false;
  13840. // Matches the IPv6 iPAddress SAN.
  13841. san_matched = ctx.check_hostname("2001:db8::1");
  13842. // A different IPv6 address must not match.
  13843. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13844. // "::1" lives only in the CN, so it must not be accepted.
  13845. cn_ipv6_matched = ctx.check_hostname("::1");
  13846. return true; // Accept for the purpose of this test
  13847. });
  13848. cli.Get("/test");
  13849. ASSERT_TRUE(verify_callback_called)
  13850. << "Verify callback should have been called";
  13851. EXPECT_TRUE(san_matched)
  13852. << "verify_hostname should match an IPv6 iPAddress SAN";
  13853. EXPECT_FALSE(wrong_ipv6_matched)
  13854. << "verify_hostname should not match a non-matching IPv6 address";
  13855. EXPECT_FALSE(cn_ipv6_matched)
  13856. << "An IPv6 host must not be authenticated via the certificate CN";
  13857. }
  13858. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13859. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13860. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13861. using namespace httplib::tls;
  13862. // SANs: DNS:a.zz, IP:42.46.122.122
  13863. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13864. ASSERT_TRUE(svr.is_valid());
  13865. svr.Get("/test", [](const Request &, Response &res) {
  13866. res.set_content("ok", "text/plain");
  13867. });
  13868. auto port = svr.bind_to_any_port(HOST);
  13869. thread t([&]() { svr.listen_after_bind(); });
  13870. auto se = detail::scope_exit([&] {
  13871. svr.stop();
  13872. t.join();
  13873. });
  13874. svr.wait_until_ready();
  13875. bool verify_callback_called = false;
  13876. bool dns_san_matched = false;
  13877. bool ip_san_matched = false;
  13878. bool ip_matched_via_dns_san = true;
  13879. bool dns_matched_via_ip_san = true;
  13880. bool cn_matched_next_to_dns_san = true;
  13881. SSLClient cli(HOST, port);
  13882. cli.enable_server_certificate_verification(true);
  13883. cli.set_ca_cert_path(CA_CERT_FILE);
  13884. cli.set_connection_timeout(5);
  13885. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13886. verify_callback_called = true;
  13887. if (!ctx.cert) return false;
  13888. dns_san_matched = ctx.check_hostname("a.zz");
  13889. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13890. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13891. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13892. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13893. return true; // Accept for the purpose of this test
  13894. });
  13895. cli.Get("/test");
  13896. ASSERT_TRUE(verify_callback_called)
  13897. << "Verify callback should have been called";
  13898. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13899. EXPECT_TRUE(ip_san_matched)
  13900. << "verify_hostname should match an iPAddress SAN";
  13901. EXPECT_FALSE(ip_matched_via_dns_san)
  13902. << "An IP host must not be authenticated via a dNSName SAN";
  13903. EXPECT_FALSE(dns_matched_via_ip_san)
  13904. << "A DNS host must not be authenticated via an iPAddress SAN";
  13905. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13906. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13907. }
  13908. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13909. // "www.*.example.test" names one host and not every host under example.test.
  13910. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13911. using namespace httplib::tls;
  13912. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13913. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13914. ASSERT_TRUE(svr.is_valid());
  13915. svr.Get("/test", [](const Request &, Response &res) {
  13916. res.set_content("ok", "text/plain");
  13917. });
  13918. auto port = svr.bind_to_any_port(HOST);
  13919. thread t([&]() { svr.listen_after_bind(); });
  13920. auto se = detail::scope_exit([&] {
  13921. svr.stop();
  13922. t.join();
  13923. });
  13924. svr.wait_until_ready();
  13925. bool verify_callback_called = false;
  13926. bool leftmost_wildcard_matched = false;
  13927. bool wildcard_spanned_labels = true;
  13928. bool inner_wildcard_matched = true;
  13929. SSLClient cli(HOST, port);
  13930. cli.enable_server_certificate_verification(true);
  13931. cli.set_ca_cert_path(CA_CERT_FILE);
  13932. cli.set_connection_timeout(5);
  13933. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13934. verify_callback_called = true;
  13935. if (!ctx.cert) return false;
  13936. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13937. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13938. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13939. return true; // Accept for the purpose of this test
  13940. });
  13941. cli.Get("/test");
  13942. ASSERT_TRUE(verify_callback_called)
  13943. << "Verify callback should have been called";
  13944. EXPECT_TRUE(leftmost_wildcard_matched)
  13945. << "A leftmost wildcard should match a single label";
  13946. EXPECT_FALSE(wildcard_spanned_labels)
  13947. << "A wildcard label must not match more than one label";
  13948. EXPECT_FALSE(inner_wildcard_matched)
  13949. << "A wildcard outside the leftmost label must not be honoured";
  13950. }
  13951. // sans() must report each SAN entry under its own type.
  13952. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13953. using namespace httplib::tls;
  13954. // SANs: DNS:a.zz, IP:42.46.122.122
  13955. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13956. ASSERT_TRUE(svr.is_valid());
  13957. svr.Get("/test", [](const Request &, Response &res) {
  13958. res.set_content("ok", "text/plain");
  13959. });
  13960. auto port = svr.bind_to_any_port(HOST);
  13961. thread t([&]() { svr.listen_after_bind(); });
  13962. auto se = detail::scope_exit([&] {
  13963. svr.stop();
  13964. t.join();
  13965. });
  13966. svr.wait_until_ready();
  13967. bool verify_callback_called = false;
  13968. std::vector<SanEntry> sans;
  13969. SSLClient cli(HOST, port);
  13970. cli.enable_server_certificate_verification(true);
  13971. cli.set_ca_cert_path(CA_CERT_FILE);
  13972. cli.set_connection_timeout(5);
  13973. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13974. verify_callback_called = true;
  13975. if (!ctx.cert) return false;
  13976. sans = ctx.sans();
  13977. return true; // Accept for the purpose of this test
  13978. });
  13979. cli.Get("/test");
  13980. ASSERT_TRUE(verify_callback_called)
  13981. << "Verify callback should have been called";
  13982. auto has_san = [&](SanType type, const std::string &value) {
  13983. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13984. return san.type == type && san.value == value;
  13985. });
  13986. };
  13987. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13988. << "sans() should report the dNSName SAN";
  13989. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13990. << "sans() should report the iPAddress SAN";
  13991. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13992. << "sans() must not report the dNSName SAN as an address";
  13993. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13994. << "sans() must not report the iPAddress SAN as a DNS name";
  13995. }
  13996. #endif
  13997. // mbedTLS-specific callback constructor test
  13998. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13999. #ifdef CPPHTTPLIB_SSL_ENABLED
  14000. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14002. ASSERT_TRUE(svr.is_valid());
  14003. // Set up a handler to verify client certificate is present
  14004. bool client_cert_verified = false;
  14005. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14006. // Verify that client certificate was provided
  14007. client_cert_verified = true;
  14008. res.set_content("success", "text/plain");
  14009. });
  14010. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14011. auto se = detail::scope_exit([&] {
  14012. svr.stop();
  14013. t.join();
  14014. ASSERT_FALSE(svr.is_running());
  14015. });
  14016. svr.wait_until_ready();
  14017. // Client with certificate
  14018. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14019. cli.enable_server_certificate_verification(false);
  14020. cli.set_connection_timeout(30);
  14021. auto res = cli.Get("/test");
  14022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14023. ASSERT_EQ(StatusCode::OK_200, res->status);
  14024. ASSERT_TRUE(client_cert_verified);
  14025. EXPECT_EQ("success", res->body);
  14026. }
  14027. #endif
  14028. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14029. // backends
  14030. #ifdef CPPHTTPLIB_SSL_ENABLED
  14031. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14032. using namespace httplib::tls;
  14033. // Test that when client CA cert file is provided,
  14034. // the server properly requests and validates client certificates
  14035. // Create a server with client authentication
  14036. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14037. ASSERT_TRUE(svr.is_valid());
  14038. bool handler_called = false;
  14039. svr.Get("/test", [&](const Request &req, Response &res) {
  14040. handler_called = true;
  14041. // Verify that a client certificate was provided
  14042. auto cert = req.peer_cert();
  14043. ASSERT_TRUE(static_cast<bool>(cert));
  14044. // Get the issuer name
  14045. std::string issuer_str = cert.issuer_name();
  14046. ASSERT_FALSE(issuer_str.empty());
  14047. // The client certificate should be issued by our test CA
  14048. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14049. res.set_content("authenticated", "text/plain");
  14050. });
  14051. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14052. auto se = detail::scope_exit([&] {
  14053. svr.stop();
  14054. t.join();
  14055. ASSERT_FALSE(svr.is_running());
  14056. });
  14057. svr.wait_until_ready();
  14058. // Connect with a client certificate issued by the CA
  14059. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14060. cli.enable_server_certificate_verification(false);
  14061. cli.set_connection_timeout(30);
  14062. auto res = cli.Get("/test");
  14063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14064. ASSERT_EQ(StatusCode::OK_200, res->status);
  14065. ASSERT_TRUE(handler_called);
  14066. EXPECT_EQ("authenticated", res->body);
  14067. }
  14068. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14069. using namespace httplib::tls;
  14070. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14071. ASSERT_TRUE(svr.is_valid());
  14072. svr.Get("/test", [](const Request &, Response &res) {
  14073. res.set_content("ok", "text/plain");
  14074. });
  14075. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14076. auto se = detail::scope_exit([&] {
  14077. svr.stop();
  14078. t.join();
  14079. });
  14080. svr.wait_until_ready();
  14081. SSLClient cli(HOST, PORT);
  14082. cli.enable_server_certificate_verification(false);
  14083. cli.set_connection_timeout(30);
  14084. bool cert_checked = false;
  14085. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14086. if (ctx.cert) {
  14087. auto sans = ctx.sans();
  14088. // Test certificate may or may not have SANs - just verify the API
  14089. // works If SANs exist, verify the types are valid
  14090. for (const auto &san : sans) {
  14091. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14092. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14093. san.type == SanType::OTHER);
  14094. EXPECT_FALSE(san.value.empty());
  14095. }
  14096. cert_checked = true;
  14097. }
  14098. return true;
  14099. });
  14100. auto res = cli.Get("/test");
  14101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14102. EXPECT_TRUE(cert_checked);
  14103. }
  14104. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14105. using namespace httplib::tls;
  14106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14107. ASSERT_TRUE(svr.is_valid());
  14108. svr.Get("/test", [](const Request &, Response &res) {
  14109. res.set_content("ok", "text/plain");
  14110. });
  14111. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14112. auto se = detail::scope_exit([&] {
  14113. svr.stop();
  14114. t.join();
  14115. });
  14116. svr.wait_until_ready();
  14117. SSLClient cli(HOST, PORT);
  14118. cli.enable_server_certificate_verification(false);
  14119. cli.set_connection_timeout(30);
  14120. bool validity_checked = false;
  14121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14122. if (ctx.cert) {
  14123. time_t not_before = 0, not_after = 0;
  14124. bool result = ctx.validity(not_before, not_after);
  14125. EXPECT_TRUE(result);
  14126. // Verify that not_before < now < not_after for a valid cert
  14127. time_t now = time(nullptr);
  14128. EXPECT_LT(not_before, now);
  14129. EXPECT_GT(not_after, now);
  14130. validity_checked = true;
  14131. }
  14132. return true;
  14133. });
  14134. auto res = cli.Get("/test");
  14135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14136. EXPECT_TRUE(validity_checked);
  14137. }
  14138. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14139. using namespace httplib::tls;
  14140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14141. ASSERT_TRUE(svr.is_valid());
  14142. svr.Get("/test", [](const Request &, Response &res) {
  14143. res.set_content("ok", "text/plain");
  14144. });
  14145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14146. auto se = detail::scope_exit([&] {
  14147. svr.stop();
  14148. t.join();
  14149. });
  14150. svr.wait_until_ready();
  14151. SSLClient cli(HOST, PORT);
  14152. cli.enable_server_certificate_verification(false);
  14153. cli.set_connection_timeout(30);
  14154. bool serial_checked = false;
  14155. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14156. if (ctx.cert) {
  14157. std::string serial = ctx.serial();
  14158. EXPECT_FALSE(serial.empty());
  14159. // Serial should be a hex string
  14160. for (char c : serial) {
  14161. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14162. (c >= 'a' && c <= 'f'));
  14163. }
  14164. serial_checked = true;
  14165. }
  14166. return true;
  14167. });
  14168. auto res = cli.Get("/test");
  14169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14170. EXPECT_TRUE(serial_checked);
  14171. }
  14172. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14173. // Test 1: Valid CA file - no error should be recorded
  14174. {
  14175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14176. CLIENT_CA_CERT_FILE);
  14177. ASSERT_TRUE(svr.is_valid());
  14178. // With valid setup, last_ssl_error should be 0
  14179. EXPECT_EQ(0, svr.ssl_last_error());
  14180. }
  14181. // Test 2: Invalid CA file content
  14182. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14183. {
  14184. // Create a temporary file with completely invalid content
  14185. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14186. {
  14187. std::ofstream ofs(temp_invalid_ca);
  14188. ofs << "This is not a certificate file at all\n";
  14189. ofs << "Just plain text content\n";
  14190. }
  14191. // Create server with invalid CA file
  14192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14193. // Clean up temporary file
  14194. std::remove(temp_invalid_ca);
  14195. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14196. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14197. // Note: SSL_CTX_load_verify_locations typically fails first,
  14198. // but our error handling code path is still exercised
  14199. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14200. }
  14201. }
  14202. TEST(VerifyCallbackTest, VerifyContextFields) {
  14203. using namespace httplib::tls;
  14204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14205. ASSERT_TRUE(svr.is_valid());
  14206. svr.Get("/test", [](const Request &, Response &res) {
  14207. res.set_content("ok", "text/plain");
  14208. });
  14209. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14210. auto se = detail::scope_exit([&] {
  14211. svr.stop();
  14212. t.join();
  14213. });
  14214. svr.wait_until_ready();
  14215. SSLClient cli(HOST, PORT);
  14216. cli.enable_server_certificate_verification(false);
  14217. cli.set_connection_timeout(30);
  14218. int callback_count = 0;
  14219. bool saw_leaf_cert = false;
  14220. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14221. if (ctx.cert) {
  14222. callback_count++;
  14223. // We should see at least one certificate (the leaf)
  14224. std::string cn = ctx.subject_cn();
  14225. if (!cn.empty()) { saw_leaf_cert = true; }
  14226. // Verify context fields are populated
  14227. EXPECT_NE(ctx.session, nullptr);
  14228. EXPECT_GE(ctx.depth, 0);
  14229. }
  14230. return true;
  14231. });
  14232. auto res = cli.Get("/test");
  14233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14234. EXPECT_GT(callback_count, 0);
  14235. EXPECT_TRUE(saw_leaf_cert);
  14236. }
  14237. // A verifier belongs to the client that set it, not to the thread that set it.
  14238. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14239. using namespace httplib::tls;
  14240. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14241. ASSERT_TRUE(svr.is_valid());
  14242. svr.Get("/test", [](const Request &, Response &res) {
  14243. res.set_content("ok", "text/plain");
  14244. });
  14245. auto port = svr.bind_to_any_port(HOST);
  14246. thread t([&]() { svr.listen_after_bind(); });
  14247. auto se = detail::scope_exit([&] {
  14248. svr.stop();
  14249. t.join();
  14250. });
  14251. svr.wait_until_ready();
  14252. auto rejecting_calls = 0;
  14253. SSLClient rejecting(HOST, port);
  14254. rejecting.enable_server_certificate_verification(false);
  14255. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14256. rejecting_calls++;
  14257. return false;
  14258. });
  14259. auto accepting_calls = 0;
  14260. SSLClient accepting(HOST, port);
  14261. accepting.enable_server_certificate_verification(false);
  14262. // Set on another thread than the requests below.
  14263. thread([&]() {
  14264. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14265. accepting_calls++;
  14266. return true;
  14267. });
  14268. }).join();
  14269. // Requested on another thread than the verifier was set on.
  14270. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14271. EXPECT_GT(rejecting_calls, 0);
  14272. auto res = accepting.Get("/test");
  14273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14274. EXPECT_GT(accepting_calls, 0);
  14275. }
  14276. // A verifier replaced while a handshake runs it lives until it returns.
  14277. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14278. using namespace httplib::tls;
  14279. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14280. ASSERT_TRUE(svr.is_valid());
  14281. svr.Get("/test", [](const Request &, Response &res) {
  14282. res.set_content("ok", "text/plain");
  14283. });
  14284. auto port = svr.bind_to_any_port(HOST);
  14285. thread t([&]() { svr.listen_after_bind(); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. });
  14290. svr.wait_until_ready();
  14291. SSLClient cli(HOST, port);
  14292. cli.enable_server_certificate_verification(false);
  14293. std::promise<void> entered;
  14294. std::promise<void> replaced;
  14295. auto replaced_future = replaced.get_future();
  14296. auto first_call = true;
  14297. // Long enough to live on the heap
  14298. std::string expected(64, 'v');
  14299. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14300. if (first_call) {
  14301. first_call = false;
  14302. entered.set_value();
  14303. replaced_future.wait();
  14304. }
  14305. return expected == std::string(64, 'v');
  14306. });
  14307. thread request([&]() {
  14308. auto res = cli.Get("/test");
  14309. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14310. });
  14311. entered.get_future().wait();
  14312. cli.set_server_certificate_verifier(
  14313. [](const VerifyContext &) { return true; });
  14314. replaced.set_value();
  14315. request.join();
  14316. }
  14317. // VerifyContext::session is the same handle the other tls:: functions take.
  14318. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14319. using namespace httplib::tls;
  14320. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14321. ASSERT_TRUE(svr.is_valid());
  14322. svr.Get("/test", [](const Request &, Response &res) {
  14323. res.set_content("ok", "text/plain");
  14324. });
  14325. auto port = svr.bind_to_any_port(HOST);
  14326. thread t([&]() { svr.listen_after_bind(); });
  14327. auto se = detail::scope_exit([&] {
  14328. svr.stop();
  14329. t.join();
  14330. });
  14331. svr.wait_until_ready();
  14332. SSLClient cli(HOST, port);
  14333. cli.enable_server_certificate_verification(false);
  14334. session_t verifier_session = nullptr;
  14335. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14336. verifier_session = ctx.session;
  14337. return true;
  14338. });
  14339. session_t session_verifier_session = nullptr;
  14340. cli.set_session_verifier([&](session_t session) {
  14341. session_verifier_session = session;
  14342. return SSLVerifierResponse::NoDecisionMade;
  14343. });
  14344. auto res = cli.Get("/test");
  14345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14346. EXPECT_NE(nullptr, verifier_session);
  14347. EXPECT_EQ(session_verifier_session, verifier_session);
  14348. }
  14349. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14350. using httplib::tls::TlsError;
  14351. // Test that verify_error_to_string returns empty for success
  14352. std::string success_str = TlsError::verify_error_to_string(0);
  14353. EXPECT_TRUE(success_str.empty());
  14354. // Test that verify_error_to_string returns non-empty for error codes
  14355. // Using a common error code (certificate expired)
  14356. std::string error_str =
  14357. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14358. EXPECT_FALSE(error_str.empty());
  14359. }
  14360. TEST(SessionVerifierTest, CertificateAccepted) {
  14361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14362. ASSERT_TRUE(svr.is_valid());
  14363. svr.Get("/test", [](const Request &, Response &res) {
  14364. res.set_content("ok", "text/plain");
  14365. });
  14366. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14367. auto se = detail::scope_exit([&] {
  14368. svr.stop();
  14369. t.join();
  14370. });
  14371. svr.wait_until_ready();
  14372. SSLClient cli(HOST, PORT);
  14373. cli.enable_server_certificate_verification(false);
  14374. cli.set_connection_timeout(30);
  14375. bool callback_called = false;
  14376. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14377. EXPECT_NE(session, nullptr);
  14378. callback_called = true;
  14379. return SSLVerifierResponse::CertificateAccepted;
  14380. });
  14381. auto res = cli.Get("/test");
  14382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14383. EXPECT_EQ(200, res->status);
  14384. EXPECT_TRUE(callback_called);
  14385. }
  14386. TEST(SessionVerifierTest, CertificateRejected) {
  14387. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14388. ASSERT_TRUE(svr.is_valid());
  14389. svr.Get("/test", [](const Request &, Response &res) {
  14390. res.set_content("ok", "text/plain");
  14391. });
  14392. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14393. auto se = detail::scope_exit([&] {
  14394. svr.stop();
  14395. t.join();
  14396. });
  14397. svr.wait_until_ready();
  14398. SSLClient cli(HOST, PORT);
  14399. cli.enable_server_certificate_verification(false);
  14400. cli.set_connection_timeout(30);
  14401. bool callback_called = false;
  14402. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14403. EXPECT_NE(session, nullptr);
  14404. callback_called = true;
  14405. return SSLVerifierResponse::CertificateRejected;
  14406. });
  14407. auto res = cli.Get("/test");
  14408. EXPECT_FALSE(res);
  14409. EXPECT_TRUE(callback_called);
  14410. }
  14411. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14413. ASSERT_TRUE(svr.is_valid());
  14414. svr.Get("/test", [](const Request &, Response &res) {
  14415. res.set_content("ok", "text/plain");
  14416. });
  14417. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14418. auto se = detail::scope_exit([&] {
  14419. svr.stop();
  14420. t.join();
  14421. });
  14422. svr.wait_until_ready();
  14423. // NoDecisionMade with verification disabled should succeed (no default check)
  14424. SSLClient cli(HOST, PORT);
  14425. cli.enable_server_certificate_verification(false);
  14426. cli.set_connection_timeout(30);
  14427. bool callback_called = false;
  14428. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14429. EXPECT_NE(session, nullptr);
  14430. callback_called = true;
  14431. return SSLVerifierResponse::NoDecisionMade;
  14432. });
  14433. auto res = cli.Get("/test");
  14434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14435. EXPECT_EQ(200, res->status);
  14436. EXPECT_TRUE(callback_called);
  14437. }
  14438. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14440. ASSERT_TRUE(svr.is_valid());
  14441. svr.Get("/test", [](const Request &, Response &res) {
  14442. res.set_content("ok", "text/plain");
  14443. });
  14444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14445. auto se = detail::scope_exit([&] {
  14446. svr.stop();
  14447. t.join();
  14448. });
  14449. svr.wait_until_ready();
  14450. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14451. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14452. // so we only check that the request fails, not whether the callback was
  14453. // called.
  14454. SSLClient cli(HOST, PORT);
  14455. cli.enable_server_certificate_verification(true);
  14456. cli.set_connection_timeout(30);
  14457. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14458. EXPECT_NE(session, nullptr);
  14459. return SSLVerifierResponse::NoDecisionMade;
  14460. });
  14461. auto res = cli.Get("/test");
  14462. EXPECT_FALSE(res);
  14463. }
  14464. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14465. // Test SSL server using PemMemory constructor with client CA certificates
  14466. // Read PEM files
  14467. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14468. read_file(SERVER_CERT_FILE, server_cert_pem);
  14469. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14470. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14471. // Create SSLServer with PemMemory constructor including client CA
  14472. SSLServer::PemMemory server_pem = {
  14473. server_cert_pem.c_str(),
  14474. server_cert_pem.size(),
  14475. server_key_pem.c_str(),
  14476. server_key_pem.size(),
  14477. client_ca_pem.c_str(),
  14478. client_ca_pem.size(),
  14479. nullptr // no password for server key
  14480. };
  14481. SSLServer svr(server_pem);
  14482. ASSERT_TRUE(svr.is_valid());
  14483. // No SSL error should be recorded for valid setup
  14484. EXPECT_EQ(0, svr.ssl_last_error());
  14485. // Set up server endpoints
  14486. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14487. res.set_content("ok", "text/plain");
  14488. });
  14489. // Start server in a thread
  14490. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14491. svr.wait_until_ready();
  14492. // Connect with client certificate (using constructor with paths)
  14493. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14494. cli.enable_server_certificate_verification(false);
  14495. auto res = cli.Get("/test-pem-ca");
  14496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14497. EXPECT_EQ(200, res->status);
  14498. EXPECT_EQ("ok", res->body);
  14499. svr.stop();
  14500. server_thread.join();
  14501. }
  14502. #endif
  14503. #ifdef _WIN32
  14504. TEST(CleanupTest, WSACleanup) {
  14505. int ret = WSACleanup();
  14506. ASSERT_EQ(0, ret);
  14507. }
  14508. #endif
  14509. #ifndef CPPHTTPLIB_SSL_ENABLED
  14510. TEST(NoSSLSupport, SimpleInterface) {
  14511. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14512. }
  14513. #endif
  14514. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14515. TEST(InvalidScheme, SimpleInterface) {
  14516. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14517. }
  14518. #endif
  14519. TEST(NoScheme, SimpleInterface) {
  14520. Client cli("yahoo.com:80");
  14521. ASSERT_TRUE(cli.is_valid());
  14522. }
  14523. TEST(SendAPI, SimpleInterface_Online) {
  14524. Client cli("http://yahoo.com");
  14525. Request req;
  14526. req.method = "GET";
  14527. req.path = "/";
  14528. auto res = cli.send(req);
  14529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14530. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14531. }
  14532. TEST(SendAPI, WithParamsInRequest) {
  14533. Server svr;
  14534. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14535. EXPECT_TRUE(req.has_param("test"));
  14536. EXPECT_EQ("test_value", req.get_param_value("test"));
  14537. });
  14538. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. ASSERT_FALSE(svr.is_running());
  14543. });
  14544. svr.wait_until_ready();
  14545. Client cli(HOST, PORT);
  14546. {
  14547. Request req;
  14548. req.method = "GET";
  14549. req.path = "/";
  14550. req.params.emplace("test", "test_value");
  14551. auto res = cli.send(req);
  14552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14553. }
  14554. {
  14555. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14557. }
  14558. }
  14559. TEST(ClientImplMethods, GetSocketTest) {
  14560. httplib::Server svr;
  14561. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14562. res.status = StatusCode::OK_200;
  14563. });
  14564. auto port = svr.bind_to_any_port("127.0.0.1");
  14565. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14566. auto se = detail::scope_exit([&] {
  14567. svr.stop();
  14568. thread.join();
  14569. ASSERT_FALSE(svr.is_running());
  14570. });
  14571. svr.wait_until_ready();
  14572. {
  14573. httplib::Client cli("127.0.0.1", port);
  14574. cli.set_keep_alive(true);
  14575. // Use the behavior of cpp-httplib of opening the connection
  14576. // only when the first request happens. If that changes,
  14577. // this test would be obsolete.
  14578. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14579. // This also implicitly tests the server. But other tests would fail much
  14580. // earlier than this one to be considered.
  14581. auto res = cli.Get("/");
  14582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14583. EXPECT_EQ(StatusCode::OK_200, res->status);
  14584. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14585. }
  14586. }
  14587. #ifdef CPPHTTPLIB_SSL_ENABLED
  14588. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14589. Client cli("http://yahoo.com");
  14590. auto res = cli.Get("/");
  14591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14592. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14593. cli.set_follow_location(true);
  14594. res = cli.Get("/");
  14595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14596. EXPECT_EQ(StatusCode::OK_200, res->status);
  14597. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14598. }
  14599. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14600. Client cli("https://yahoo.com");
  14601. auto res = cli.Get("/");
  14602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14603. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14604. cli.set_follow_location(true);
  14605. res = cli.Get("/");
  14606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14607. EXPECT_EQ(StatusCode::OK_200, res->status);
  14608. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14609. }
  14610. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14611. Client cli("https://yahoo.com");
  14612. auto res = cli.Get("/");
  14613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14614. ASSERT_FALSE(!res);
  14615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14616. ASSERT_FALSE(res == nullptr);
  14617. ASSERT_TRUE(res != nullptr);
  14618. EXPECT_EQ(Error::Success, res.error());
  14619. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14620. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14621. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14622. cli.set_follow_location(true);
  14623. res = cli.Get("/");
  14624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14625. EXPECT_EQ(Error::Success, res.error());
  14626. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14627. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14628. EXPECT_EQ(StatusCode::OK_200, res->status);
  14629. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14630. }
  14631. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14632. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14633. Client cli("https://cdnjs.cloudflare.com");
  14634. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14635. Headers{{"Accept-Encoding", "br"}});
  14636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14637. EXPECT_EQ(StatusCode::OK_200, res->status);
  14638. EXPECT_EQ(287630U, res->body.size());
  14639. EXPECT_EQ("application/javascript; charset=utf-8",
  14640. res->get_header_value("Content-Type"));
  14641. }
  14642. #endif
  14643. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14644. #undef REDIR_HOST // Silence compiler warning
  14645. #define REDIR_HOST "https://httpbingo.org"
  14646. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14647. Client cli(REDIR_HOST);
  14648. cli.set_follow_location(true);
  14649. auto res =
  14650. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14652. EXPECT_EQ(StatusCode::OK_200, res->status);
  14653. }
  14654. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14655. Client cli(REDIR_HOST);
  14656. cli.set_follow_location(true);
  14657. Params params;
  14658. params.emplace("url", "http://example.com");
  14659. params.emplace("status_code", "302");
  14660. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14662. EXPECT_EQ(StatusCode::OK_200, res->status);
  14663. }
  14664. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14665. Client cli(REDIR_HOST);
  14666. cli.set_follow_location(true);
  14667. Params params;
  14668. params.emplace("url", "http://example.com");
  14669. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14671. EXPECT_EQ(StatusCode::OK_200, res->status);
  14672. }
  14673. TEST(HttpToHttpsRedirectTest, CertFile) {
  14674. auto ssl_port = PORT + 1;
  14675. Server svr;
  14676. ASSERT_TRUE(svr.is_valid());
  14677. svr.Get("/index", [&](const Request &, Response &res) {
  14678. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14679. "/index");
  14680. svr.stop();
  14681. });
  14682. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14683. ASSERT_TRUE(ssl_svr.is_valid());
  14684. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14685. res.set_content("test", "text/plain");
  14686. ssl_svr.stop();
  14687. });
  14688. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14689. thread t2 =
  14690. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14691. auto se = detail::scope_exit([&] {
  14692. t2.join();
  14693. t.join();
  14694. ASSERT_FALSE(svr.is_running());
  14695. });
  14696. svr.wait_until_ready();
  14697. ssl_svr.wait_until_ready();
  14698. Client cli("127.0.0.1", PORT);
  14699. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14700. cli.enable_server_certificate_verification(true);
  14701. cli.set_follow_location(true);
  14702. cli.set_connection_timeout(30);
  14703. auto res = cli.Get("/index");
  14704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14705. ASSERT_EQ(StatusCode::OK_200, res->status);
  14706. }
  14707. TEST(SSLClientRedirectTest, CertFile) {
  14708. auto ssl_port = PORT + 1;
  14709. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14710. ASSERT_TRUE(ssl_svr1.is_valid());
  14711. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14712. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14713. "/index");
  14714. ssl_svr1.stop();
  14715. });
  14716. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14717. ASSERT_TRUE(ssl_svr2.is_valid());
  14718. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14719. res.set_content("test", "text/plain");
  14720. ssl_svr2.stop();
  14721. });
  14722. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14723. thread t2 =
  14724. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14725. auto se = detail::scope_exit([&] {
  14726. t2.join();
  14727. t.join();
  14728. ASSERT_FALSE(ssl_svr1.is_running());
  14729. });
  14730. ssl_svr1.wait_until_ready();
  14731. ssl_svr2.wait_until_ready();
  14732. SSLClient cli("127.0.0.1", PORT);
  14733. std::string cert;
  14734. read_file(SERVER_CERT2_FILE, cert);
  14735. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14736. cli.enable_server_certificate_verification(true);
  14737. cli.set_follow_location(true);
  14738. cli.set_connection_timeout(30);
  14739. auto res = cli.Get("/index");
  14740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14741. ASSERT_EQ(StatusCode::OK_200, res->status);
  14742. }
  14743. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14744. // another port, so the client follows it with a new client.
  14745. static Result GetThroughTlsRedirectToDifferentPort(
  14746. const std::function<void(SSLClient &)> &setup,
  14747. const char *target_cert = SERVER_CERT2_FILE,
  14748. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14749. auto ssl_port = PORT + 1;
  14750. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14751. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14752. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14753. "/index");
  14754. });
  14755. SSLServer ssl_svr2(target_cert, target_key);
  14756. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14757. res.set_content("test", "text/plain");
  14758. });
  14759. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14760. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14761. auto se = detail::scope_exit([&] {
  14762. ssl_svr2.stop();
  14763. ssl_svr1.stop();
  14764. t2.join();
  14765. t.join();
  14766. });
  14767. ssl_svr1.wait_until_ready();
  14768. ssl_svr2.wait_until_ready();
  14769. SSLClient cli("127.0.0.1", PORT);
  14770. cli.set_follow_location(true);
  14771. cli.set_connection_timeout(30);
  14772. setup(cli);
  14773. return cli.Get("/index");
  14774. }
  14775. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14776. auto calls = 0;
  14777. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14778. cli.enable_server_certificate_verification(false);
  14779. // Accept the first server only.
  14780. cli.set_session_verifier([&](tls::session_t) {
  14781. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14782. : SSLVerifierResponse::CertificateRejected;
  14783. });
  14784. });
  14785. EXPECT_FALSE(res);
  14786. EXPECT_EQ(2, calls);
  14787. }
  14788. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14789. std::string pinned;
  14790. auto res = GetThroughTlsRedirectToDifferentPort(
  14791. [&](SSLClient &cli) {
  14792. cli.enable_server_certificate_verification(false);
  14793. // Pin the first certificate seen.
  14794. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14795. if (pinned.empty()) { pinned = ctx.serial(); }
  14796. return ctx.serial() == pinned;
  14797. });
  14798. },
  14799. // A certificate other than the first server's.
  14800. SERVER_CERT_FILE);
  14801. EXPECT_FALSE(res);
  14802. EXPECT_FALSE(pinned.empty());
  14803. }
  14804. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14805. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14806. std::string cert;
  14807. read_file(SERVER_CERT2_FILE, cert);
  14808. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14809. });
  14810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14811. EXPECT_EQ(StatusCode::OK_200, res->status);
  14812. }
  14813. // The target's certificate is signed by the root CA, which the first server's
  14814. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14815. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14816. auto res = GetThroughTlsRedirectToDifferentPort(
  14817. [](SSLClient &cli) {
  14818. std::string root_ca, cert;
  14819. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14820. read_file(SERVER_CERT2_FILE, cert);
  14821. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14822. cli.load_ca_cert_store(cert.data(), cert.size());
  14823. cli.enable_server_hostname_verification(false);
  14824. },
  14825. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14827. EXPECT_EQ(StatusCode::OK_200, res->status);
  14828. }
  14829. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14830. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14831. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14832. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14833. auto res = GetThroughTlsRedirectToDifferentPort(
  14834. [](SSLClient &cli) {
  14835. std::string root_ca, cert;
  14836. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14837. read_file(SERVER_CERT2_FILE, cert);
  14838. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14839. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14840. cli.enable_server_hostname_verification(false);
  14841. },
  14842. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14843. ASSERT_FALSE(res);
  14844. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14845. }
  14846. #endif
  14847. #endif
  14848. #ifdef CPPHTTPLIB_SSL_ENABLED
  14849. // Test that set_ca_cert_store() skips system certs (consistent with
  14850. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14851. // should be trusted - system certs should NOT be loaded.
  14852. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14853. // Load a specific cert that is NOT a system CA cert
  14854. std::string cert;
  14855. read_file(SERVER_CERT2_FILE, cert);
  14856. SSLClient cli("google.com");
  14857. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14858. cli.enable_server_certificate_verification(true);
  14859. // This should FAIL because:
  14860. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14861. // 2. System certs should NOT be loaded when custom store is set
  14862. // If system certs WERE loaded, this would succeed
  14863. auto res = cli.Get("/");
  14864. ASSERT_FALSE(res);
  14865. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14866. }
  14867. // Same as above, but through the native store handle path. Regression test:
  14868. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14869. // merged system certs into the user-provided store.
  14870. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14871. std::string cert;
  14872. read_file(SERVER_CERT2_FILE, cert);
  14873. SSLClient cli("google.com");
  14874. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14875. cli.enable_server_certificate_verification(true);
  14876. auto res = cli.Get("/");
  14877. ASSERT_FALSE(res);
  14878. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14879. }
  14880. // A custom store set via the native handle must still verify a server whose
  14881. // cert it does contain.
  14882. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14883. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14884. ASSERT_TRUE(svr.is_valid());
  14885. svr.Get("/test", [&](const Request &, Response &res) {
  14886. res.set_content("test", "text/plain");
  14887. });
  14888. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14889. auto se = detail::scope_exit([&] {
  14890. svr.stop();
  14891. t.join();
  14892. ASSERT_FALSE(svr.is_running());
  14893. });
  14894. svr.wait_until_ready();
  14895. SSLClient cli("127.0.0.1", PORT);
  14896. std::string cert;
  14897. read_file(SERVER_CERT2_FILE, cert);
  14898. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14899. cli.enable_server_certificate_verification(true);
  14900. cli.set_connection_timeout(30);
  14901. auto res = cli.Get("/test");
  14902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14903. ASSERT_EQ(StatusCode::OK_200, res->status);
  14904. }
  14905. // CA certs loaded through the universal Client must be transferred to the
  14906. // client created internally for following an HTTPS redirect. Regression test:
  14907. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14908. // the CA data for redirect transfer.
  14909. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14910. auto ssl_port = PORT + 1;
  14911. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14912. ASSERT_TRUE(ssl_svr1.is_valid());
  14913. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14914. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14915. "/index");
  14916. });
  14917. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14918. ASSERT_TRUE(ssl_svr2.is_valid());
  14919. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14920. res.set_content("test", "text/plain");
  14921. });
  14922. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14923. thread t2 =
  14924. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14925. auto se = detail::scope_exit([&] {
  14926. ssl_svr2.stop();
  14927. ssl_svr1.stop();
  14928. t2.join();
  14929. t.join();
  14930. ASSERT_FALSE(ssl_svr1.is_running());
  14931. });
  14932. ssl_svr1.wait_until_ready();
  14933. ssl_svr2.wait_until_ready();
  14934. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14935. std::string cert;
  14936. read_file(SERVER_CERT2_FILE, cert);
  14937. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14938. cli.enable_server_certificate_verification(true);
  14939. cli.set_follow_location(true);
  14940. cli.set_connection_timeout(30);
  14941. auto res = cli.Get("/index");
  14942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14943. ASSERT_EQ(StatusCode::OK_200, res->status);
  14944. }
  14945. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14946. // so a host signed by a system CA verifies even though a custom CA is set
  14947. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14948. std::string cert;
  14949. read_file(SERVER_CERT2_FILE, cert);
  14950. SSLClient cli("google.com");
  14951. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14952. cli.enable_system_ca(true);
  14953. cli.enable_server_certificate_verification(true);
  14954. auto res = cli.Get("/");
  14955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14956. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14957. }
  14958. // The custom CA remains effective when combined with the system CA
  14959. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14960. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14961. ASSERT_TRUE(svr.is_valid());
  14962. svr.Get("/test", [&](const Request &, Response &res) {
  14963. res.set_content("test", "text/plain");
  14964. });
  14965. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14966. auto se = detail::scope_exit([&] {
  14967. svr.stop();
  14968. t.join();
  14969. ASSERT_FALSE(svr.is_running());
  14970. });
  14971. svr.wait_until_ready();
  14972. SSLClient cli("127.0.0.1", PORT);
  14973. std::string cert;
  14974. read_file(SERVER_CERT2_FILE, cert);
  14975. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14976. cli.enable_system_ca(true);
  14977. cli.enable_server_certificate_verification(true);
  14978. cli.set_connection_timeout(30);
  14979. auto res = cli.Get("/test");
  14980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14981. ASSERT_EQ(StatusCode::OK_200, res->status);
  14982. }
  14983. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14984. // skip chain verification entirely (only the certificate identity was
  14985. // checked), so a server presenting an untrusted certificate with a matching
  14986. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14987. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14988. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14989. ASSERT_TRUE(svr.is_valid());
  14990. svr.Get("/test", [&](const Request &, Response &res) {
  14991. res.set_content("test", "text/plain");
  14992. });
  14993. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14994. auto se = detail::scope_exit([&] {
  14995. svr.stop();
  14996. t.join();
  14997. ASSERT_FALSE(svr.is_running());
  14998. });
  14999. svr.wait_until_ready();
  15000. SSLClient cli("127.0.0.1", PORT);
  15001. std::string cert;
  15002. // A trusted CA that did not sign the server certificate. The server cert
  15003. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15004. // this connection.
  15005. read_file(CLIENT_CA_CERT_FILE, cert);
  15006. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15007. cli.enable_server_certificate_verification(true);
  15008. cli.set_connection_timeout(30);
  15009. auto res = cli.Get("/test");
  15010. ASSERT_FALSE(res);
  15011. }
  15012. // enable_system_ca(false) prevents system CA loading entirely
  15013. TEST(SSLClientTest, DisableSystemCa_Online) {
  15014. SSLClient cli("google.com");
  15015. cli.enable_system_ca(false);
  15016. cli.enable_server_certificate_verification(true);
  15017. auto res = cli.Get("/");
  15018. ASSERT_FALSE(res);
  15019. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15020. // itself when the CA chain is empty
  15021. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15022. res.error() == Error::SSLConnection);
  15023. }
  15024. // The universal Client forwards enable_system_ca()
  15025. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15026. std::string cert;
  15027. read_file(SERVER_CERT2_FILE, cert);
  15028. Client cli("https://google.com");
  15029. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15030. cli.enable_system_ca(true);
  15031. cli.enable_server_certificate_verification(true);
  15032. auto res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15035. }
  15036. // The system CA policy must carry over to the client created internally for
  15037. // following a cross-host HTTPS redirect
  15038. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15039. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15040. ASSERT_TRUE(svr.is_valid());
  15041. svr.Get("/index", [&](const Request &, Response &res) {
  15042. res.set_redirect("https://www.google.com/");
  15043. });
  15044. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15045. auto se = detail::scope_exit([&] {
  15046. svr.stop();
  15047. t.join();
  15048. ASSERT_FALSE(svr.is_running());
  15049. });
  15050. svr.wait_until_ready();
  15051. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15052. std::string cert;
  15053. read_file(SERVER_CERT2_FILE, cert);
  15054. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15055. cli.enable_system_ca(true);
  15056. cli.enable_server_certificate_verification(true);
  15057. cli.set_follow_location(true);
  15058. cli.set_connection_timeout(30);
  15059. // Receiving any response proves the redirect client completed the TLS
  15060. // handshake with a system-CA-signed host
  15061. auto res = cli.Get("/index");
  15062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15063. }
  15064. TEST(MultipartFormDataTest, LargeData) {
  15065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15066. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15067. const ContentReader &content_reader) {
  15068. if (req.is_multipart_form_data()) {
  15069. std::vector<FormData> items;
  15070. content_reader(
  15071. [&](const FormData &file) {
  15072. items.push_back(file);
  15073. return true;
  15074. },
  15075. [&](const char *data, size_t data_length) {
  15076. items.back().content.append(data, data_length);
  15077. return true;
  15078. });
  15079. EXPECT_TRUE(std::string(items[0].name) == "document");
  15080. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15081. EXPECT_TRUE(items[0].filename == "2MB_data");
  15082. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15083. EXPECT_TRUE(items[1].name == "hello");
  15084. EXPECT_TRUE(items[1].content == "world");
  15085. EXPECT_TRUE(items[1].filename == "");
  15086. EXPECT_TRUE(items[1].content_type == "");
  15087. } else {
  15088. std::string body;
  15089. content_reader([&](const char *data, size_t data_length) {
  15090. body.append(data, data_length);
  15091. return true;
  15092. });
  15093. }
  15094. });
  15095. auto port = svr.bind_to_any_port(HOST);
  15096. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15097. auto se = detail::scope_exit([&] {
  15098. svr.stop();
  15099. t.join();
  15100. ASSERT_FALSE(svr.is_running());
  15101. });
  15102. svr.wait_until_ready();
  15103. {
  15104. std::string data(1024 * 1024 * 2, '.');
  15105. std::stringstream buffer;
  15106. buffer << data;
  15107. SSLClient cli(HOST, port);
  15108. cli.enable_server_certificate_verification(false);
  15109. UploadFormDataItems items{
  15110. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15111. {"hello", "world", "", ""},
  15112. };
  15113. auto res = cli.Post("/post", items);
  15114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15115. ASSERT_EQ(StatusCode::OK_200, res->status);
  15116. }
  15117. }
  15118. TEST(MultipartFormDataTest, DataProviderItems) {
  15119. std::random_device seed_gen;
  15120. std::mt19937 random(seed_gen());
  15121. std::string rand1;
  15122. rand1.resize(1000);
  15123. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15124. std::string rand2;
  15125. rand2.resize(3000);
  15126. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15128. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15129. const ContentReader &content_reader) {
  15130. ASSERT_FALSE(req.is_multipart_form_data());
  15131. std::string body;
  15132. content_reader([&](const char *data, size_t data_length) {
  15133. body.append(data, data_length);
  15134. return true;
  15135. });
  15136. EXPECT_EQ(body, "");
  15137. });
  15138. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15139. const ContentReader &content_reader) {
  15140. ASSERT_TRUE(req.is_multipart_form_data());
  15141. std::vector<FormData> items;
  15142. content_reader(
  15143. [&](const FormData &file) {
  15144. items.push_back(file);
  15145. return true;
  15146. },
  15147. [&](const char *data, size_t data_length) {
  15148. items.back().content.append(data, data_length);
  15149. return true;
  15150. });
  15151. ASSERT_TRUE(items.size() == 2);
  15152. EXPECT_EQ(std::string(items[0].name), "name1");
  15153. EXPECT_EQ(items[0].content, "Testing123");
  15154. EXPECT_EQ(items[0].filename, "filename1");
  15155. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15156. EXPECT_EQ(items[1].name, "name2");
  15157. EXPECT_EQ(items[1].content, "Testing456");
  15158. EXPECT_EQ(items[1].filename, "");
  15159. EXPECT_EQ(items[1].content_type, "");
  15160. });
  15161. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15162. const ContentReader &content_reader) {
  15163. ASSERT_TRUE(req.is_multipart_form_data());
  15164. std::vector<FormData> items;
  15165. content_reader(
  15166. [&](const FormData &file) {
  15167. items.push_back(file);
  15168. return true;
  15169. },
  15170. [&](const char *data, size_t data_length) {
  15171. items.back().content.append(data, data_length);
  15172. return true;
  15173. });
  15174. ASSERT_TRUE(items.size() == 2);
  15175. EXPECT_EQ(items[0].name, "name3");
  15176. EXPECT_EQ(items[0].content, rand1);
  15177. EXPECT_EQ(items[0].filename, "filename3");
  15178. EXPECT_EQ(items[0].content_type, "");
  15179. EXPECT_EQ(items[1].name, "name4");
  15180. EXPECT_EQ(items[1].content, rand2);
  15181. EXPECT_EQ(items[1].filename, "filename4");
  15182. EXPECT_EQ(items[1].content_type, "");
  15183. });
  15184. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15185. const ContentReader &content_reader) {
  15186. ASSERT_TRUE(req.is_multipart_form_data());
  15187. std::vector<FormData> items;
  15188. content_reader(
  15189. [&](const FormData &file) {
  15190. items.push_back(file);
  15191. return true;
  15192. },
  15193. [&](const char *data, size_t data_length) {
  15194. items.back().content.append(data, data_length);
  15195. return true;
  15196. });
  15197. ASSERT_TRUE(items.size() == 4);
  15198. EXPECT_EQ(std::string(items[0].name), "name1");
  15199. EXPECT_EQ(items[0].content, "Testing123");
  15200. EXPECT_EQ(items[0].filename, "filename1");
  15201. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15202. EXPECT_EQ(items[1].name, "name2");
  15203. EXPECT_EQ(items[1].content, "Testing456");
  15204. EXPECT_EQ(items[1].filename, "");
  15205. EXPECT_EQ(items[1].content_type, "");
  15206. EXPECT_EQ(items[2].name, "name3");
  15207. EXPECT_EQ(items[2].content, rand1);
  15208. EXPECT_EQ(items[2].filename, "filename3");
  15209. EXPECT_EQ(items[2].content_type, "");
  15210. EXPECT_EQ(items[3].name, "name4");
  15211. EXPECT_EQ(items[3].content, rand2);
  15212. EXPECT_EQ(items[3].filename, "filename4");
  15213. EXPECT_EQ(items[3].content_type, "");
  15214. });
  15215. auto port = svr.bind_to_any_port("localhost");
  15216. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15217. auto se = detail::scope_exit([&] {
  15218. svr.stop();
  15219. t.join();
  15220. ASSERT_FALSE(svr.is_running());
  15221. });
  15222. svr.wait_until_ready();
  15223. {
  15224. SSLClient cli("localhost", port);
  15225. cli.enable_server_certificate_verification(false);
  15226. UploadFormDataItems items{
  15227. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15228. {"name2", "Testing456", "", ""}, // not a file
  15229. };
  15230. {
  15231. auto res = cli.Post("/post-none", {}, {}, {});
  15232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15233. ASSERT_EQ(StatusCode::OK_200, res->status);
  15234. }
  15235. FormDataProviderItems providers;
  15236. {
  15237. auto res =
  15238. cli.Post("/post-items", {}, items, providers); // empty providers
  15239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15240. ASSERT_EQ(StatusCode::OK_200, res->status);
  15241. }
  15242. providers.push_back({"name3",
  15243. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15244. // test the offset is given correctly at each step
  15245. if (!offset)
  15246. sink.os.write(rand1.data(), 30);
  15247. else if (offset == 30)
  15248. sink.os.write(rand1.data() + 30, 300);
  15249. else if (offset == 330)
  15250. sink.os.write(rand1.data() + 330, 670);
  15251. else if (offset == rand1.size())
  15252. sink.done();
  15253. return true;
  15254. },
  15255. "filename3",
  15256. {}});
  15257. providers.push_back({"name4",
  15258. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15259. // test the offset is given correctly at each step
  15260. if (!offset)
  15261. sink.os.write(rand2.data(), 2000);
  15262. else if (offset == 2000)
  15263. sink.os.write(rand2.data() + 2000, 1);
  15264. else if (offset == 2001)
  15265. sink.os.write(rand2.data() + 2001, 999);
  15266. else if (offset == rand2.size())
  15267. sink.done();
  15268. return true;
  15269. },
  15270. "filename4",
  15271. {}});
  15272. {
  15273. auto res = cli.Post("/post-providers", {}, {}, providers);
  15274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15275. ASSERT_EQ(StatusCode::OK_200, res->status);
  15276. }
  15277. {
  15278. auto res = cli.Post("/post-both", {}, items, providers);
  15279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15280. ASSERT_EQ(StatusCode::OK_200, res->status);
  15281. }
  15282. }
  15283. }
  15284. TEST(MultipartFormDataTest, BadHeader) {
  15285. Server svr;
  15286. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15287. res.set_content("ok", "text/plain");
  15288. });
  15289. thread t = thread([&] { svr.listen(HOST, PORT); });
  15290. auto se = detail::scope_exit([&] {
  15291. svr.stop();
  15292. t.join();
  15293. ASSERT_FALSE(svr.is_running());
  15294. });
  15295. svr.wait_until_ready();
  15296. const std::string body =
  15297. "This is the preamble. It is to be ignored, though it\r\n"
  15298. "is a handy place for composition agents to include an\r\n"
  15299. "explanatory note to non-MIME conformant readers.\r\n"
  15300. "\r\n"
  15301. "\r\n"
  15302. "--simple boundary\r\n"
  15303. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15304. ": BAD...\r\n"
  15305. "\r\n"
  15306. "value1\r\n"
  15307. "--simple boundary\r\n"
  15308. "Content-Disposition: form-data; name=\"field2\"; "
  15309. "filename=\"example.txt\"\r\n"
  15310. "\r\n"
  15311. "value2\r\n"
  15312. "--simple boundary--\r\n"
  15313. "This is the epilogue. It is also to be ignored.\r\n";
  15314. std::string content_type =
  15315. R"(multipart/form-data; boundary="simple boundary")";
  15316. Client cli(HOST, PORT);
  15317. auto res = cli.Post("/post", body, content_type.c_str());
  15318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15320. }
  15321. TEST(MultipartFormDataTest, WithPreamble) {
  15322. Server svr;
  15323. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15324. res.set_content("ok", "text/plain");
  15325. });
  15326. thread t = thread([&] { svr.listen(HOST, PORT); });
  15327. auto se = detail::scope_exit([&] {
  15328. svr.stop();
  15329. t.join();
  15330. ASSERT_FALSE(svr.is_running());
  15331. });
  15332. svr.wait_until_ready();
  15333. const std::string body =
  15334. "This is the preamble. It is to be ignored, though it\r\n"
  15335. "is a handy place for composition agents to include an\r\n"
  15336. "explanatory note to non-MIME conformant readers.\r\n"
  15337. "\r\n"
  15338. "\r\n"
  15339. "--simple boundary\r\n"
  15340. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15341. "\r\n"
  15342. "value1\r\n"
  15343. "--simple boundary\r\n"
  15344. "Content-Disposition: form-data; name=\"field2\"; "
  15345. "filename=\"example.txt\"\r\n"
  15346. "\r\n"
  15347. "value2\r\n"
  15348. "--simple boundary--\r\n"
  15349. "This is the epilogue. It is also to be ignored.\r\n";
  15350. std::string content_type =
  15351. R"(multipart/form-data; boundary="simple boundary")";
  15352. Client cli(HOST, PORT);
  15353. auto res = cli.Post("/post", body, content_type.c_str());
  15354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15355. EXPECT_EQ(StatusCode::OK_200, res->status);
  15356. }
  15357. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15359. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15360. const ContentReader &content_reader) {
  15361. if (req.is_multipart_form_data()) {
  15362. std::vector<FormData> items;
  15363. content_reader(
  15364. [&](const FormData &file) {
  15365. items.push_back(file);
  15366. return true;
  15367. },
  15368. [&](const char *data, size_t data_length) {
  15369. items.back().content.append(data, data_length);
  15370. return true;
  15371. });
  15372. EXPECT_TRUE(std::string(items[0].name) == "document");
  15373. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15374. EXPECT_TRUE(items[0].filename == "2MB_data");
  15375. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15376. EXPECT_TRUE(items[1].name == "hello");
  15377. EXPECT_TRUE(items[1].content == "world");
  15378. EXPECT_TRUE(items[1].filename == "");
  15379. EXPECT_TRUE(items[1].content_type == "");
  15380. } else {
  15381. std::string body;
  15382. content_reader([&](const char *data, size_t data_length) {
  15383. body.append(data, data_length);
  15384. return true;
  15385. });
  15386. }
  15387. });
  15388. auto port = svr.bind_to_any_port("localhost");
  15389. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15390. auto se = detail::scope_exit([&] {
  15391. svr.stop();
  15392. t.join();
  15393. ASSERT_FALSE(svr.is_running());
  15394. });
  15395. svr.wait_until_ready();
  15396. {
  15397. std::string data(1024 * 1024 * 2, '.');
  15398. std::stringstream buffer;
  15399. buffer << data;
  15400. SSLClient cli("localhost", port);
  15401. cli.enable_server_certificate_verification(false);
  15402. UploadFormDataItems items{
  15403. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15404. {"hello", "world", "", ""},
  15405. };
  15406. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15408. ASSERT_EQ(StatusCode::OK_200, res->status);
  15409. }
  15410. }
  15411. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15412. std::string data(1024 * 1024 * 2, '&');
  15413. std::stringstream buffer;
  15414. buffer << data;
  15415. Client cli("https://localhost:8080");
  15416. UploadFormDataItems items{
  15417. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15418. {"hello", "world", "", ""},
  15419. };
  15420. for (const char &c : " \t\r\n") {
  15421. auto res =
  15422. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15423. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15424. ASSERT_FALSE(res);
  15425. }
  15426. }
  15427. TEST(MultipartFormDataTest, PutFormData) {
  15428. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15429. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15430. const ContentReader &content_reader) {
  15431. if (req.is_multipart_form_data()) {
  15432. std::vector<FormData> items;
  15433. content_reader(
  15434. [&](const FormData &file) {
  15435. items.push_back(file);
  15436. return true;
  15437. },
  15438. [&](const char *data, size_t data_length) {
  15439. items.back().content.append(data, data_length);
  15440. return true;
  15441. });
  15442. EXPECT_TRUE(std::string(items[0].name) == "document");
  15443. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15444. EXPECT_TRUE(items[0].filename == "2MB_data");
  15445. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15446. EXPECT_TRUE(items[1].name == "hello");
  15447. EXPECT_TRUE(items[1].content == "world");
  15448. EXPECT_TRUE(items[1].filename == "");
  15449. EXPECT_TRUE(items[1].content_type == "");
  15450. } else {
  15451. std::string body;
  15452. content_reader([&](const char *data, size_t data_length) {
  15453. body.append(data, data_length);
  15454. return true;
  15455. });
  15456. }
  15457. });
  15458. auto port = svr.bind_to_any_port("localhost");
  15459. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15460. auto se = detail::scope_exit([&] {
  15461. svr.stop();
  15462. t.join();
  15463. ASSERT_FALSE(svr.is_running());
  15464. });
  15465. svr.wait_until_ready();
  15466. {
  15467. std::string data(1024 * 1024 * 2, '&');
  15468. std::stringstream buffer;
  15469. buffer << data;
  15470. SSLClient cli("localhost", port);
  15471. cli.enable_server_certificate_verification(false);
  15472. UploadFormDataItems items{
  15473. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15474. {"hello", "world", "", ""},
  15475. };
  15476. auto res = cli.Put("/put", items);
  15477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15478. ASSERT_EQ(StatusCode::OK_200, res->status);
  15479. }
  15480. }
  15481. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15483. svr.Put("/put_customboundary",
  15484. [&](const Request &req, const Response & /*res*/,
  15485. const ContentReader &content_reader) {
  15486. if (req.is_multipart_form_data()) {
  15487. std::vector<FormData> items;
  15488. content_reader(
  15489. [&](const FormData &file) {
  15490. items.push_back(file);
  15491. return true;
  15492. },
  15493. [&](const char *data, size_t data_length) {
  15494. items.back().content.append(data, data_length);
  15495. return true;
  15496. });
  15497. EXPECT_TRUE(std::string(items[0].name) == "document");
  15498. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15499. EXPECT_TRUE(items[0].filename == "2MB_data");
  15500. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15501. EXPECT_TRUE(items[1].name == "hello");
  15502. EXPECT_TRUE(items[1].content == "world");
  15503. EXPECT_TRUE(items[1].filename == "");
  15504. EXPECT_TRUE(items[1].content_type == "");
  15505. } else {
  15506. std::string body;
  15507. content_reader([&](const char *data, size_t data_length) {
  15508. body.append(data, data_length);
  15509. return true;
  15510. });
  15511. }
  15512. });
  15513. auto port = svr.bind_to_any_port("localhost");
  15514. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15515. auto se = detail::scope_exit([&] {
  15516. svr.stop();
  15517. t.join();
  15518. ASSERT_FALSE(svr.is_running());
  15519. });
  15520. svr.wait_until_ready();
  15521. {
  15522. std::string data(1024 * 1024 * 2, '&');
  15523. std::stringstream buffer;
  15524. buffer << data;
  15525. SSLClient cli("localhost", port);
  15526. cli.enable_server_certificate_verification(false);
  15527. UploadFormDataItems items{
  15528. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15529. {"hello", "world", "", ""},
  15530. };
  15531. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15533. ASSERT_EQ(StatusCode::OK_200, res->status);
  15534. }
  15535. }
  15536. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15537. std::string data(1024 * 1024 * 2, '&');
  15538. std::stringstream buffer;
  15539. buffer << data;
  15540. Client cli("https://localhost:8080");
  15541. cli.enable_server_certificate_verification(false);
  15542. UploadFormDataItems items{
  15543. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15544. {"hello", "world", "", ""},
  15545. };
  15546. for (const char &c : " \t\r\n") {
  15547. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15548. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15549. ASSERT_FALSE(res);
  15550. }
  15551. }
  15552. TEST(MultipartFormDataTest, AlternateFilename) {
  15553. auto handled = false;
  15554. Server svr;
  15555. svr.Post("/test", [&](const Request &req, Response &res) {
  15556. ASSERT_EQ(2u, req.form.files.size());
  15557. ASSERT_EQ(1u, req.form.fields.size());
  15558. // Test files
  15559. const auto &file1 = req.form.get_file("file1");
  15560. ASSERT_EQ("file1", file1.name);
  15561. ASSERT_EQ("A.txt", file1.filename);
  15562. ASSERT_EQ("text/plain", file1.content_type);
  15563. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15564. const auto &file2 = req.form.get_file("file2");
  15565. ASSERT_EQ("file2", file2.name);
  15566. ASSERT_EQ("a.html", file2.filename);
  15567. ASSERT_EQ("text/html", file2.content_type);
  15568. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15569. file2.content);
  15570. // Test text field
  15571. const auto &text = req.form.get_field("text");
  15572. ASSERT_EQ("text default", text);
  15573. res.set_content("ok", "text/plain");
  15574. handled = true;
  15575. });
  15576. thread t = thread([&] { svr.listen(HOST, PORT); });
  15577. auto se = detail::scope_exit([&] {
  15578. svr.stop();
  15579. t.join();
  15580. ASSERT_FALSE(svr.is_running());
  15581. ASSERT_TRUE(handled);
  15582. });
  15583. svr.wait_until_ready();
  15584. auto req = "POST /test HTTP/1.1\r\n"
  15585. "Host: localhost\r\n"
  15586. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15587. "Content-Length: 399\r\n"
  15588. "\r\n"
  15589. "----------\r\n"
  15590. "Content-Disposition: form-data; name=\"text\"\r\n"
  15591. "\r\n"
  15592. "text default\r\n"
  15593. "----------\r\n"
  15594. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15595. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15596. "Content-Type: text/plain\r\n"
  15597. "\r\n"
  15598. "Content of a.txt.\r\n"
  15599. "\r\n"
  15600. "----------\r\n"
  15601. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15602. "\"a.html\"\r\n"
  15603. "Content-Type: text/html\r\n"
  15604. "\r\n"
  15605. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15606. "\r\n"
  15607. "------------\r\n";
  15608. ASSERT_TRUE(send_request(1, req));
  15609. }
  15610. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15611. auto handled = false;
  15612. Server svr;
  15613. svr.Post("/test", [&](const Request &req, Response &res) {
  15614. // Case-insensitive "utf-8''" prefix with a long value
  15615. const auto &file = req.form.get_file("file1");
  15616. ASSERT_EQ("file1", file.name);
  15617. // 8000 chars exercises both the Content-Disposition parser and the
  15618. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15619. // Prior to the fix, std::regex_match on this header would cause O(N)
  15620. // stack recursion in libstdc++, leading to SIGSEGV.
  15621. std::string expected_filename(8000, 'A');
  15622. ASSERT_EQ(expected_filename, file.filename);
  15623. res.set_content("ok", "text/plain");
  15624. handled = true;
  15625. });
  15626. thread t = thread([&] { svr.listen(HOST, PORT); });
  15627. auto se = detail::scope_exit([&] {
  15628. svr.stop();
  15629. t.join();
  15630. ASSERT_FALSE(svr.is_running());
  15631. ASSERT_TRUE(handled);
  15632. });
  15633. svr.wait_until_ready();
  15634. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15635. // Regression test for GHSA-qq6v-r583-3h69
  15636. std::string long_filename(8000, 'A');
  15637. std::string body = "----------\r\n"
  15638. "Content-Disposition: form-data; name=\"file1\"; "
  15639. "filename*=\"Utf-8''" +
  15640. long_filename +
  15641. "\"\r\n"
  15642. "\r\n"
  15643. "hello\r\n"
  15644. "------------\r\n";
  15645. auto req = "POST /test HTTP/1.1\r\n"
  15646. "Host: localhost\r\n"
  15647. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15648. "Content-Length: " +
  15649. std::to_string(body.size()) + "\r\n\r\n" + body;
  15650. ASSERT_TRUE(send_request(1, req));
  15651. }
  15652. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15653. auto handled = false;
  15654. Server svr;
  15655. svr.Post("/test", [&](const Request &req, Response &) {
  15656. ASSERT_EQ(2u, req.form.fields.size());
  15657. const auto &text1 = req.form.get_field("text1");
  15658. ASSERT_EQ("text1", text1);
  15659. const auto &text2 = req.form.get_field("text2");
  15660. ASSERT_EQ("text2", text2);
  15661. handled = true;
  15662. });
  15663. thread t = thread([&] { svr.listen(HOST, PORT); });
  15664. auto se = detail::scope_exit([&] {
  15665. svr.stop();
  15666. t.join();
  15667. ASSERT_FALSE(svr.is_running());
  15668. ASSERT_TRUE(handled);
  15669. });
  15670. svr.wait_until_ready();
  15671. auto req = "POST /test HTTP/1.1\r\n"
  15672. "Host: localhost\r\n"
  15673. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15674. "Content-Length: 146\r\n"
  15675. "\r\n----------\r\n"
  15676. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15677. "\r\n"
  15678. "text1"
  15679. "\r\n----------\r\n"
  15680. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15681. "\r\n"
  15682. "text2"
  15683. "\r\n------------";
  15684. std::string response;
  15685. ASSERT_TRUE(send_request(1, req, &response));
  15686. ASSERT_EQ("200", response.substr(9, 3));
  15687. }
  15688. TEST(MultipartFormDataTest, ContentLength) {
  15689. auto handled = false;
  15690. Server svr;
  15691. svr.Post("/test", [&](const Request &req, Response &) {
  15692. ASSERT_EQ(2u, req.form.fields.size());
  15693. const auto &text1 = req.form.get_field("text1");
  15694. ASSERT_EQ("text1", text1);
  15695. const auto &text2 = req.form.get_field("text2");
  15696. ASSERT_EQ("text2", text2);
  15697. handled = true;
  15698. });
  15699. thread t = thread([&] { svr.listen(HOST, PORT); });
  15700. auto se = detail::scope_exit([&] {
  15701. svr.stop();
  15702. t.join();
  15703. ASSERT_FALSE(svr.is_running());
  15704. ASSERT_TRUE(handled);
  15705. });
  15706. svr.wait_until_ready();
  15707. auto req = "POST /test HTTP/1.1\r\n"
  15708. "Host: localhost\r\n"
  15709. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15710. "Content-Length: 167\r\n"
  15711. "\r\n----------\r\n"
  15712. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15713. "Content-Length: 5\r\n"
  15714. "\r\n"
  15715. "text1"
  15716. "\r\n----------\r\n"
  15717. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15718. "\r\n"
  15719. "text2"
  15720. "\r\n------------\r\n";
  15721. std::string response;
  15722. ASSERT_TRUE(send_request(1, req, &response));
  15723. ASSERT_EQ("200", response.substr(9, 3));
  15724. }
  15725. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15726. auto handled = false;
  15727. Server svr;
  15728. svr.Post("/test", [&](const Request &req, Response &) {
  15729. ASSERT_EQ(2u, req.form.fields.size());
  15730. const auto &text1 = req.form.get_field("text1");
  15731. ASSERT_EQ("text1", text1);
  15732. // TODO: Add header access for text fields if needed
  15733. const auto &text2 = req.form.get_field("text2");
  15734. ASSERT_EQ("text2", text2);
  15735. // TODO: Header access for text fields needs to be implemented
  15736. // auto &headers = it->second.headers;
  15737. // ASSERT_EQ(3U, headers.size());
  15738. // auto custom_header = headers.find("x-whatever");
  15739. // ASSERT_TRUE(custom_header != headers.end());
  15740. // ASSERT_NE("customvalue", custom_header->second);
  15741. // ASSERT_EQ("CustomValue", custom_header->second);
  15742. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15743. handled = true;
  15744. });
  15745. thread t = thread([&] { svr.listen(HOST, PORT); });
  15746. auto se = detail::scope_exit([&] {
  15747. svr.stop();
  15748. t.join();
  15749. ASSERT_FALSE(svr.is_running());
  15750. ASSERT_TRUE(handled);
  15751. });
  15752. svr.wait_until_ready();
  15753. auto req = "POST /test HTTP/1.1\r\n"
  15754. "Host: localhost\r\n"
  15755. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15756. "Content-Length: 232\r\n"
  15757. "\r\n----------\r\n"
  15758. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15759. "Content-Length: 5\r\n"
  15760. "X-Test: 1\r\n"
  15761. "\r\n"
  15762. "text1"
  15763. "\r\n----------\r\n"
  15764. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15765. "Content-Type: text/plain\r\n"
  15766. "X-Whatever: CustomValue\r\n"
  15767. "\r\n"
  15768. "text2"
  15769. "\r\n------------\r\n"
  15770. "That should be disregarded. Not even read";
  15771. std::string response;
  15772. ASSERT_TRUE(send_request(1, req, &response));
  15773. ASSERT_EQ("200", response.substr(9, 3));
  15774. }
  15775. TEST(MultipartFormDataTest, LargeHeader) {
  15776. auto handled = false;
  15777. Server svr;
  15778. svr.Post("/test", [&](const Request &req, Response &) {
  15779. ASSERT_EQ(1u, req.form.fields.size());
  15780. const auto &text = req.form.get_field("name1");
  15781. ASSERT_EQ("text1", text);
  15782. handled = true;
  15783. });
  15784. thread t = thread([&] { svr.listen(HOST, PORT); });
  15785. auto se = detail::scope_exit([&] {
  15786. svr.stop();
  15787. t.join();
  15788. ASSERT_FALSE(svr.is_running());
  15789. ASSERT_TRUE(handled);
  15790. });
  15791. svr.wait_until_ready();
  15792. auto boundary = std::string("cpp-httplib-multipart-data");
  15793. std::string content = "--" + boundary +
  15794. "\r\n"
  15795. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15796. "\r\n"
  15797. "text1\r\n"
  15798. "--" +
  15799. boundary + "--\r\n";
  15800. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15801. "Host: localhost\r\n"
  15802. "Content-Type: multipart/form-data;boundary=" +
  15803. boundary +
  15804. "\r\n"
  15805. "Content-Length: " +
  15806. std::to_string(content.size()) +
  15807. "\r\n"
  15808. "Dummy-Header: ";
  15809. std::string header_suffix = "\r\n"
  15810. "\r\n";
  15811. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15812. size_t header_dummy_size =
  15813. read_buff_size -
  15814. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15815. auto header_dummy = std::string(header_dummy_size, '@');
  15816. auto req = header_prefix + header_dummy + header_suffix + content;
  15817. std::string response;
  15818. ASSERT_TRUE(send_request(1, req, &response));
  15819. ASSERT_EQ("200", response.substr(9, 3));
  15820. }
  15821. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15822. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15823. // (not chunked Transfer-Encoding) after the streaming refactor.
  15824. auto handled = false;
  15825. Server svr;
  15826. svr.Post("/upload", [&](const Request &req, Response &res) {
  15827. auto cl_it = req.headers.find("Content-Length");
  15828. EXPECT_TRUE(cl_it != req.headers.end());
  15829. auto te_it = req.headers.find("Transfer-Encoding");
  15830. EXPECT_TRUE(te_it == req.headers.end());
  15831. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15832. res.set_content("ok", "text/plain");
  15833. handled = true;
  15834. });
  15835. auto port = svr.bind_to_any_port(HOST);
  15836. auto t = thread([&] { svr.listen_after_bind(); });
  15837. auto se = detail::scope_exit([&] {
  15838. svr.stop();
  15839. t.join();
  15840. ASSERT_FALSE(svr.is_running());
  15841. ASSERT_TRUE(handled);
  15842. });
  15843. svr.wait_until_ready();
  15844. UploadFormDataItems items = {
  15845. {"field1", "hello", "", "text/plain"},
  15846. {"file1", "world", "test.txt", "application/octet-stream"},
  15847. };
  15848. Client cli(HOST, port);
  15849. auto res = cli.Post("/upload", {}, items);
  15850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15851. EXPECT_EQ(StatusCode::OK_200, res->status);
  15852. }
  15853. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15854. // Verify that make_multipart_content_provider coalesces many small segments
  15855. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15856. constexpr size_t kItemCount = 1000;
  15857. UploadFormDataItems items;
  15858. items.reserve(kItemCount);
  15859. for (size_t i = 0; i < kItemCount; i++) {
  15860. items.push_back(
  15861. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15862. }
  15863. const std::string boundary = "----test-boundary";
  15864. auto content_length = detail::get_multipart_content_length(items, boundary);
  15865. auto provider = detail::make_multipart_content_provider(items, boundary);
  15866. // Drive the provider the same way write_content_with_progress does
  15867. size_t write_count = 0;
  15868. size_t total_bytes = 0;
  15869. DataSink sink;
  15870. size_t offset = 0;
  15871. sink.write = [&](const char *d, size_t l) -> bool {
  15872. (void)d;
  15873. write_count++;
  15874. total_bytes += l;
  15875. offset += l;
  15876. return true;
  15877. };
  15878. sink.is_writable = []() -> bool { return true; };
  15879. while (offset < content_length) {
  15880. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15881. }
  15882. EXPECT_EQ(content_length, total_bytes);
  15883. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15884. // With buffering into 64KB blocks, write_count should be much smaller.
  15885. auto segment_count = 3 * kItemCount + 1;
  15886. EXPECT_LT(write_count, segment_count / 10);
  15887. }
  15888. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15889. // Integration test: send many UploadFormDataItems and verify the server
  15890. // receives all of them correctly (#2410).
  15891. constexpr size_t kItemCount = 500;
  15892. auto handled = false;
  15893. Server svr;
  15894. svr.Post("/upload", [&](const Request &req, Response &res) {
  15895. EXPECT_EQ(kItemCount, req.form.fields.size());
  15896. for (size_t i = 0; i < kItemCount; i++) {
  15897. auto key = "field" + std::to_string(i);
  15898. auto val = "value" + std::to_string(i);
  15899. auto it = req.form.fields.find(key);
  15900. if (it != req.form.fields.end()) {
  15901. EXPECT_EQ(val, it->second.content);
  15902. } else {
  15903. ADD_FAILURE() << "Missing field: " << key;
  15904. }
  15905. }
  15906. res.set_content("ok", "text/plain");
  15907. handled = true;
  15908. });
  15909. auto port = svr.bind_to_any_port(HOST);
  15910. auto t = thread([&] { svr.listen_after_bind(); });
  15911. auto se = detail::scope_exit([&] {
  15912. svr.stop();
  15913. t.join();
  15914. ASSERT_FALSE(svr.is_running());
  15915. ASSERT_TRUE(handled);
  15916. });
  15917. svr.wait_until_ready();
  15918. UploadFormDataItems items;
  15919. items.reserve(kItemCount);
  15920. for (size_t i = 0; i < kItemCount; i++) {
  15921. items.push_back(
  15922. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15923. }
  15924. Client cli(HOST, port);
  15925. auto res = cli.Post("/upload", items);
  15926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15927. EXPECT_EQ(StatusCode::OK_200, res->status);
  15928. }
  15929. TEST(MultipartFormDataTest, MakeFileProvider) {
  15930. // Verify make_file_provider sends a file's contents correctly.
  15931. const std::string file_content(4096, 'Z');
  15932. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15933. {
  15934. std::ofstream ofs(tmp_path, std::ios::binary);
  15935. ofs.write(file_content.data(),
  15936. static_cast<std::streamsize>(file_content.size()));
  15937. }
  15938. auto handled = false;
  15939. Server svr;
  15940. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15941. const ContentReader &content_reader) {
  15942. ASSERT_TRUE(req.is_multipart_form_data());
  15943. std::vector<FormData> items;
  15944. content_reader(
  15945. [&](const FormData &file) {
  15946. items.push_back(file);
  15947. return true;
  15948. },
  15949. [&](const char *data, size_t data_length) {
  15950. items.back().content.append(data, data_length);
  15951. return true;
  15952. });
  15953. ASSERT_EQ(1u, items.size());
  15954. EXPECT_EQ("myfile", items[0].name);
  15955. EXPECT_EQ("data.bin", items[0].filename);
  15956. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15957. EXPECT_EQ(file_content, items[0].content);
  15958. handled = true;
  15959. });
  15960. auto port = svr.bind_to_any_port(HOST);
  15961. auto t = thread([&] { svr.listen_after_bind(); });
  15962. auto se = detail::scope_exit([&] {
  15963. svr.stop();
  15964. t.join();
  15965. ASSERT_FALSE(svr.is_running());
  15966. ASSERT_TRUE(handled);
  15967. std::remove(tmp_path.c_str());
  15968. });
  15969. svr.wait_until_ready();
  15970. FormDataProviderItems providers;
  15971. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15972. "application/octet-stream"));
  15973. Client cli(HOST, port);
  15974. auto res = cli.Post("/upload", {}, {}, providers);
  15975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15976. EXPECT_EQ(StatusCode::OK_200, res->status);
  15977. }
  15978. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15979. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15980. // (100) headers is rejected with a 400 Bad Request response.
  15981. Server svr;
  15982. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15983. res.set_content("ok", "text/plain");
  15984. });
  15985. thread t = thread([&] { svr.listen(HOST, PORT); });
  15986. auto se = detail::scope_exit([&] {
  15987. svr.stop();
  15988. t.join();
  15989. ASSERT_FALSE(svr.is_running());
  15990. });
  15991. svr.wait_until_ready();
  15992. // Build a multipart part with 101 custom headers (exceeding
  15993. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15994. std::stringstream body;
  15995. body << "--simpleboundary\r\n"
  15996. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15997. for (int i = 0; i < 101; i++) {
  15998. body << "X-Custom-Header-" << i << ": value\r\n";
  15999. }
  16000. body << "\r\n"
  16001. << "value1\r\n"
  16002. << "--simpleboundary--\r\n";
  16003. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16004. Client cli(HOST, PORT);
  16005. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16007. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16008. }
  16009. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16010. // A body that never contains the declared boundary must not be accumulated
  16011. // while the parser waits for it. Buffering it would also make every read
  16012. // rescan everything seen so far, which is quadratic in the body size.
  16013. Server svr;
  16014. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16015. res.set_content("ok", "text/plain");
  16016. });
  16017. auto port = svr.bind_to_any_port(HOST);
  16018. thread t = thread([&] { svr.listen_after_bind(); });
  16019. auto se = detail::scope_exit([&] {
  16020. svr.stop();
  16021. t.join();
  16022. ASSERT_FALSE(svr.is_running());
  16023. });
  16024. svr.wait_until_ready();
  16025. Client cli(HOST, port);
  16026. cli.set_read_timeout(60, 0);
  16027. cli.set_write_timeout(60, 0);
  16028. // '-' is the worst case: it matches the first character of the boundary, so
  16029. // every position has to be checked against it.
  16030. auto post_dashes = [&](size_t size) {
  16031. const std::string body(size, '-');
  16032. auto start = std::chrono::steady_clock::now();
  16033. auto res =
  16034. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16035. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16036. std::chrono::steady_clock::now() - start)
  16037. .count();
  16038. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16039. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16040. return ms;
  16041. };
  16042. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16043. // Windows.
  16044. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16045. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16046. // Comparing the two sizes rather than checking an absolute duration keeps
  16047. // this meaningful across build types and CI load, both of which move the
  16048. // absolute numbers by more than an order of magnitude. Four times the bytes
  16049. // costs about four times the time when parsing is linear, and about sixteen
  16050. // times when the body is buffered and rescanned.
  16051. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16052. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16053. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16054. << "ms, which suggests the body is being buffered and rescanned";
  16055. }
  16056. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16057. // A boundary can only be followed by CRLF or by "--", so anything else is
  16058. // malformed no matter what comes next. The parser must say so right away
  16059. // instead of buffering the rest of the declared body.
  16060. Server svr;
  16061. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16062. res.set_content("ok", "text/plain");
  16063. });
  16064. auto port = svr.bind_to_any_port(HOST);
  16065. thread t = thread([&] { svr.listen_after_bind(); });
  16066. auto se = detail::scope_exit([&] {
  16067. svr.stop();
  16068. t.join();
  16069. ASSERT_FALSE(svr.is_running());
  16070. });
  16071. svr.wait_until_ready();
  16072. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16073. // buffers instead of failing would still be waiting for the remaining bytes.
  16074. const std::string body = "--zzzz\r\n"
  16075. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16076. "\r\n"
  16077. "text1"
  16078. "\r\n--zzzzXX";
  16079. const std::string req = "POST /post HTTP/1.1\r\n"
  16080. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16081. "Content-Length: 1048576\r\n"
  16082. "\r\n" +
  16083. body;
  16084. std::string response;
  16085. ASSERT_TRUE(send_request(3, req, &response, port));
  16086. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16087. EXPECT_EQ("400", response.substr(9, 3));
  16088. }
  16089. // Posts a multipart body split into two writes, so that the server sees the
  16090. // split at whatever offset the caller chose, and expects the single "text1"
  16091. // field to come through.
  16092. static void expect_split_multipart_ok(const std::string &body1,
  16093. const std::string &body2) {
  16094. auto handled = false;
  16095. Server svr;
  16096. svr.Post("/post", [&](const Request &req, Response &) {
  16097. EXPECT_EQ(1u, req.form.fields.size());
  16098. EXPECT_EQ("text1", req.form.get_field("text1"));
  16099. handled = true;
  16100. });
  16101. auto port = svr.bind_to_any_port(HOST);
  16102. thread t = thread([&] { svr.listen_after_bind(); });
  16103. auto se = detail::scope_exit([&] {
  16104. svr.stop();
  16105. t.join();
  16106. ASSERT_FALSE(svr.is_running());
  16107. ASSERT_TRUE(handled);
  16108. });
  16109. svr.wait_until_ready();
  16110. // "Connection: close" makes the server close once it has answered, so the
  16111. // response drain ends immediately instead of idling until the read timeout.
  16112. const std::string head =
  16113. "POST /post HTTP/1.1\r\n"
  16114. "Host: localhost\r\n"
  16115. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16116. "Connection: close\r\n"
  16117. "Content-Length: " +
  16118. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16119. std::string response;
  16120. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16121. ASSERT_GE(response.size(), 12u) << "no response";
  16122. EXPECT_EQ("200", response.substr(9, 3));
  16123. }
  16124. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16125. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16126. // ignored, including when it does not arrive in the same read as the
  16127. // close-delimiter itself.
  16128. expect_split_multipart_ok("--zzzz\r\n"
  16129. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16130. "\r\n"
  16131. "text1"
  16132. "\r\n--zzzz--",
  16133. "\r\nthis epilogue must be ignored\r\n");
  16134. }
  16135. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16136. // The initial boundary may be preceded by a preamble of any length and may
  16137. // straddle a read boundary. Discarding data while waiting for it must not
  16138. // throw away a partial boundary sitting at the end of the buffer.
  16139. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16140. "zz\r\n"
  16141. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16142. "\r\n"
  16143. "text1"
  16144. "\r\n--zzzz--\r\n");
  16145. }
  16146. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16147. // The received boundary was only checked for being non-empty, so it could be
  16148. // as long as a header is allowed to be. The parser scans the body for
  16149. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16150. // costs a nearly full comparison at nearly every position, making the
  16151. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16152. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16153. Server svr;
  16154. svr.Post("/post", [](const Request &req, Response &res) {
  16155. EXPECT_EQ(1u, req.form.fields.size());
  16156. EXPECT_EQ("text1", req.form.get_field("text1"));
  16157. res.set_content("ok", "text/plain");
  16158. });
  16159. auto port = svr.bind_to_any_port(HOST);
  16160. thread t = thread([&] { svr.listen_after_bind(); });
  16161. auto se = detail::scope_exit([&] {
  16162. svr.stop();
  16163. t.join();
  16164. ASSERT_FALSE(svr.is_running());
  16165. });
  16166. svr.wait_until_ready();
  16167. Client cli(HOST, port);
  16168. auto post_with_boundary_of_length = [&](size_t len) {
  16169. const std::string boundary(len, 'a');
  16170. const std::string body =
  16171. "--" + boundary +
  16172. "\r\n"
  16173. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16174. "\r\n"
  16175. "text1"
  16176. "\r\n--" +
  16177. boundary + "--\r\n";
  16178. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16179. };
  16180. auto res = post_with_boundary_of_length(70);
  16181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16182. EXPECT_EQ(StatusCode::OK_200, res->status);
  16183. res = post_with_boundary_of_length(71);
  16184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16185. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16186. }
  16187. TEST(MakeFileBodyTest, Basic) {
  16188. const std::string file_content(4096, 'Z');
  16189. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16190. {
  16191. std::ofstream ofs(tmp_path, std::ios::binary);
  16192. ofs.write(file_content.data(),
  16193. static_cast<std::streamsize>(file_content.size()));
  16194. }
  16195. auto handled = false;
  16196. Server svr;
  16197. svr.Post("/upload", [&](const Request &req, Response &res) {
  16198. EXPECT_EQ(file_content, req.body);
  16199. handled = true;
  16200. res.status = StatusCode::OK_200;
  16201. });
  16202. auto port = svr.bind_to_any_port(HOST);
  16203. auto t = thread([&] { svr.listen_after_bind(); });
  16204. auto se = detail::scope_exit([&] {
  16205. svr.stop();
  16206. t.join();
  16207. ASSERT_FALSE(svr.is_running());
  16208. ASSERT_TRUE(handled);
  16209. std::remove(tmp_path.c_str());
  16210. });
  16211. svr.wait_until_ready();
  16212. auto fb = make_file_body(tmp_path);
  16213. ASSERT_GT(fb.first, 0u);
  16214. Client cli(HOST, port);
  16215. auto res =
  16216. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16218. EXPECT_EQ(StatusCode::OK_200, res->status);
  16219. }
  16220. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16221. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16222. {
  16223. std::ofstream ofs(path, std::ios::binary);
  16224. const std::string content(100, 'A');
  16225. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16226. }
  16227. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16228. auto body = make_file_body(path);
  16229. ASSERT_EQ(100u, body.first);
  16230. ASSERT_TRUE(static_cast<bool>(body.second));
  16231. // Rewritten shorter after its length was measured - and, on a server, after
  16232. // that length has already gone out as Content-Length.
  16233. {
  16234. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16235. const std::string content(10, 'A');
  16236. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16237. }
  16238. std::string written;
  16239. DataSink sink;
  16240. sink.write = [&](const char *d, size_t l) {
  16241. written.append(d, l);
  16242. return true;
  16243. };
  16244. // The provider has to report failure. write_content_with_progress() advances
  16245. // its offset only by what was written, so a provider that returns true
  16246. // without completing the length it promised is called again straight away,
  16247. // and again.
  16248. EXPECT_FALSE(body.second(0, body.first, sink));
  16249. EXPECT_EQ(std::string(10, 'A'), written);
  16250. }
  16251. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16252. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16253. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16254. {
  16255. std::ofstream ofs(path, std::ios::binary);
  16256. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16257. }
  16258. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16259. auto body = make_file_body(path);
  16260. ASSERT_EQ(content.size(), body.first);
  16261. ASSERT_TRUE(static_cast<bool>(body.second));
  16262. std::string written;
  16263. DataSink sink;
  16264. sink.write = [&](const char *d, size_t l) {
  16265. written.append(d, l);
  16266. return true;
  16267. };
  16268. EXPECT_TRUE(body.second(0, body.first, sink));
  16269. EXPECT_EQ(content, written);
  16270. }
  16271. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16272. static constexpr unsigned int number_of_tasks{1000000};
  16273. std::atomic_uint count{0};
  16274. std::unique_ptr<TaskQueue> task_queue{
  16275. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16276. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16277. auto queued = task_queue->enqueue(
  16278. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16279. EXPECT_TRUE(queued);
  16280. }
  16281. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16282. task_queue->shutdown();
  16283. #else
  16284. EXPECT_NO_THROW(task_queue->shutdown());
  16285. #endif
  16286. EXPECT_EQ(number_of_tasks, count.load());
  16287. }
  16288. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16289. static constexpr unsigned int number_of_tasks{1000000};
  16290. static constexpr unsigned int qlimit{2};
  16291. unsigned int queued_count{0};
  16292. std::atomic_uint count{0};
  16293. std::unique_ptr<TaskQueue> task_queue{
  16294. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16295. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16296. if (task_queue->enqueue(
  16297. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16298. queued_count++;
  16299. }
  16300. }
  16301. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16302. task_queue->shutdown();
  16303. #else
  16304. EXPECT_NO_THROW(task_queue->shutdown());
  16305. #endif
  16306. EXPECT_EQ(queued_count, count.load());
  16307. EXPECT_TRUE(queued_count <= number_of_tasks);
  16308. EXPECT_TRUE(queued_count >= qlimit);
  16309. }
  16310. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16311. // Use a short idle timeout so a dynamic thread spawns, times out and
  16312. // exits during the test, and the pool keeps working afterwards.
  16313. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16314. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16315. /*idle_timeout_sec=*/1}};
  16316. std::atomic_uint count{0};
  16317. std::condition_variable cv;
  16318. std::mutex mtx;
  16319. bool release = false;
  16320. // Block the base thread so the second task spawns a dynamic thread.
  16321. EXPECT_TRUE(task_queue->enqueue([&] {
  16322. std::unique_lock<std::mutex> lock(mtx);
  16323. while (!release) {
  16324. cv.wait(lock);
  16325. }
  16326. count++;
  16327. }));
  16328. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16329. // Let the dynamic thread finish its task and exceed the idle timeout.
  16330. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16331. {
  16332. std::unique_lock<std::mutex> lock(mtx);
  16333. release = true;
  16334. }
  16335. cv.notify_all();
  16336. // The pool must still accept and run tasks after the dynamic thread exited.
  16337. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16338. task_queue->shutdown();
  16339. EXPECT_EQ(3u, count.load());
  16340. }
  16341. TEST(TaskQueueTest, MaxQueuedRequests) {
  16342. static constexpr unsigned int qlimit{3};
  16343. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16344. std::condition_variable sem_cv;
  16345. std::mutex sem_mtx;
  16346. int credits = 0;
  16347. bool queued;
  16348. /* Fill up the queue with tasks that will block until we give them credits to
  16349. * complete. */
  16350. for (unsigned int n = 0; n <= qlimit;) {
  16351. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16352. std::unique_lock<std::mutex> lock(sem_mtx);
  16353. while (credits <= 0) {
  16354. sem_cv.wait(lock);
  16355. }
  16356. /* Consume the credit and signal the test code if they are all gone. */
  16357. if (--credits == 0) { sem_cv.notify_one(); }
  16358. });
  16359. if (n < qlimit) {
  16360. /* The first qlimit enqueues must succeed. */
  16361. EXPECT_TRUE(queued);
  16362. } else {
  16363. /* The last one will succeed only when the worker thread
  16364. * starts and dequeues the first blocking task. Although
  16365. * not necessary for the correctness of this test, we sleep for
  16366. * a short while to avoid busy waiting. */
  16367. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16368. }
  16369. if (queued) { n++; }
  16370. }
  16371. /* Further enqueues must fail since the queue is full. */
  16372. for (auto i = 0; i < 4; i++) {
  16373. queued = task_queue->enqueue([] {});
  16374. EXPECT_FALSE(queued);
  16375. }
  16376. /* Give the credits to allow the previous tasks to complete. */
  16377. {
  16378. std::unique_lock<std::mutex> lock(sem_mtx);
  16379. credits += qlimit + 1;
  16380. }
  16381. sem_cv.notify_all();
  16382. /* Wait for all the credits to be consumed. */
  16383. {
  16384. std::unique_lock<std::mutex> lock(sem_mtx);
  16385. while (credits > 0) {
  16386. sem_cv.wait(lock);
  16387. }
  16388. }
  16389. /* Check that we are able again to enqueue at least qlimit tasks. */
  16390. for (unsigned int i = 0; i < qlimit; i++) {
  16391. queued = task_queue->enqueue([] {});
  16392. EXPECT_TRUE(queued);
  16393. }
  16394. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16395. task_queue->shutdown();
  16396. #else
  16397. EXPECT_NO_THROW(task_queue->shutdown());
  16398. #endif
  16399. }
  16400. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16401. Server svr;
  16402. std::string method;
  16403. std::string body;
  16404. auto has_content_length = false;
  16405. auto has_transfer_encoding = false;
  16406. std::atomic<int> bad_requests{0};
  16407. // Leftover body bytes get parsed as a malformed request and answered with
  16408. // 400
  16409. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16410. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16411. });
  16412. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16413. res.set_redirect("/down", StatusCode::SeeOther_303);
  16414. });
  16415. svr.Get("/down", [&](const Request &req, Response &res) {
  16416. method = req.method;
  16417. body = req.body;
  16418. has_content_length = req.has_header("Content-Length");
  16419. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16420. res.set_content("ok", "text/plain");
  16421. });
  16422. auto port = svr.bind_to_any_port(HOST);
  16423. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16424. auto se = detail::scope_exit([&] {
  16425. svr.stop();
  16426. thread.join();
  16427. ASSERT_FALSE(svr.is_running());
  16428. });
  16429. svr.wait_until_ready();
  16430. const std::string payload = "SECRET-BODY";
  16431. auto check = [&](Client &cli, const Result &res) {
  16432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16433. EXPECT_EQ(StatusCode::OK_200, res->status);
  16434. EXPECT_EQ("ok", res->body);
  16435. EXPECT_EQ("GET", method);
  16436. EXPECT_TRUE(body.empty());
  16437. EXPECT_FALSE(has_content_length);
  16438. EXPECT_FALSE(has_transfer_encoding);
  16439. // Nothing of the original body may be left on the connection
  16440. auto res2 = cli.Get("/down");
  16441. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16442. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16443. EXPECT_EQ("ok", res2->body);
  16444. EXPECT_EQ(0, bad_requests);
  16445. };
  16446. // With content length
  16447. {
  16448. Client cli(HOST, port);
  16449. cli.set_keep_alive(true);
  16450. cli.set_follow_location(true);
  16451. auto res = cli.Post(
  16452. "/up", payload.size(),
  16453. [&](size_t offset, size_t length, DataSink &sink) {
  16454. return sink.write(payload.data() + offset, length);
  16455. },
  16456. "text/plain");
  16457. check(cli, res);
  16458. }
  16459. // Without content length (chunked)
  16460. {
  16461. Client cli(HOST, port);
  16462. cli.set_keep_alive(true);
  16463. cli.set_follow_location(true);
  16464. auto res = cli.Post(
  16465. "/up",
  16466. [&](size_t /*offset*/, DataSink &sink) {
  16467. sink.write(payload.data(), payload.size());
  16468. sink.done();
  16469. return true;
  16470. },
  16471. "text/plain");
  16472. check(cli, res);
  16473. }
  16474. }
  16475. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16476. Server svr;
  16477. std::string target;
  16478. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16479. // Echo the still-encoded name back in the Location
  16480. const std::string prefix = "/start/";
  16481. res.status = StatusCode::Found_302;
  16482. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16483. });
  16484. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16485. target = req.target;
  16486. res.set_content("ok", "text/plain");
  16487. });
  16488. auto port = svr.bind_to_any_port(HOST);
  16489. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16490. auto se = detail::scope_exit([&] {
  16491. svr.stop();
  16492. thread.join();
  16493. ASSERT_FALSE(svr.is_running());
  16494. });
  16495. svr.wait_until_ready();
  16496. // Decoding the Location path would turn the first four into a path
  16497. // separator, a query delimiter, a fragment delimiter and a different
  16498. // percent-encoded octet. The rest must keep reaching the server as they are.
  16499. const std::vector<std::string> names = {
  16500. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16501. };
  16502. for (auto path_encode : {true, false}) {
  16503. Client cli(HOST, port);
  16504. cli.set_follow_location(true);
  16505. cli.set_path_encode(path_encode);
  16506. for (const auto &name : names) {
  16507. target.clear();
  16508. auto res = cli.Get("/start/" + name);
  16509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16510. EXPECT_EQ(StatusCode::OK_200, res->status);
  16511. EXPECT_EQ("/dest/" + name, target);
  16512. }
  16513. }
  16514. }
  16515. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16516. Server svr;
  16517. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16518. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16519. });
  16520. svr.Get("/hello", [](const Request &req, Response &res) {
  16521. res.set_content(req.get_param_value("key"), "text/plain");
  16522. });
  16523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16524. auto se = detail::scope_exit([&] {
  16525. svr.stop();
  16526. thread.join();
  16527. ASSERT_FALSE(svr.is_running());
  16528. });
  16529. svr.wait_until_ready();
  16530. {
  16531. Client cli(HOST, PORT);
  16532. cli.set_follow_location(true);
  16533. auto res = cli.Get("/");
  16534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16535. EXPECT_EQ(StatusCode::OK_200, res->status);
  16536. EXPECT_EQ("val&key2=val2", res->body);
  16537. }
  16538. }
  16539. #endif
  16540. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16541. Server svr;
  16542. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16543. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16544. });
  16545. svr.Get("/hello", [](const Request &req, Response &res) {
  16546. res.set_content(req.get_param_value("key"), "text/plain");
  16547. });
  16548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16549. auto se = detail::scope_exit([&] {
  16550. svr.stop();
  16551. thread.join();
  16552. ASSERT_FALSE(svr.is_running());
  16553. });
  16554. svr.wait_until_ready();
  16555. {
  16556. Client cli(HOST, PORT);
  16557. cli.set_follow_location(true);
  16558. auto res = cli.Get("/");
  16559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16560. EXPECT_EQ(StatusCode::OK_200, res->status);
  16561. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16562. }
  16563. }
  16564. TEST(RedirectTest, RedirectWithPlusInPath) {
  16565. Server svr;
  16566. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16567. res.set_redirect("/a+b");
  16568. });
  16569. // Route pattern uses regex; escape + as \\+
  16570. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16571. res.set_content(req.path, "text/plain");
  16572. });
  16573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16574. auto se = detail::scope_exit([&] {
  16575. svr.stop();
  16576. thread.join();
  16577. ASSERT_FALSE(svr.is_running());
  16578. });
  16579. svr.wait_until_ready();
  16580. {
  16581. Client cli(HOST, PORT);
  16582. cli.set_follow_location(true);
  16583. auto res = cli.Get("/");
  16584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16585. EXPECT_EQ(StatusCode::OK_200, res->status);
  16586. EXPECT_EQ("/a+b", res->body);
  16587. }
  16588. }
  16589. TEST(RedirectTest, ResolveRelativeLocation) {
  16590. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16591. const std::vector<std::pair<std::string, std::string>> cases = {
  16592. {"g", "/b/c/g"},
  16593. {"./g", "/b/c/g"},
  16594. {"g/", "/b/c/g/"},
  16595. {"?y", "/b/c/d;p?y"},
  16596. {"g?y", "/b/c/g?y"},
  16597. {"#s", "/b/c/d;p?q#s"},
  16598. {"g#s", "/b/c/g#s"},
  16599. {"g?y#s", "/b/c/g?y#s"},
  16600. {";x", "/b/c/;x"},
  16601. {"g;x", "/b/c/g;x"},
  16602. {".", "/b/c/"},
  16603. {"./", "/b/c/"},
  16604. {"..", "/b/"},
  16605. {"../", "/b/"},
  16606. {"../g", "/b/g"},
  16607. {"../..", "/"},
  16608. {"../../", "/"},
  16609. {"../../g", "/g"},
  16610. {"../../../g", "/g"},
  16611. {"g.", "/b/c/g."},
  16612. {".g", "/b/c/.g"},
  16613. {"g..", "/b/c/g.."},
  16614. {"..g", "/b/c/..g"},
  16615. {"./../g", "/b/g"},
  16616. {"./g/.", "/b/c/g/"},
  16617. {"g/./h", "/b/c/g/h"},
  16618. {"g/../h", "/b/c/h"},
  16619. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16620. {"g;x=1/../y", "/b/c/y"},
  16621. {"g?y/./x", "/b/c/g?y/./x"},
  16622. {"g#s/../x", "/b/c/g#s/../x"},
  16623. // Not relative-path references, so left for parse_url.
  16624. {"/g", "/g"},
  16625. {"//g", "//g"},
  16626. {"http://g/x", "http://g/x"},
  16627. {"g:h", "g:h"},
  16628. };
  16629. for (const auto &c : cases) {
  16630. EXPECT_EQ(c.second,
  16631. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16632. << c.first;
  16633. }
  16634. }
  16635. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16636. Server svr;
  16637. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16638. res.set_redirect(req.get_param_value("to"));
  16639. });
  16640. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16641. res.set_content(req.target, "text/plain");
  16642. });
  16643. svr.Get("/other", [](const Request &req, Response &res) {
  16644. res.set_content(req.target, "text/plain");
  16645. });
  16646. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16647. auto se = detail::scope_exit([&] {
  16648. svr.stop();
  16649. thread.join();
  16650. ASSERT_FALSE(svr.is_running());
  16651. });
  16652. svr.wait_until_ready();
  16653. const std::vector<std::pair<std::string, std::string>> cases = {
  16654. {"next", "/dir/next"},
  16655. {"./next?x=1", "/dir/next?x=1"},
  16656. {"../other", "/other"},
  16657. };
  16658. for (const auto &c : cases) {
  16659. Client cli(HOST, PORT);
  16660. cli.set_follow_location(true);
  16661. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16662. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16663. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16664. EXPECT_EQ(c.second, res->body) << c.first;
  16665. }
  16666. }
  16667. #ifdef CPPHTTPLIB_SSL_ENABLED
  16668. TEST(RedirectTest, Issue2185_Online) {
  16669. SSLClient client("github.com");
  16670. client.set_follow_location(true);
  16671. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16672. "Coollab-Windows.zip");
  16673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16674. EXPECT_EQ(StatusCode::OK_200, res->status);
  16675. EXPECT_EQ(9920427U, res->body.size());
  16676. }
  16677. #endif
  16678. TEST(VulnerabilityTest, CRLFInjection) {
  16679. Server svr;
  16680. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16681. res.set_content("Hello 1", "text/plain");
  16682. });
  16683. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16684. res.set_content("Hello 2", "text/plain");
  16685. });
  16686. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16687. res.set_content("Hello 3", "text/plain");
  16688. });
  16689. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16690. res.set_content("Hello 4", "text/plain");
  16691. });
  16692. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16693. for (const auto &x : req.headers) {
  16694. auto key = x.first;
  16695. EXPECT_STRNE("evil", key.c_str());
  16696. }
  16697. });
  16698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16699. auto se = detail::scope_exit([&] {
  16700. svr.stop();
  16701. thread.join();
  16702. ASSERT_FALSE(svr.is_running());
  16703. });
  16704. svr.wait_until_ready();
  16705. {
  16706. Client cli(HOST, PORT);
  16707. cli.Post("/test1", "A=B",
  16708. "application/x-www-form-urlencoded\r\nevil: hello1");
  16709. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16710. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16711. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16712. }
  16713. }
  16714. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16715. auto server_thread = std::thread([] {
  16716. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16717. default_socket_options(srv);
  16718. sockaddr_in addr{};
  16719. addr.sin_family = AF_INET;
  16720. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16721. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16722. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16723. ::listen(srv, 1);
  16724. sockaddr_in cli_addr{};
  16725. socklen_t cli_len = sizeof(cli_addr);
  16726. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16727. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16728. std::string buf_all;
  16729. char buf[2048];
  16730. ssize_t n;
  16731. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16732. buf_all.append(buf, static_cast<size_t>(n));
  16733. size_t pos;
  16734. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16735. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16736. auto e = request_block.find("\r\n");
  16737. if (e != std::string::npos) {
  16738. auto request_line = request_block.substr(0, e);
  16739. std::string msg =
  16740. "CRLF injection detected in request line: '" + request_line + "'";
  16741. EXPECT_FALSE(true) << msg;
  16742. }
  16743. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16744. ::send(cli,
  16745. #ifdef _WIN32
  16746. static_cast<const char *>(resp.c_str()),
  16747. static_cast<int>(resp.size()),
  16748. #else
  16749. resp.c_str(), resp.size(),
  16750. #endif
  16751. 0);
  16752. buf_all.erase(0, pos + 4);
  16753. }
  16754. }
  16755. detail::close_socket(cli);
  16756. detail::close_socket(srv);
  16757. });
  16758. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16759. auto cli = Client("127.0.0.1", PORT + 1);
  16760. auto headers = Headers{
  16761. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16762. {"Connection", "keep-alive"}};
  16763. auto res = cli.Get("/hi", headers);
  16764. EXPECT_FALSE(res);
  16765. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16766. server_thread.join();
  16767. }
  16768. // A request rejected before any byte reaches the socket must fail right away
  16769. // instead of waiting for a response the server will never send.
  16770. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16771. // The kernel completes the TCP handshake from the listen backlog, so the
  16772. // client connects, but nothing ever reads, responds or closes.
  16773. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16774. default_socket_options(srv);
  16775. sockaddr_in addr{};
  16776. addr.sin_family = AF_INET;
  16777. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16778. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16779. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16780. ASSERT_EQ(0, ::listen(srv, 8));
  16781. auto cli = Client("127.0.0.1", PORT + 1);
  16782. cli.set_read_timeout(10, 0);
  16783. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16784. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16785. std::chrono::steady_clock::now() - start)
  16786. .count();
  16787. };
  16788. {
  16789. Request req;
  16790. req.method = "GE T";
  16791. req.path = "/";
  16792. auto start = std::chrono::steady_clock::now();
  16793. auto res = cli.send(req);
  16794. EXPECT_FALSE(res);
  16795. EXPECT_EQ(Error::Write, res.error());
  16796. EXPECT_LT(elapsed_ms(start), 1000);
  16797. }
  16798. {
  16799. auto start = std::chrono::steady_clock::now();
  16800. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16801. EXPECT_FALSE(res);
  16802. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16803. EXPECT_LT(elapsed_ms(start), 1000);
  16804. }
  16805. EXPECT_FALSE(cli.is_socket_open());
  16806. detail::close_socket(srv);
  16807. }
  16808. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16809. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16810. default_socket_options(srv);
  16811. sockaddr_in addr{};
  16812. addr.sin_family = AF_INET;
  16813. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16814. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16815. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16816. ASSERT_EQ(0, ::listen(srv, 1));
  16817. std::string received;
  16818. auto server_thread = std::thread([&] {
  16819. auto sock = ::accept(srv, nullptr, nullptr);
  16820. if (sock == INVALID_SOCKET) { return; }
  16821. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16822. char buf[2048];
  16823. ssize_t n;
  16824. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16825. received.append(buf, static_cast<size_t>(n));
  16826. }
  16827. detail::close_socket(sock);
  16828. });
  16829. {
  16830. auto cli = Client("127.0.0.1", PORT + 1);
  16831. // "Z" sorts after the default headers, so writing straight to the socket
  16832. // would have sent the request line and those headers before the rejection.
  16833. auto handle =
  16834. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16835. EXPECT_FALSE(handle.is_valid());
  16836. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16837. }
  16838. server_thread.join();
  16839. detail::close_socket(srv);
  16840. EXPECT_TRUE(received.empty()) << received;
  16841. }
  16842. TEST(PathParamsTest, StaticMatch) {
  16843. const auto pattern = "/users/all";
  16844. detail::PathParamsMatcher matcher(pattern);
  16845. Request request;
  16846. request.path = "/users/all";
  16847. ASSERT_TRUE(matcher.match(request));
  16848. std::unordered_map<std::string, std::string> expected_params = {};
  16849. EXPECT_EQ(request.path_params, expected_params);
  16850. }
  16851. TEST(PathParamsTest, StaticMismatch) {
  16852. const auto pattern = "/users/all";
  16853. detail::PathParamsMatcher matcher(pattern);
  16854. Request request;
  16855. request.path = "/users/1";
  16856. ASSERT_FALSE(matcher.match(request));
  16857. }
  16858. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16859. const auto pattern = "/users/:id/subscriptions";
  16860. detail::PathParamsMatcher matcher(pattern);
  16861. Request request;
  16862. request.path = "/users/42/subscriptions";
  16863. ASSERT_TRUE(matcher.match(request));
  16864. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16865. EXPECT_EQ(request.path_params, expected_params);
  16866. }
  16867. TEST(PathParamsTest, SingleParamInTheEnd) {
  16868. const auto pattern = "/users/:id";
  16869. detail::PathParamsMatcher matcher(pattern);
  16870. Request request;
  16871. request.path = "/users/24";
  16872. ASSERT_TRUE(matcher.match(request));
  16873. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16874. EXPECT_EQ(request.path_params, expected_params);
  16875. }
  16876. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16877. const auto pattern = "/users/:id/";
  16878. detail::PathParamsMatcher matcher(pattern);
  16879. Request request;
  16880. request.path = "/users/42/";
  16881. ASSERT_TRUE(matcher.match(request));
  16882. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16883. EXPECT_EQ(request.path_params, expected_params);
  16884. }
  16885. TEST(PathParamsTest, EmptyParam) {
  16886. const auto pattern = "/users/:id/";
  16887. detail::PathParamsMatcher matcher(pattern);
  16888. Request request;
  16889. request.path = "/users//";
  16890. ASSERT_TRUE(matcher.match(request));
  16891. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16892. EXPECT_EQ(request.path_params, expected_params);
  16893. }
  16894. TEST(PathParamsTest, FragmentMismatch) {
  16895. const auto pattern = "/users/:id/";
  16896. detail::PathParamsMatcher matcher(pattern);
  16897. Request request;
  16898. request.path = "/admins/24/";
  16899. ASSERT_FALSE(matcher.match(request));
  16900. }
  16901. TEST(PathParamsTest, ExtraFragments) {
  16902. const auto pattern = "/users/:id";
  16903. detail::PathParamsMatcher matcher(pattern);
  16904. Request request;
  16905. request.path = "/users/42/subscriptions";
  16906. ASSERT_FALSE(matcher.match(request));
  16907. }
  16908. TEST(PathParamsTest, MissingTrailingParam) {
  16909. const auto pattern = "/users/:id";
  16910. detail::PathParamsMatcher matcher(pattern);
  16911. Request request;
  16912. request.path = "/users";
  16913. ASSERT_FALSE(matcher.match(request));
  16914. }
  16915. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16916. const auto pattern = "/users/:id/subscriptions";
  16917. detail::PathParamsMatcher matcher(pattern);
  16918. Request request;
  16919. request.path = "/users/subscriptions";
  16920. ASSERT_FALSE(matcher.match(request));
  16921. }
  16922. TEST(PathParamsTest, MultipleParams) {
  16923. const auto pattern = "/users/:userid/subscriptions/:subid";
  16924. detail::PathParamsMatcher matcher(pattern);
  16925. Request request;
  16926. request.path = "/users/42/subscriptions/2";
  16927. ASSERT_TRUE(matcher.match(request));
  16928. std::unordered_map<std::string, std::string> expected_params = {
  16929. {"userid", "42"}, {"subid", "2"}};
  16930. EXPECT_EQ(request.path_params, expected_params);
  16931. }
  16932. TEST(PathParamsTest, SequenceOfParams) {
  16933. const auto pattern = "/values/:x/:y/:z";
  16934. detail::PathParamsMatcher matcher(pattern);
  16935. Request request;
  16936. request.path = "/values/1/2/3";
  16937. ASSERT_TRUE(matcher.match(request));
  16938. std::unordered_map<std::string, std::string> expected_params = {
  16939. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16940. EXPECT_EQ(request.path_params, expected_params);
  16941. }
  16942. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16943. const auto pattern = "/prefix:suffix";
  16944. detail::PathParamsMatcher matcher(pattern);
  16945. Request request;
  16946. request.path = "/prefix:suffix";
  16947. ASSERT_TRUE(matcher.match(request));
  16948. const std::unordered_map<std::string, std::string> expected_params = {};
  16949. EXPECT_EQ(request.path_params, expected_params);
  16950. }
  16951. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16952. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16953. // calling thread's stack on a long enough path for a quantified pattern;
  16954. // RegexMatcher must refuse to run regex matching on paths beyond
  16955. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16956. detail::RegexMatcher matcher("/files/(.*)");
  16957. Request within_limit;
  16958. within_limit.path = "/files/" + std::string(10, 'A');
  16959. EXPECT_TRUE(matcher.match(within_limit));
  16960. Request over_limit;
  16961. over_limit.path =
  16962. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16963. EXPECT_FALSE(matcher.match(over_limit));
  16964. }
  16965. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16966. Server svr;
  16967. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16968. res.set_content("ok", "text/plain");
  16969. });
  16970. auto port = svr.bind_to_any_port(HOST);
  16971. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16972. auto se = detail::scope_exit([&] {
  16973. svr.stop();
  16974. thread.join();
  16975. ASSERT_FALSE(svr.is_running());
  16976. });
  16977. svr.wait_until_ready();
  16978. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16979. // request URI limit; this used to be able to crash the process.
  16980. std::string path =
  16981. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16982. std::string req = "GET " + path +
  16983. " HTTP/1.1\r\n"
  16984. "Host: " +
  16985. std::string(HOST) + ":" + std::to_string(port) +
  16986. "\r\n"
  16987. "Connection: close\r\n"
  16988. "\r\n";
  16989. std::string response;
  16990. ASSERT_TRUE(send_request(5, req, &response, port));
  16991. EXPECT_NE(std::string::npos, response.find("404"));
  16992. }
  16993. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16994. Server svr;
  16995. auto handler = [](const Request & /*req*/, Response &res) {
  16996. res.set_content("hit", "text/plain");
  16997. };
  16998. // No regex metacharacter, so this one is compared literally
  16999. svr.Get("/literal/route", handler);
  17000. // '.' is a regex metacharacter, so this one must keep regex semantics
  17001. svr.Get("/a.c", handler);
  17002. auto port = svr.bind_to_any_port(HOST);
  17003. std::thread t([&]() { svr.listen_after_bind(); });
  17004. auto se = detail::scope_exit([&] {
  17005. svr.stop();
  17006. t.join();
  17007. ASSERT_FALSE(svr.is_running());
  17008. });
  17009. svr.wait_until_ready();
  17010. Client cli(HOST, port);
  17011. struct {
  17012. const char *path;
  17013. int status;
  17014. } cases[] = {
  17015. {"/literal/route", StatusCode::OK_200},
  17016. {"/literal/routes", StatusCode::NotFound_404},
  17017. {"/literal/rout", StatusCode::NotFound_404},
  17018. {"/abc", StatusCode::OK_200},
  17019. {"/a.c", StatusCode::OK_200},
  17020. };
  17021. for (const auto &x : cases) {
  17022. auto res = cli.Get(x.path);
  17023. ASSERT_TRUE(res) << x.path;
  17024. EXPECT_EQ(x.status, res->status) << x.path;
  17025. }
  17026. }
  17027. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17028. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17029. // from exhausting the stack, so it must only constrain routes that actually
  17030. // run a regular expression. A literal route is matched by comparison and
  17031. // stays usable at any length.
  17032. Server svr;
  17033. const std::string pattern =
  17034. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17035. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17036. res.set_content("hit", "text/plain");
  17037. });
  17038. auto port = svr.bind_to_any_port(HOST);
  17039. std::thread t([&]() { svr.listen_after_bind(); });
  17040. auto se = detail::scope_exit([&] {
  17041. svr.stop();
  17042. t.join();
  17043. ASSERT_FALSE(svr.is_running());
  17044. });
  17045. svr.wait_until_ready();
  17046. Client cli(HOST, port);
  17047. auto res = cli.Get(pattern);
  17048. ASSERT_TRUE(res);
  17049. EXPECT_EQ(StatusCode::OK_200, res->status);
  17050. }
  17051. TEST(ParseUrlTest, VariousPatterns) {
  17052. {
  17053. detail::UrlComponents uc;
  17054. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17055. EXPECT_EQ("http", uc.scheme);
  17056. EXPECT_EQ("example.com", uc.host);
  17057. EXPECT_EQ("8080", uc.port);
  17058. EXPECT_EQ("/path", uc.path);
  17059. EXPECT_EQ("?q=1", uc.query);
  17060. }
  17061. {
  17062. detail::UrlComponents uc;
  17063. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17064. EXPECT_EQ("https", uc.scheme);
  17065. EXPECT_EQ("example.com", uc.host);
  17066. EXPECT_TRUE(uc.port.empty());
  17067. EXPECT_EQ("/path", uc.path);
  17068. }
  17069. {
  17070. detail::UrlComponents uc;
  17071. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17072. EXPECT_EQ("::1", uc.host);
  17073. EXPECT_EQ("8080", uc.port);
  17074. EXPECT_EQ("/path", uc.path);
  17075. }
  17076. {
  17077. detail::UrlComponents uc;
  17078. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17079. }
  17080. {
  17081. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17082. // the path while the connection still targets the bracketed host.
  17083. detail::UrlComponents uc;
  17084. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17085. }
  17086. {
  17087. detail::UrlComponents uc;
  17088. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17089. }
  17090. {
  17091. detail::UrlComponents uc;
  17092. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17093. EXPECT_EQ("::1", uc.host);
  17094. EXPECT_TRUE(uc.port.empty());
  17095. EXPECT_EQ("/path", uc.path);
  17096. }
  17097. {
  17098. detail::UrlComponents uc;
  17099. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17100. EXPECT_TRUE(uc.scheme.empty());
  17101. EXPECT_EQ("example.com", uc.host);
  17102. EXPECT_EQ("/path", uc.path);
  17103. EXPECT_EQ("?q=1", uc.query);
  17104. }
  17105. {
  17106. detail::UrlComponents uc;
  17107. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17108. EXPECT_TRUE(uc.host.empty());
  17109. EXPECT_EQ("/path", uc.path);
  17110. EXPECT_EQ("?q=1", uc.query);
  17111. }
  17112. {
  17113. detail::UrlComponents uc;
  17114. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17115. EXPECT_EQ("example.com", uc.host);
  17116. EXPECT_EQ("8080", uc.port);
  17117. }
  17118. {
  17119. // Unix socket path — must not be parsed as host
  17120. detail::UrlComponents uc;
  17121. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17122. EXPECT_TRUE(uc.host.empty());
  17123. }
  17124. {
  17125. detail::UrlComponents uc;
  17126. ASSERT_TRUE(detail::parse_url("", uc));
  17127. EXPECT_TRUE(uc.host.empty());
  17128. EXPECT_TRUE(uc.path.empty());
  17129. }
  17130. {
  17131. detail::UrlComponents uc;
  17132. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17133. }
  17134. {
  17135. detail::UrlComponents uc;
  17136. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17137. }
  17138. {
  17139. // Accepted by parse_url; callers restrict to http/https
  17140. detail::UrlComponents uc;
  17141. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17142. EXPECT_EQ("ftp", uc.scheme);
  17143. }
  17144. {
  17145. detail::UrlComponents uc;
  17146. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17147. }
  17148. {
  17149. detail::UrlComponents uc;
  17150. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17151. }
  17152. }
  17153. TEST(ParseUrlTest, FragmentHandling) {
  17154. {
  17155. detail::UrlComponents uc;
  17156. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17157. EXPECT_EQ("/path", uc.path);
  17158. EXPECT_TRUE(uc.query.empty());
  17159. }
  17160. {
  17161. detail::UrlComponents uc;
  17162. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17163. EXPECT_TRUE(uc.path.empty());
  17164. EXPECT_TRUE(uc.query.empty());
  17165. }
  17166. }
  17167. TEST(ParseUrlTest, UserinfoHandling) {
  17168. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17169. // parsers would see evil.com as the host.
  17170. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17171. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17172. for (auto url : urls) {
  17173. detail::UrlComponents uc;
  17174. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17175. }
  17176. }
  17177. TEST(ParseUrlTest, IPv6EdgeCases) {
  17178. {
  17179. detail::UrlComponents uc;
  17180. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17181. EXPECT_TRUE(uc.scheme.empty());
  17182. EXPECT_EQ("::1", uc.host);
  17183. EXPECT_EQ("8080", uc.port);
  17184. }
  17185. {
  17186. // Zone ID '%25' is not in [a-fA-F0-9:]
  17187. detail::UrlComponents uc;
  17188. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17189. }
  17190. }
  17191. TEST(ParseUrlTest, SchemeEdgeCases) {
  17192. {
  17193. detail::UrlComponents uc;
  17194. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17195. }
  17196. {
  17197. detail::UrlComponents uc;
  17198. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17199. }
  17200. {
  17201. detail::UrlComponents uc;
  17202. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17203. }
  17204. }
  17205. TEST(ParseUrlTest, PortEdgeCases) {
  17206. {
  17207. detail::UrlComponents uc;
  17208. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17209. EXPECT_TRUE(uc.port.empty());
  17210. EXPECT_EQ("/path", uc.path);
  17211. }
  17212. {
  17213. // parse_url accepts any port string; validation is done by parse_port
  17214. detail::UrlComponents uc;
  17215. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17216. EXPECT_EQ("abc", uc.port);
  17217. }
  17218. }
  17219. TEST(ParseUrlTest, WebSocketPatterns) {
  17220. {
  17221. detail::UrlComponents uc;
  17222. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17223. EXPECT_EQ("ws", uc.scheme);
  17224. EXPECT_EQ("echo.example.com", uc.host);
  17225. EXPECT_EQ("8080", uc.port);
  17226. EXPECT_EQ("/ws", uc.path);
  17227. }
  17228. {
  17229. detail::UrlComponents uc;
  17230. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17231. EXPECT_EQ("wss", uc.scheme);
  17232. EXPECT_EQ("echo.example.com", uc.host);
  17233. EXPECT_TRUE(uc.port.empty());
  17234. EXPECT_EQ("/ws", uc.path);
  17235. }
  17236. }
  17237. TEST(ParseUrlTest, QueryOnly) {
  17238. detail::UrlComponents uc;
  17239. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17240. EXPECT_TRUE(uc.host.empty());
  17241. EXPECT_TRUE(uc.path.empty());
  17242. EXPECT_EQ("?q=1&r=2", uc.query);
  17243. }
  17244. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17245. detail::UrlComponents uc;
  17246. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17247. EXPECT_TRUE(uc.scheme.empty());
  17248. EXPECT_EQ("example.com", uc.host);
  17249. EXPECT_EQ("443", uc.port);
  17250. EXPECT_EQ("/path", uc.path);
  17251. }
  17252. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17253. // If ipv6 regex working, regex match codepath is taken.
  17254. // else port will default to 80 in Client impl
  17255. int clientImplMagicPort = 80;
  17256. int port = 4321;
  17257. // above ports must be different to avoid false negative
  17258. EXPECT_NE(clientImplMagicPort, port);
  17259. std::string ipV6TestURL = "http://[ff06::c3]";
  17260. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17261. CLIENT_PRIVATE_KEY_FILE);
  17262. EXPECT_EQ(cli.port(), port);
  17263. }
  17264. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17265. auto file_path = "./www/dir/index.html";
  17266. auto dir_path = "./www/dir";
  17267. detail::FileStat stat_file(file_path);
  17268. EXPECT_TRUE(stat_file.is_file());
  17269. EXPECT_FALSE(stat_file.is_dir());
  17270. detail::FileStat stat_dir(dir_path);
  17271. EXPECT_FALSE(stat_dir.is_file());
  17272. EXPECT_TRUE(stat_dir.is_dir());
  17273. }
  17274. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17275. // IPv4 with default HTTP port (80)
  17276. EXPECT_EQ("example.com",
  17277. detail::make_host_and_port_string("example.com", 80, false));
  17278. // IPv4 with default HTTPS port (443)
  17279. EXPECT_EQ("example.com",
  17280. detail::make_host_and_port_string("example.com", 443, true));
  17281. // IPv4 with non-default HTTP port
  17282. EXPECT_EQ("example.com:8080",
  17283. detail::make_host_and_port_string("example.com", 8080, false));
  17284. // IPv4 with non-default HTTPS port
  17285. EXPECT_EQ("example.com:8443",
  17286. detail::make_host_and_port_string("example.com", 8443, true));
  17287. // IPv6 with default HTTP port (80)
  17288. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17289. // IPv6 with default HTTPS port (443)
  17290. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17291. // IPv6 with non-default HTTP port
  17292. EXPECT_EQ("[::1]:8080",
  17293. detail::make_host_and_port_string("::1", 8080, false));
  17294. // IPv6 with non-default HTTPS port
  17295. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17296. // IPv6 full address with default port
  17297. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17298. detail::make_host_and_port_string(
  17299. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17300. // IPv6 full address with non-default port
  17301. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17302. detail::make_host_and_port_string(
  17303. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17304. // IPv6 localhost with non-default port
  17305. EXPECT_EQ("[::1]:3000",
  17306. detail::make_host_and_port_string("::1", 3000, false));
  17307. // IPv6 with zone ID (link-local address) with default port
  17308. EXPECT_EQ("[fe80::1%eth0]",
  17309. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17310. // IPv6 with zone ID (link-local address) with non-default port
  17311. EXPECT_EQ("[fe80::1%eth0]:8080",
  17312. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17313. // Edge case: Port 443 with is_ssl=false (should add port)
  17314. EXPECT_EQ("example.com:443",
  17315. detail::make_host_and_port_string("example.com", 443, false));
  17316. // Edge case: Port 80 with is_ssl=true (should add port)
  17317. EXPECT_EQ("example.com:80",
  17318. detail::make_host_and_port_string("example.com", 80, true));
  17319. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17320. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17321. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17322. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17323. // Security fix: Already bracketed IPv6 should not get double brackets
  17324. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17325. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17326. EXPECT_EQ("[::1]:8080",
  17327. detail::make_host_and_port_string("[::1]", 8080, false));
  17328. EXPECT_EQ("[2001:db8::1]:8080",
  17329. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17330. EXPECT_EQ("[fe80::1%eth0]",
  17331. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17332. EXPECT_EQ("[fe80::1%eth0]:8080",
  17333. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17334. // Edge case: Empty host (should return as-is)
  17335. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17336. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17337. // This is a known limitation but shouldn't crash
  17338. EXPECT_EQ("[host:name]",
  17339. detail::make_host_and_port_string("host:name", 80, false));
  17340. // Port number edge cases (no validation, but should not crash)
  17341. EXPECT_EQ("example.com:0",
  17342. detail::make_host_and_port_string("example.com", 0, false));
  17343. EXPECT_EQ("example.com:-1",
  17344. detail::make_host_and_port_string("example.com", -1, false));
  17345. EXPECT_EQ("example.com:65535",
  17346. detail::make_host_and_port_string("example.com", 65535, false));
  17347. EXPECT_EQ("example.com:65536",
  17348. detail::make_host_and_port_string("example.com", 65536, false));
  17349. }
  17350. #ifdef CPPHTTPLIB_SSL_ENABLED
  17351. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17352. httplib::SSLClient cli("roblox.com", 443);
  17353. cli.set_follow_location(true);
  17354. auto res = cli.Get("/");
  17355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17356. EXPECT_EQ(StatusCode::OK_200, res->status);
  17357. }
  17358. #endif
  17359. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17360. Server svr;
  17361. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17362. EXPECT_EQ(res.status, 400);
  17363. });
  17364. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17365. auto se = detail::scope_exit([&] {
  17366. svr.stop();
  17367. thread.join();
  17368. ASSERT_FALSE(svr.is_running());
  17369. });
  17370. svr.wait_until_ready();
  17371. Client cli(HOST, PORT);
  17372. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17373. }
  17374. TEST(InvalidHeaderCharsTest, is_field_name) {
  17375. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17376. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17377. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17378. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17379. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17380. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17381. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17382. EXPECT_FALSE(detail::fields::is_field_name(""));
  17383. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17384. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17385. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17386. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17387. }
  17388. TEST(InvalidHeaderCharsTest, is_field_value) {
  17389. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17390. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17391. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17392. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17393. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17394. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17395. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17396. EXPECT_TRUE(detail::fields::is_field_value(""));
  17397. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17398. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17399. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17400. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17401. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17402. }
  17403. TEST(InvalidHeaderCharsTest, OnServer) {
  17404. Server svr;
  17405. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17406. std::string header = "Not Set";
  17407. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17408. res.set_header(header, "value");
  17409. res.set_content("Page Content Page Content", "text/plain");
  17410. });
  17411. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17412. std::string header = "Not Set";
  17413. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17414. res.set_header("X-Test", header);
  17415. res.set_content("Page Content Page Content", "text/plain");
  17416. });
  17417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17418. auto se = detail::scope_exit([&] {
  17419. svr.stop();
  17420. thread.join();
  17421. ASSERT_FALSE(svr.is_running());
  17422. });
  17423. svr.wait_until_ready();
  17424. Client cli(HOST, PORT);
  17425. {
  17426. auto res = cli.Get(
  17427. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17429. EXPECT_EQ("Page Content Page Content", res->body);
  17430. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17431. }
  17432. {
  17433. auto res = cli.Get(
  17434. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17436. EXPECT_EQ("Page Content Page Content", res->body);
  17437. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17438. }
  17439. }
  17440. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17441. auto handled = false;
  17442. Server svr;
  17443. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17444. thread t = thread([&] { svr.listen(HOST, PORT); });
  17445. auto se = detail::scope_exit([&] {
  17446. svr.stop();
  17447. t.join();
  17448. ASSERT_FALSE(svr.is_running());
  17449. ASSERT_FALSE(handled);
  17450. });
  17451. svr.wait_until_ready();
  17452. auto req = "POST /test HTTP/1.1\r\n"
  17453. "Content-Length: x\r\n"
  17454. "\r\n";
  17455. std::string response;
  17456. ASSERT_TRUE(send_request(1, req, &response));
  17457. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17458. response.substr(0, response.find("\r\n")));
  17459. }
  17460. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17461. // case-insensitive, and a server that receives a 100-continue expectation in
  17462. // an HTTP/1.0 request MUST ignore it.
  17463. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17464. std::string response;
  17465. ASSERT_TRUE(send_request(1, req, &response, port));
  17466. *got_100 = response.find("100 Continue") != std::string::npos;
  17467. }
  17468. class ExpectTokenTest : public ::testing::Test {
  17469. protected:
  17470. void SetUp() override {
  17471. svr_.Post("/p", [](const Request &, Response &res) {
  17472. res.set_content("ok", "text/plain");
  17473. });
  17474. port_ = svr_.bind_to_any_port(HOST);
  17475. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17476. svr_.wait_until_ready();
  17477. }
  17478. void TearDown() override {
  17479. svr_.stop();
  17480. if (thread_.joinable()) { thread_.join(); }
  17481. }
  17482. std::string request(const char *version, const char *expect_value) const {
  17483. return std::string("POST /p ") + version +
  17484. "\r\n"
  17485. "Host: localhost\r\n"
  17486. "Content-Length: 2\r\n"
  17487. "Connection: close\r\n"
  17488. "Expect: " +
  17489. expect_value +
  17490. "\r\n"
  17491. "\r\n"
  17492. "hi";
  17493. }
  17494. Server svr_;
  17495. int port_ = 0;
  17496. thread thread_;
  17497. };
  17498. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17499. bool got_100 = false;
  17500. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17501. EXPECT_TRUE(got_100);
  17502. }
  17503. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17504. bool got_100 = true;
  17505. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17506. EXPECT_FALSE(got_100);
  17507. }
  17508. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17509. bool got_100 = false;
  17510. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17511. EXPECT_TRUE(got_100);
  17512. }
  17513. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17514. bool got_100 = false;
  17515. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17516. EXPECT_TRUE(got_100);
  17517. }
  17518. // `100 Continue` is sent only when the server starts reading the body, so a
  17519. // request rejected before that never invites the client to send it. The
  17520. // requests below carry the expectation but withhold the body, as a client
  17521. // waiting for `100 Continue` would.
  17522. // A POST that expects `100 Continue` and withholds its two-byte body.
  17523. static std::string expect_headers_only(const std::string &path) {
  17524. return "POST " + path +
  17525. " HTTP/1.1\r\n"
  17526. "Host: localhost\r\n"
  17527. "Content-Length: 2\r\n"
  17528. "Expect: 100-continue\r\n"
  17529. "\r\n";
  17530. }
  17531. class ExpectLazyContinueTest : public ::testing::Test {
  17532. protected:
  17533. void SetUp() override {
  17534. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17535. if (req.path == "/pre-routing") {
  17536. res.status = StatusCode::Unauthorized_401;
  17537. return Server::HandlerResponse::Handled;
  17538. }
  17539. return Server::HandlerResponse::Unhandled;
  17540. });
  17541. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17542. if (req.matched_route == "/pre-request") {
  17543. res.status = StatusCode::Forbidden_403;
  17544. return Server::HandlerResponse::Handled;
  17545. }
  17546. return Server::HandlerResponse::Unhandled;
  17547. });
  17548. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17549. res.set_content("ok", "text/plain");
  17550. });
  17551. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17552. res.set_content("ok", "text/plain");
  17553. });
  17554. svr_.Post("/reader-used", [](const Request &, Response &res,
  17555. const ContentReader &content_reader) {
  17556. std::string body;
  17557. content_reader([&](const char *data, size_t len) {
  17558. body.append(data, len);
  17559. return true;
  17560. });
  17561. res.set_content(body, "text/plain");
  17562. });
  17563. svr_.Post("/reader-unused",
  17564. [](const Request &, Response &res, const ContentReader &) {
  17565. res.set_content("ignored", "text/plain");
  17566. });
  17567. port_ = svr_.bind_to_any_port(HOST);
  17568. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17569. svr_.wait_until_ready();
  17570. }
  17571. void TearDown() override {
  17572. svr_.stop();
  17573. if (thread_.joinable()) { thread_.join(); }
  17574. }
  17575. // Sends `req` and reads until the server closes the connection. Returns
  17576. // false if the read had to wait for the client-side timeout instead.
  17577. bool send_until_closed(const std::string &req, std::string *resp) const {
  17578. auto start = std::chrono::steady_clock::now();
  17579. if (!send_request(3, req, resp, port_)) { return false; }
  17580. auto elapsed = std::chrono::steady_clock::now() - start;
  17581. return elapsed < std::chrono::seconds(2);
  17582. }
  17583. // The final response comes without `100 Continue`, and the server closes
  17584. // the connection since the body may or may not follow.
  17585. void expect_final_without_interim(const std::string &path,
  17586. const char *status_line) const {
  17587. std::string resp;
  17588. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17589. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17590. EXPECT_EQ(0u, resp.find(status_line));
  17591. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17592. }
  17593. Server svr_;
  17594. int port_ = 0;
  17595. thread thread_;
  17596. };
  17597. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17598. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17599. }
  17600. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17601. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17602. }
  17603. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17604. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17605. }
  17606. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17607. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17608. }
  17609. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17610. // The body follows once `100 Continue` has had time to arrive.
  17611. auto req = expect_headers_only("/reader-used");
  17612. req.insert(req.size() - 2, "Connection: close\r\n");
  17613. std::string resp;
  17614. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17615. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17616. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17617. EXPECT_NE(std::string::npos, resp.find("hi"));
  17618. }
  17619. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17620. // Large enough for the client to add `Expect: 100-continue` itself.
  17621. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17622. std::atomic<bool> body_sent{false};
  17623. Client cli(HOST, port_);
  17624. auto res = cli.Post(
  17625. "/pre-request", length,
  17626. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17627. body_sent = true;
  17628. std::string chunk(len, 'x');
  17629. sink.write(chunk.data(), chunk.size());
  17630. return true;
  17631. },
  17632. "application/octet-stream");
  17633. ASSERT_TRUE(res);
  17634. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17635. EXPECT_FALSE(body_sent);
  17636. }
  17637. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17638. Server svr;
  17639. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17640. return StatusCode::ExpectationFailed_417;
  17641. });
  17642. svr.Post("/p", [](const Request &, Response &res) {
  17643. res.set_content("ok", "text/plain");
  17644. });
  17645. auto port = svr.bind_to_any_port(HOST);
  17646. thread t = thread([&] { svr.listen_after_bind(); });
  17647. auto se = detail::scope_exit([&] {
  17648. svr.stop();
  17649. t.join();
  17650. });
  17651. svr.wait_until_ready();
  17652. std::string resp;
  17653. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17654. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17655. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17656. // Exactly one response: the route handler must not run after the 417.
  17657. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17658. }
  17659. #ifndef _WIN32
  17660. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17661. static constexpr char reject[] = "Unauthorized";
  17662. static constexpr char accept[] = "Upload accepted";
  17663. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17664. Server svr;
  17665. svr.set_expect_100_continue_handler(
  17666. [](const Request & /*req*/, Response &res) {
  17667. res.status = StatusCode::Unauthorized_401;
  17668. res.set_content(reject, "text/plain");
  17669. return res.status;
  17670. });
  17671. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17672. res.set_content(accept, "text/plain");
  17673. });
  17674. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17675. auto se = detail::scope_exit([&] {
  17676. svr.stop();
  17677. thread.join();
  17678. ASSERT_FALSE(svr.is_running());
  17679. });
  17680. svr.wait_until_ready();
  17681. {
  17682. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17683. curl_easy_init(), &curl_easy_cleanup};
  17684. ASSERT_NE(curl, nullptr);
  17685. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17686. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17687. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17688. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17689. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17690. &curl_slist_free_all};
  17691. ASSERT_NE(list, nullptr);
  17692. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17693. struct read_data {
  17694. size_t read_size;
  17695. size_t total_size;
  17696. } data = {0, total_size};
  17697. using read_callback_t =
  17698. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17699. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17700. void *userdata) -> size_t {
  17701. read_data *d = (read_data *)userdata;
  17702. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17703. std::fill_n(ptr, size * nmemb, 'A');
  17704. d->read_size += size * nmemb;
  17705. return size * nmemb;
  17706. };
  17707. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17708. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17709. std::vector<char> buffer;
  17710. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17711. using write_callback_t =
  17712. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17713. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17714. void *userdata) -> size_t {
  17715. std::vector<char> *buf = (std::vector<char> *)userdata;
  17716. buf->reserve(buf->size() + size * nmemb + 1);
  17717. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17718. return size * nmemb;
  17719. };
  17720. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17721. {
  17722. const auto res = curl_easy_perform(curl.get());
  17723. ASSERT_EQ(res, CURLE_OK);
  17724. }
  17725. {
  17726. auto response_code = long{};
  17727. const auto res =
  17728. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17729. ASSERT_EQ(res, CURLE_OK);
  17730. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17731. }
  17732. {
  17733. auto dl = curl_off_t{};
  17734. const auto res =
  17735. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17736. ASSERT_EQ(res, CURLE_OK);
  17737. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17738. }
  17739. {
  17740. buffer.push_back('\0');
  17741. ASSERT_STRCASEEQ(buffer.data(), reject);
  17742. }
  17743. }
  17744. }
  17745. #endif
  17746. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17747. // Regression test for #2458.
  17748. //
  17749. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17750. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17751. // ticket can make the client socket spuriously readable during the
  17752. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17753. // the client withholds the body and then blocks reading a response that never
  17754. // comes, failing with `Failed to read connection`.
  17755. //
  17756. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17757. // within the timeout. This raw OpenSSL server deliberately never sends
  17758. // `100 Continue`; the client must still deliver the body and receive 200.
  17759. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17760. signal(SIGPIPE, SIG_IGN);
  17761. const auto port = PORT + 4;
  17762. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17763. ASSERT_NE(srv, INVALID_SOCKET);
  17764. int opt = 1;
  17765. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17766. sockaddr_in addr{};
  17767. addr.sin_family = AF_INET;
  17768. addr.sin_port = htons(static_cast<uint16_t>(port));
  17769. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17770. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17771. ASSERT_EQ(0, ::listen(srv, 1));
  17772. std::atomic<size_t> server_body_bytes{0};
  17773. auto server_thread = std::thread([&] {
  17774. sockaddr_in cli_addr{};
  17775. socklen_t cli_len = sizeof(cli_addr);
  17776. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17777. if (cli == INVALID_SOCKET) { return; }
  17778. // Bound the lifetime of the server side so a buggy client (which never
  17779. // sends the body) cannot make this thread block forever on join.
  17780. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17781. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17782. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17783. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17784. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17785. SSL *ssl = SSL_new(ctx);
  17786. SSL_set_fd(ssl, static_cast<int>(cli));
  17787. if (SSL_accept(ssl) > 0) {
  17788. // Read the request headers. Reading here also flushes the TLS 1.3
  17789. // session tickets to the client. Deliberately do NOT send
  17790. // `100 Continue`.
  17791. std::string buf;
  17792. char tmp[1024];
  17793. while (buf.find("\r\n\r\n") == std::string::npos) {
  17794. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17795. if (n <= 0) { break; }
  17796. buf.append(tmp, static_cast<size_t>(n));
  17797. }
  17798. // A correct client sends the body now; count what arrives.
  17799. auto pos = buf.find("\r\n\r\n");
  17800. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17801. while (body < 4096) {
  17802. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17803. if (n <= 0) { break; }
  17804. body += static_cast<size_t>(n);
  17805. }
  17806. server_body_bytes = body;
  17807. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17808. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17809. SSL_shutdown(ssl);
  17810. }
  17811. SSL_free(ssl);
  17812. detail::close_socket(cli);
  17813. SSL_CTX_free(ctx);
  17814. });
  17815. auto se = detail::scope_exit([&] {
  17816. server_thread.join();
  17817. detail::close_socket(srv);
  17818. });
  17819. SSLClient cli("127.0.0.1", port);
  17820. cli.enable_server_certificate_verification(false);
  17821. cli.set_connection_timeout(5, 0);
  17822. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17823. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17824. std::string body(4096, 'A');
  17825. auto res = cli.Put("/api/test", body, "application/json");
  17826. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17827. EXPECT_EQ(StatusCode::OK_200, res->status);
  17828. EXPECT_EQ(body.size(), server_body_bytes.load());
  17829. }
  17830. #endif
  17831. template <typename S, typename C>
  17832. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17833. svr.Get("/stream", [&](const Request &, Response &res) {
  17834. auto data = new std::string("01234567890123456789");
  17835. res.set_content_provider(
  17836. data->size(), "text/plain",
  17837. [&, data](size_t offset, size_t length, DataSink &sink) {
  17838. const size_t DATA_CHUNK_SIZE = 4;
  17839. const auto &d = *data;
  17840. std::this_thread::sleep_for(std::chrono::seconds(1));
  17841. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17842. return true;
  17843. },
  17844. [data](bool success) {
  17845. EXPECT_FALSE(success);
  17846. delete data;
  17847. });
  17848. });
  17849. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17850. auto i = new size_t(0);
  17851. res.set_content_provider(
  17852. "text/plain",
  17853. [i](size_t, DataSink &sink) {
  17854. if (*i < 5) {
  17855. std::this_thread::sleep_for(std::chrono::seconds(1));
  17856. sink.write("abcd", 4);
  17857. (*i)++;
  17858. } else {
  17859. sink.done();
  17860. }
  17861. return true;
  17862. },
  17863. [i](bool success) {
  17864. EXPECT_FALSE(success);
  17865. delete i;
  17866. });
  17867. });
  17868. svr.Get("/chunked", [&](const Request &, Response &res) {
  17869. auto i = new size_t(0);
  17870. res.set_chunked_content_provider(
  17871. "text/plain",
  17872. [i](size_t, DataSink &sink) {
  17873. if (*i < 5) {
  17874. std::this_thread::sleep_for(std::chrono::seconds(1));
  17875. sink.os << "abcd";
  17876. (*i)++;
  17877. } else {
  17878. sink.done();
  17879. }
  17880. return true;
  17881. },
  17882. [i](bool success) {
  17883. EXPECT_FALSE(success);
  17884. delete i;
  17885. });
  17886. });
  17887. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17888. auto se = detail::scope_exit([&] {
  17889. svr.stop();
  17890. listen_thread.join();
  17891. ASSERT_FALSE(svr.is_running());
  17892. });
  17893. svr.wait_until_ready();
  17894. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17895. {
  17896. auto start = std::chrono::steady_clock::now();
  17897. auto res = cli.Get("/stream");
  17898. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17899. std::chrono::steady_clock::now() - start)
  17900. .count();
  17901. ASSERT_FALSE(res);
  17902. EXPECT_EQ(Error::Read, res.error());
  17903. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17904. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17905. }
  17906. {
  17907. auto start = std::chrono::steady_clock::now();
  17908. auto res = cli.Get("/stream_without_length");
  17909. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17910. std::chrono::steady_clock::now() - start)
  17911. .count();
  17912. ASSERT_FALSE(res);
  17913. EXPECT_EQ(Error::Read, res.error());
  17914. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17915. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17916. }
  17917. {
  17918. auto start = std::chrono::steady_clock::now();
  17919. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17920. EXPECT_EQ("abcd", string(data, data_length));
  17921. return true;
  17922. });
  17923. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17924. std::chrono::steady_clock::now() - start)
  17925. .count();
  17926. ASSERT_FALSE(res);
  17927. EXPECT_EQ(Error::Read, res.error());
  17928. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17929. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17930. }
  17931. }
  17932. TEST(MaxTimeoutTest, ContentStream) {
  17933. time_t timeout = 2000;
  17934. time_t threshold = 200;
  17935. Server svr;
  17936. Client cli("localhost", PORT);
  17937. max_timeout_test(svr, cli, timeout, threshold);
  17938. }
  17939. #ifdef CPPHTTPLIB_SSL_ENABLED
  17940. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17941. time_t timeout = 2000;
  17942. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17944. SSLClient cli("localhost", PORT);
  17945. cli.enable_server_certificate_verification(false);
  17946. max_timeout_test(svr, cli, timeout, threshold);
  17947. }
  17948. #endif
  17949. class EventDispatcher {
  17950. public:
  17951. EventDispatcher() {}
  17952. bool wait_event(DataSink *sink) {
  17953. unique_lock<mutex> lk(m_);
  17954. int id = id_;
  17955. // Wait with timeout to prevent hanging if client disconnects
  17956. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17957. [&] { return cid_ == id; })) {
  17958. return false; // Timeout occurred
  17959. }
  17960. sink->write(message_.data(), message_.size());
  17961. return true;
  17962. }
  17963. void send_event(const string &message) {
  17964. lock_guard<mutex> lk(m_);
  17965. cid_ = id_++;
  17966. message_ = message;
  17967. cv_.notify_all();
  17968. }
  17969. private:
  17970. mutex m_;
  17971. condition_variable cv_;
  17972. atomic_int id_{0};
  17973. atomic_int cid_{-1};
  17974. string message_;
  17975. };
  17976. TEST(ClientInThreadTest, Issue2068) {
  17977. EventDispatcher ed;
  17978. Server svr;
  17979. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17980. res.set_chunked_content_provider("text/event-stream",
  17981. [&](size_t /*offset*/, DataSink &sink) {
  17982. return ed.wait_event(&sink);
  17983. });
  17984. });
  17985. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17986. svr.wait_until_ready();
  17987. thread event_thread([&] {
  17988. int id = 0;
  17989. while (svr.is_running()) {
  17990. this_thread::sleep_for(chrono::milliseconds(500));
  17991. std::stringstream ss;
  17992. ss << "data: " << id << "\n\n";
  17993. ed.send_event(ss.str());
  17994. id++;
  17995. }
  17996. });
  17997. auto se = detail::scope_exit([&] {
  17998. svr.stop();
  17999. listen_thread.join();
  18000. event_thread.join();
  18001. ASSERT_FALSE(svr.is_running());
  18002. });
  18003. {
  18004. auto client = detail::make_unique<Client>(HOST, PORT);
  18005. client->set_read_timeout(std::chrono::minutes(10));
  18006. std::atomic<bool> stop{false};
  18007. std::thread t([&] {
  18008. client->Get("/event1",
  18009. [&](const char *, size_t) -> bool { return !stop; });
  18010. });
  18011. std::this_thread::sleep_for(std::chrono::seconds(2));
  18012. stop = true;
  18013. client->stop();
  18014. t.join();
  18015. // Reset client after thread has finished
  18016. client.reset();
  18017. }
  18018. }
  18019. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18020. auto handled = false;
  18021. Server svr;
  18022. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18023. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18024. auto se = detail::scope_exit([&] {
  18025. svr.stop();
  18026. t.join();
  18027. ASSERT_FALSE(svr.is_running());
  18028. ASSERT_FALSE(handled);
  18029. });
  18030. svr.wait_until_ready();
  18031. // Two Content-Length headers with different values — must be rejected
  18032. auto req = "POST /test HTTP/1.1\r\n"
  18033. "Content-Length: 5\r\n"
  18034. "Content-Length: 10\r\n"
  18035. "\r\n"
  18036. "hello";
  18037. std::string response;
  18038. ASSERT_TRUE(send_request(1, req, &response));
  18039. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18040. response.substr(0, response.find("\r\n")));
  18041. }
  18042. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18043. auto handled = false;
  18044. Server svr;
  18045. svr.Post("/test", [&](const Request &, Response &res) {
  18046. handled = true;
  18047. res.set_content("ok", "text/plain");
  18048. });
  18049. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18050. auto se = detail::scope_exit([&] {
  18051. svr.stop();
  18052. t.join();
  18053. ASSERT_FALSE(svr.is_running());
  18054. ASSERT_TRUE(handled);
  18055. });
  18056. svr.wait_until_ready();
  18057. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18058. auto req = "POST /test HTTP/1.1\r\n"
  18059. "Host: localhost\r\n"
  18060. "Content-Length: 5\r\n"
  18061. "Content-Length: 5\r\n"
  18062. "\r\n"
  18063. "hello";
  18064. std::string response;
  18065. ASSERT_TRUE(send_request(1, req, &response));
  18066. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18067. }
  18068. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18069. Server svr;
  18070. svr.Get("/test", [](const Request &, Response &res) {
  18071. res.set_content("ok", "text/plain");
  18072. });
  18073. auto port = svr.bind_to_any_port(HOST);
  18074. thread t = thread([&] { svr.listen_after_bind(); });
  18075. auto se = detail::scope_exit([&] {
  18076. svr.stop();
  18077. t.join();
  18078. ASSERT_FALSE(svr.is_running());
  18079. });
  18080. svr.wait_until_ready();
  18081. auto status_line = [&](const std::string &host_lines) {
  18082. std::string res;
  18083. send_request(
  18084. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18085. &res, port);
  18086. return res.substr(0, res.find("\r\n"));
  18087. };
  18088. const char *accepted[] = {
  18089. "Host: localhost\r\n",
  18090. "Host: a.example:8080\r\n",
  18091. "Host: my_service\r\n",
  18092. "Host: [::1]:8080\r\n",
  18093. "Host: [fe80::1%25eth0]\r\n",
  18094. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18095. };
  18096. for (auto host_lines : accepted) {
  18097. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18098. }
  18099. const char *rejected[] = {
  18100. "Host: a.example\r\nHost: b.example\r\n",
  18101. "Host: a.example\r\nHost: a.example\r\n",
  18102. "Host: a@b.example\r\n",
  18103. "Host: a.example/b\r\n",
  18104. "Host: a.example\\b\r\n",
  18105. "Host: a.example?b\r\n",
  18106. "Host: a.example#b\r\n",
  18107. "Host: a.example b.example\r\n",
  18108. };
  18109. for (auto host_lines : rejected) {
  18110. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18111. << host_lines;
  18112. }
  18113. }
  18114. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18115. Server svr;
  18116. svr.Get("/", [](const Request &req, Response &res) {
  18117. EXPECT_EQ(2U, req.trailers.size());
  18118. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18119. // Denied
  18120. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18121. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18122. // Accepted
  18123. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18124. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18125. EXPECT_TRUE(req.has_trailer("X-World"));
  18126. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18127. res.set_content("ok", "text/plain");
  18128. });
  18129. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18130. auto se = detail::scope_exit([&] {
  18131. svr.stop();
  18132. t.join();
  18133. ASSERT_FALSE(svr.is_running());
  18134. });
  18135. svr.wait_until_ready();
  18136. const std::string req = "GET / HTTP/1.1\r\n"
  18137. "Transfer-Encoding: chunked\r\n"
  18138. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18139. "\r\n"
  18140. "0\r\n"
  18141. "Content-Length: 10\r\n"
  18142. "Host: internal.local\r\n"
  18143. "Content-Type: malicious/content\r\n"
  18144. "Cookie: any\r\n"
  18145. "Set-Cookie: any\r\n"
  18146. "X-Forwarded-For: attacker.com\r\n"
  18147. "X-Real-Ip: 1.1.1.1\r\n"
  18148. "X-Hello: hello\r\n"
  18149. "X-World: world\r\n"
  18150. "\r\n";
  18151. std::string res;
  18152. ASSERT_TRUE(send_request(1, req, &res));
  18153. }
  18154. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18155. // several field lines, and the combined value is what has to be parsed. A
  18156. // Trailer field split across lines therefore declares every name it lists;
  18157. // reading only the first line silently drops the trailers the later lines
  18158. // declare. The prohibited-trailer filter still applies to every line.
  18159. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18160. Server svr;
  18161. size_t observed_trailer_count = 0;
  18162. std::string observed_hello;
  18163. std::string observed_world;
  18164. bool observed_content_length = true;
  18165. svr.Get("/", [&](const Request &req, Response &res) {
  18166. observed_trailer_count = req.trailers.size();
  18167. observed_hello = req.get_trailer_value("X-Hello");
  18168. observed_world = req.get_trailer_value("X-World");
  18169. observed_content_length = req.has_trailer("Content-Length");
  18170. res.set_content("ok", "text/plain");
  18171. });
  18172. auto port = svr.bind_to_any_port(HOST);
  18173. thread t = thread([&]() { svr.listen_after_bind(); });
  18174. auto se = detail::scope_exit([&] {
  18175. svr.stop();
  18176. t.join();
  18177. ASSERT_FALSE(svr.is_running());
  18178. });
  18179. svr.wait_until_ready();
  18180. const std::string req = "GET / HTTP/1.1\r\n"
  18181. "Host: localhost\r\n"
  18182. "Transfer-Encoding: chunked\r\n"
  18183. "Trailer: X-Hello\r\n"
  18184. "Trailer: X-World, Content-Length\r\n"
  18185. "\r\n"
  18186. "0\r\n"
  18187. "X-Hello: hello\r\n"
  18188. "X-World: world\r\n"
  18189. "Content-Length: 10\r\n"
  18190. "\r\n";
  18191. std::string res;
  18192. ASSERT_TRUE(send_request(1, req, &res, port));
  18193. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18194. // Accepted: both field lines contribute to the declared set
  18195. EXPECT_EQ(2U, observed_trailer_count);
  18196. EXPECT_EQ(observed_hello, "hello");
  18197. EXPECT_EQ(observed_world, "world");
  18198. // Denied: a prohibited name stays prohibited on a later field line
  18199. EXPECT_FALSE(observed_content_length);
  18200. }
  18201. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18202. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18203. // unbounded run of fields that are never declared, because the counter would
  18204. // only advance for declared fields.
  18205. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18206. Server svr;
  18207. bool handler_called = false;
  18208. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18209. handler_called = true;
  18210. res.set_content("ok", "text/plain");
  18211. });
  18212. auto port = svr.bind_to_any_port(HOST);
  18213. thread t = thread([&]() { svr.listen_after_bind(); });
  18214. auto se = detail::scope_exit([&] {
  18215. svr.stop();
  18216. t.join();
  18217. ASSERT_FALSE(svr.is_running());
  18218. });
  18219. svr.wait_until_ready();
  18220. // Declare nothing, then send far more undeclared trailer fields than the
  18221. // header-count limit. Parsing must stop and reject the request rather than
  18222. // read every line.
  18223. std::string req = "GET / HTTP/1.1\r\n"
  18224. "Transfer-Encoding: chunked\r\n"
  18225. "\r\n"
  18226. "0\r\n";
  18227. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18228. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18229. }
  18230. req += "\r\n";
  18231. std::string res;
  18232. ASSERT_TRUE(send_request(1, req, &res, port));
  18233. // The request is rejected before the handler runs.
  18234. EXPECT_FALSE(handler_called);
  18235. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18236. }
  18237. // The set of declared trailer names is capped so a peer cannot grow it without
  18238. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18239. // declared past the cap is not honored, even if the field is actually sent.
  18240. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18241. Server svr;
  18242. // One name inside the cap and one past it, so the test tracks the cap rather
  18243. // than a fixed count.
  18244. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18245. const std::string within_cap_name = "X-T-0";
  18246. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18247. bool observed_within_cap = false;
  18248. bool observed_past_cap = false;
  18249. svr.Get("/", [&](const Request &req, Response &res) {
  18250. observed_within_cap = req.has_trailer(within_cap_name);
  18251. observed_past_cap = req.has_trailer(past_cap_name);
  18252. res.set_content("ok", "text/plain");
  18253. });
  18254. auto port = svr.bind_to_any_port(HOST);
  18255. thread t = thread([&]() { svr.listen_after_bind(); });
  18256. auto se = detail::scope_exit([&] {
  18257. svr.stop();
  18258. t.join();
  18259. ASSERT_FALSE(svr.is_running());
  18260. });
  18261. svr.wait_until_ready();
  18262. // Declare more trailer names than the cap in a single Trailer field, then
  18263. // actually send the first (within the cap) and the last (past it).
  18264. std::string trailer_decl = "Trailer: ";
  18265. for (int i = 0; i < declared_count; i++) {
  18266. if (i != 0) { trailer_decl += ", "; }
  18267. trailer_decl += "X-T-" + std::to_string(i);
  18268. }
  18269. trailer_decl += "\r\n";
  18270. const std::string req = "GET / HTTP/1.1\r\n"
  18271. "Host: localhost\r\n"
  18272. "Transfer-Encoding: chunked\r\n" +
  18273. trailer_decl +
  18274. "\r\n"
  18275. "0\r\n" +
  18276. within_cap_name + ": a\r\n" + past_cap_name +
  18277. ": b\r\n"
  18278. "\r\n";
  18279. std::string res;
  18280. ASSERT_TRUE(send_request(1, req, &res, port));
  18281. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18282. // A name within the cap is honored; one declared past the cap is dropped.
  18283. EXPECT_TRUE(observed_within_cap);
  18284. EXPECT_FALSE(observed_past_cap);
  18285. }
  18286. // A direct client that is not listed in trusted_proxies must not be able to
  18287. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18288. // the peer address on the actual TCP connection determines whether the
  18289. // header is honored.
  18290. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18291. Server svr;
  18292. // Deliberately does NOT include the loopback address the test client
  18293. // actually connects from, so the direct connection is not a trusted proxy.
  18294. svr.set_trusted_proxies({"203.0.113.66"});
  18295. std::string observed_remote_addr;
  18296. svr.Get("/ip", [&](const Request &req, Response &res) {
  18297. observed_remote_addr = req.remote_addr;
  18298. res.set_content("ok", "text/plain");
  18299. });
  18300. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18301. auto se = detail::scope_exit([&] {
  18302. svr.stop();
  18303. t.join();
  18304. ASSERT_FALSE(svr.is_running());
  18305. });
  18306. svr.wait_until_ready();
  18307. Client cli(HOST, PORT);
  18308. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18310. EXPECT_EQ(StatusCode::OK_200, res->status);
  18311. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18312. // ignored entirely and the real connection-level address retained.
  18313. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18314. observed_remote_addr == "127.0.0.1");
  18315. }
  18316. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18317. Server svr;
  18318. std::string observed_remote_addr;
  18319. std::string observed_xff;
  18320. svr.Get("/ip", [&](const Request &req, Response &res) {
  18321. observed_remote_addr = req.remote_addr;
  18322. observed_xff = req.get_header_value("X-Forwarded-For");
  18323. res.set_content("ok", "text/plain");
  18324. });
  18325. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18326. auto se = detail::scope_exit([&] {
  18327. svr.stop();
  18328. t.join();
  18329. ASSERT_FALSE(svr.is_running());
  18330. });
  18331. svr.wait_until_ready();
  18332. Client cli(HOST, PORT);
  18333. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18335. EXPECT_EQ(StatusCode::OK_200, res->status);
  18336. EXPECT_EQ(observed_xff, "203.0.113.66");
  18337. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18338. observed_remote_addr == "127.0.0.1");
  18339. }
  18340. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18341. Server svr;
  18342. svr.set_trusted_proxies({"203.0.113.66"});
  18343. std::string observed_remote_addr;
  18344. std::string observed_xff;
  18345. svr.Get("/ip", [&](const Request &req, Response &res) {
  18346. observed_remote_addr = req.remote_addr;
  18347. observed_xff = req.get_header_value("X-Forwarded-For");
  18348. res.set_content("ok", "text/plain");
  18349. });
  18350. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18351. auto se = detail::scope_exit([&] {
  18352. svr.stop();
  18353. t.join();
  18354. ASSERT_FALSE(svr.is_running());
  18355. });
  18356. svr.wait_until_ready();
  18357. Client cli(HOST, PORT);
  18358. auto res = cli.Get("/ip");
  18359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18360. EXPECT_EQ(StatusCode::OK_200, res->status);
  18361. EXPECT_EQ(observed_xff, "");
  18362. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18363. observed_remote_addr == "127.0.0.1");
  18364. }
  18365. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18366. Server svr;
  18367. // Include the loopback address the test client actually connects from, so
  18368. // the direct connection itself is recognized as the trusted proxy hop.
  18369. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18370. std::string observed_remote_addr;
  18371. std::string observed_xff;
  18372. svr.Get("/ip", [&](const Request &req, Response &res) {
  18373. observed_remote_addr = req.remote_addr;
  18374. observed_xff = req.get_header_value("X-Forwarded-For");
  18375. res.set_content("ok", "text/plain");
  18376. });
  18377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18378. auto se = detail::scope_exit([&] {
  18379. svr.stop();
  18380. t.join();
  18381. ASSERT_FALSE(svr.is_running());
  18382. });
  18383. svr.wait_until_ready();
  18384. Client cli(HOST, PORT);
  18385. auto res = cli.Get(
  18386. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18388. EXPECT_EQ(StatusCode::OK_200, res->status);
  18389. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18390. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18391. }
  18392. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18393. Server svr;
  18394. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18395. std::string observed_remote_addr;
  18396. std::string observed_xff;
  18397. svr.Get("/ip", [&](const Request &req, Response &res) {
  18398. observed_remote_addr = req.remote_addr;
  18399. observed_xff = req.get_header_value("X-Forwarded-For");
  18400. res.set_content("ok", "text/plain");
  18401. });
  18402. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18403. auto se = detail::scope_exit([&] {
  18404. svr.stop();
  18405. t.join();
  18406. ASSERT_FALSE(svr.is_running());
  18407. });
  18408. svr.wait_until_ready();
  18409. Client cli(HOST, PORT);
  18410. auto res = cli.Get(
  18411. "/ip",
  18412. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18414. EXPECT_EQ(StatusCode::OK_200, res->status);
  18415. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18416. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18417. }
  18418. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18419. Server svr;
  18420. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18421. std::string observed_remote_addr;
  18422. std::string observed_xff;
  18423. svr.Get("/ip", [&](const Request &req, Response &res) {
  18424. observed_remote_addr = req.remote_addr;
  18425. observed_xff = req.get_header_value("X-Forwarded-For");
  18426. res.set_content("ok", "text/plain");
  18427. });
  18428. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18429. auto se = detail::scope_exit([&] {
  18430. svr.stop();
  18431. t.join();
  18432. ASSERT_FALSE(svr.is_running());
  18433. });
  18434. svr.wait_until_ready();
  18435. Client cli(HOST, PORT);
  18436. auto res = cli.Get(
  18437. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18439. EXPECT_EQ(StatusCode::OK_200, res->status);
  18440. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18441. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18442. // and must not be selected.
  18443. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18444. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18445. }
  18446. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18447. Server svr;
  18448. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18449. std::string observed_remote_addr;
  18450. svr.Get("/ip", [&](const Request &req, Response &res) {
  18451. observed_remote_addr = req.remote_addr;
  18452. res.set_content("ok", "text/plain");
  18453. });
  18454. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18455. auto se = detail::scope_exit([&] {
  18456. svr.stop();
  18457. t.join();
  18458. ASSERT_FALSE(svr.is_running());
  18459. });
  18460. svr.wait_until_ready();
  18461. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18462. // a forged address and the trusted proxy's own address; the forged value must
  18463. // not win over the address the trusted proxy actually recorded.
  18464. Client cli(HOST, PORT);
  18465. auto res = cli.Get(
  18466. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18468. EXPECT_EQ(StatusCode::OK_200, res->status);
  18469. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18470. }
  18471. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18472. Server svr;
  18473. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18474. std::string observed_remote_addr;
  18475. std::string observed_xff;
  18476. svr.Get("/ip", [&](const Request &req, Response &res) {
  18477. observed_remote_addr = req.remote_addr;
  18478. observed_xff = req.get_header_value("X-Forwarded-For");
  18479. res.set_content("ok", "text/plain");
  18480. });
  18481. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18482. auto se = detail::scope_exit([&] {
  18483. svr.stop();
  18484. t.join();
  18485. ASSERT_FALSE(svr.is_running());
  18486. });
  18487. svr.wait_until_ready();
  18488. Client cli(HOST, PORT);
  18489. auto res = cli.Get(
  18490. "/ip",
  18491. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18493. EXPECT_EQ(StatusCode::OK_200, res->status);
  18494. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18495. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18496. }
  18497. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18498. Server svr;
  18499. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18500. std::string observed_remote_addr;
  18501. std::string observed_xff;
  18502. svr.Get("/ip", [&](const Request &req, Response &res) {
  18503. observed_remote_addr = req.remote_addr;
  18504. observed_xff = req.get_header_value("X-Forwarded-For");
  18505. res.set_content("ok", "text/plain");
  18506. });
  18507. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18508. auto se = detail::scope_exit([&] {
  18509. svr.stop();
  18510. t.join();
  18511. ASSERT_FALSE(svr.is_running());
  18512. });
  18513. svr.wait_until_ready();
  18514. std::string raw_req =
  18515. "GET /ip HTTP/1.1\r\n"
  18516. "Host: localhost\r\n"
  18517. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18518. "Connection: close\r\n"
  18519. "\r\n";
  18520. std::string out;
  18521. ASSERT_TRUE(send_request(5, raw_req, &out));
  18522. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18523. // Header parser trims surrounding whitespace of the header value
  18524. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18525. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18526. }
  18527. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18528. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18529. // their own X-Forwarded-For as a separate field line rather than extending the
  18530. // one the client sent, so every occurrence has to be taken into account.
  18531. // Reading only the first one hands back the address the client chose.
  18532. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18533. Server svr;
  18534. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18535. std::string observed_remote_addr;
  18536. size_t observed_xff_count = 0;
  18537. svr.Get("/ip", [&](const Request &req, Response &res) {
  18538. observed_remote_addr = req.remote_addr;
  18539. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18540. res.set_content("ok", "text/plain");
  18541. });
  18542. auto port = svr.bind_to_any_port(HOST);
  18543. thread t = thread([&]() { svr.listen_after_bind(); });
  18544. auto se = detail::scope_exit([&] {
  18545. svr.stop();
  18546. t.join();
  18547. ASSERT_FALSE(svr.is_running());
  18548. });
  18549. svr.wait_until_ready();
  18550. // The client supplies the first field line; the trusted proxy appends the
  18551. // address it observed as a second one.
  18552. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18553. "Host: localhost\r\n"
  18554. "X-Forwarded-For: 1.2.3.4\r\n"
  18555. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18556. "Connection: close\r\n"
  18557. "\r\n";
  18558. std::string out;
  18559. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18560. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18561. EXPECT_EQ(observed_xff_count, 2U);
  18562. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18563. // The same chain spread over one field line per hop derives the same client
  18564. // address, i.e. the split and the comma-joined representations agree.
  18565. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18566. "Host: localhost\r\n"
  18567. "X-Forwarded-For: 1.2.3.4\r\n"
  18568. "X-Forwarded-For: 198.51.100.23\r\n"
  18569. "X-Forwarded-For: 192.0.2.45\r\n"
  18570. "Connection: close\r\n"
  18571. "\r\n";
  18572. out.clear();
  18573. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18574. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18575. EXPECT_EQ(observed_xff_count, 3U);
  18576. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18577. }
  18578. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18579. // crash the server (it used to call front() on an empty vector inside
  18580. // get_client_ip). The connection-level remote address must be retained instead.
  18581. static void run_malformed_xff_test(const std::string &xff_value) {
  18582. Server svr;
  18583. svr.set_trusted_proxies({"192.0.2.45"});
  18584. std::string observed_remote_addr;
  18585. svr.Get("/ip", [&](const Request &req, Response &res) {
  18586. observed_remote_addr = req.remote_addr;
  18587. res.set_content("ok", "text/plain");
  18588. });
  18589. int port = 0;
  18590. thread t = thread([&]() {
  18591. port = svr.bind_to_any_port(HOST);
  18592. svr.listen_after_bind();
  18593. });
  18594. auto se = detail::scope_exit([&] {
  18595. svr.stop();
  18596. t.join();
  18597. ASSERT_FALSE(svr.is_running());
  18598. });
  18599. svr.wait_until_ready();
  18600. Client cli(HOST, port);
  18601. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18603. EXPECT_EQ(StatusCode::OK_200, res->status);
  18604. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18605. observed_remote_addr == "127.0.0.1");
  18606. }
  18607. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18608. run_malformed_xff_test("");
  18609. }
  18610. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18611. run_malformed_xff_test(",");
  18612. }
  18613. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18614. run_malformed_xff_test(", , ,");
  18615. }
  18616. // The same rule applies to Accept: a request whose acceptable types are spread
  18617. // over several field lines must be negotiated against all of them.
  18618. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18619. // case-insensitive connection options. Comparing the whole field value against
  18620. // one option misses a client that sends several of them, and misses every
  18621. // casing but the one written in the comparison.
  18622. //
  18623. // Sends req, reads the response, then reuses the same socket for a second
  18624. // request to find out whether the server kept the connection.
  18625. static void probe_connection_reuse(int port, const std::string &req,
  18626. bool *announced_close, bool *reusable) {
  18627. auto error = Error::Success;
  18628. auto sock = detail::create_client_socket(
  18629. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18630. /*connection_timeout_sec=*/5, 0,
  18631. /*read_timeout_sec=*/1, 0,
  18632. /*write_timeout_sec=*/5, 0, std::string(), error);
  18633. ASSERT_NE(sock, INVALID_SOCKET);
  18634. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18635. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18636. "Host: localhost\r\n"
  18637. "Connection: close\r\n"
  18638. "\r\n";
  18639. std::string first_response;
  18640. std::string second_response;
  18641. detail::process_client_socket(
  18642. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18643. [&](Stream &strm) {
  18644. if (strm.write(req.data(), req.size()) !=
  18645. static_cast<ssize_t>(req.size())) {
  18646. return false;
  18647. }
  18648. char buf[512];
  18649. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18650. // Headers plus the two-byte body of the handler below
  18651. while (reader.getline()) {
  18652. first_response += reader.ptr();
  18653. if (first_response.find("ok") != std::string::npos) { break; }
  18654. }
  18655. if (strm.write(second.data(), second.size()) !=
  18656. static_cast<ssize_t>(second.size())) {
  18657. return true;
  18658. }
  18659. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18660. while (reader2.getline()) {
  18661. second_response += reader2.ptr();
  18662. if (second_response.find("ok") != std::string::npos) { break; }
  18663. }
  18664. return true;
  18665. });
  18666. *announced_close =
  18667. first_response.find("Connection: close") != std::string::npos;
  18668. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18669. }
  18670. class ConnectionTokenTest : public ::testing::Test {
  18671. protected:
  18672. void SetUp() override {
  18673. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18674. res.set_content("ok", "text/plain");
  18675. });
  18676. port_ = svr_.bind_to_any_port(HOST);
  18677. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18678. svr_.wait_until_ready();
  18679. }
  18680. void TearDown() override {
  18681. svr_.stop();
  18682. if (thread_.joinable()) { thread_.join(); }
  18683. }
  18684. Server svr_;
  18685. int port_ = 0;
  18686. thread thread_;
  18687. };
  18688. // "close" alongside another option still closes the connection, and the
  18689. // response says so rather than leaving the peer to discover it.
  18690. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18691. bool announced_close = false;
  18692. bool reusable = true;
  18693. probe_connection_reuse(port_,
  18694. "GET /keepalive HTTP/1.1\r\n"
  18695. "Host: localhost\r\n"
  18696. "Connection: keep-alive, close\r\n"
  18697. "\r\n",
  18698. &announced_close, &reusable);
  18699. EXPECT_TRUE(announced_close);
  18700. EXPECT_FALSE(reusable);
  18701. }
  18702. // "close" split over two field lines is the same list, so it is honored too.
  18703. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18704. bool announced_close = false;
  18705. bool reusable = true;
  18706. probe_connection_reuse(port_,
  18707. "GET /keepalive HTTP/1.1\r\n"
  18708. "Host: localhost\r\n"
  18709. "Connection: keep-alive\r\n"
  18710. "Connection: close\r\n"
  18711. "\r\n",
  18712. &announced_close, &reusable);
  18713. EXPECT_TRUE(announced_close);
  18714. EXPECT_FALSE(reusable);
  18715. }
  18716. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18717. // keep-alive in the spelling everyone actually sends keeps its connection.
  18718. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18719. bool announced_close = false;
  18720. bool reusable = false;
  18721. probe_connection_reuse(port_,
  18722. "GET /keepalive HTTP/1.0\r\n"
  18723. "Host: localhost\r\n"
  18724. "Connection: keep-alive\r\n"
  18725. "\r\n",
  18726. &announced_close, &reusable);
  18727. EXPECT_FALSE(announced_close);
  18728. EXPECT_TRUE(reusable);
  18729. }
  18730. // A token the value merely contains is not the token itself.
  18731. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18732. bool announced_close = false;
  18733. bool reusable = false;
  18734. probe_connection_reuse(port_,
  18735. "GET /keepalive HTTP/1.1\r\n"
  18736. "Host: localhost\r\n"
  18737. "Connection: notclose\r\n"
  18738. "\r\n",
  18739. &announced_close, &reusable);
  18740. EXPECT_FALSE(announced_close);
  18741. EXPECT_TRUE(reusable);
  18742. }
  18743. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18744. Server svr;
  18745. std::vector<std::string> observed_types;
  18746. svr.Get("/", [&](const Request &req, Response &res) {
  18747. observed_types = req.accept_content_types;
  18748. res.set_content("ok", "text/plain");
  18749. });
  18750. auto port = svr.bind_to_any_port(HOST);
  18751. thread t = thread([&]() { svr.listen_after_bind(); });
  18752. auto se = detail::scope_exit([&] {
  18753. svr.stop();
  18754. t.join();
  18755. ASSERT_FALSE(svr.is_running());
  18756. });
  18757. svr.wait_until_ready();
  18758. Client cli(HOST, port);
  18759. Headers headers;
  18760. headers.emplace("Accept", "text/plain;q=0.5");
  18761. headers.emplace("Accept", "application/json");
  18762. auto res = cli.Get("/", headers);
  18763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18764. EXPECT_EQ(StatusCode::OK_200, res->status);
  18765. // Sorted by q-value, so the second field line's type comes first
  18766. ASSERT_EQ(2U, observed_types.size());
  18767. EXPECT_EQ("application/json", observed_types[0]);
  18768. EXPECT_EQ("text/plain", observed_types[1]);
  18769. }
  18770. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18771. // empty field line must not contribute a bare comma to the combined value.
  18772. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18773. Server svr;
  18774. std::vector<std::string> observed_types;
  18775. svr.Get("/", [&](const Request &req, Response &res) {
  18776. observed_types = req.accept_content_types;
  18777. res.set_content("ok", "text/plain");
  18778. });
  18779. auto port = svr.bind_to_any_port(HOST);
  18780. thread t = thread([&]() { svr.listen_after_bind(); });
  18781. auto se = detail::scope_exit([&] {
  18782. svr.stop();
  18783. t.join();
  18784. ASSERT_FALSE(svr.is_running());
  18785. });
  18786. svr.wait_until_ready();
  18787. // Empty first field line, then a real one
  18788. std::string raw_req = "GET / HTTP/1.1\r\n"
  18789. "Host: localhost\r\n"
  18790. "Accept:\r\n"
  18791. "Accept: application/json\r\n"
  18792. "Connection: close\r\n"
  18793. "\r\n";
  18794. std::string out;
  18795. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18796. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18797. ASSERT_EQ(1U, observed_types.size());
  18798. EXPECT_EQ("application/json", observed_types[0]);
  18799. }
  18800. // The skip in get_combined_header_value() is what keeps an empty field line
  18801. // from contributing a bare comma. Only a trailing empty field line exercises
  18802. // it: a leading one is already covered by the "combined is still empty" check,
  18803. // and parse_accept_header() now ignores the empty element either way, so the
  18804. // request-level test above can no longer tell the two apart.
  18805. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18806. Headers headers;
  18807. headers.emplace("Accept", "text/html");
  18808. headers.emplace("Accept", "");
  18809. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18810. headers.clear();
  18811. headers.emplace("Accept", "");
  18812. headers.emplace("Accept", "application/json");
  18813. EXPECT_EQ("application/json",
  18814. detail::get_combined_header_value(headers, "Accept"));
  18815. }
  18816. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18817. // An encoding offered on a later Accept-Encoding field line is still offered.
  18818. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18819. Server svr;
  18820. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18821. res.set_content(std::string(1024, 'x'), "text/plain");
  18822. });
  18823. auto port = svr.bind_to_any_port(HOST);
  18824. thread t = thread([&]() { svr.listen_after_bind(); });
  18825. auto se = detail::scope_exit([&] {
  18826. svr.stop();
  18827. t.join();
  18828. ASSERT_FALSE(svr.is_running());
  18829. });
  18830. svr.wait_until_ready();
  18831. Client cli(HOST, port);
  18832. cli.set_decompress(false);
  18833. Headers headers;
  18834. headers.emplace("Accept-Encoding", "identity");
  18835. headers.emplace("Accept-Encoding", "gzip");
  18836. auto res = cli.Get("/", headers);
  18837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18838. EXPECT_EQ(StatusCode::OK_200, res->status);
  18839. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18840. }
  18841. #endif
  18842. #ifndef _WIN32
  18843. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18844. Server svr;
  18845. svr.Post("/post", [&](const Request &req, Response &res) {
  18846. res.set_content(req.body, "text/plain");
  18847. });
  18848. svr.Put("/put", [&](const Request &req, Response &res) {
  18849. res.set_content(req.body, "text/plain");
  18850. });
  18851. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18852. res.set_content(req.body, "text/plain");
  18853. });
  18854. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18855. res.set_content(req.body, "text/plain");
  18856. });
  18857. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18858. auto se = detail::scope_exit([&] {
  18859. svr.stop();
  18860. t.join();
  18861. ASSERT_FALSE(svr.is_running());
  18862. });
  18863. svr.wait_until_ready();
  18864. std::string resp;
  18865. // POST without Content-Length
  18866. ASSERT_TRUE(send_request(5,
  18867. "POST /post HTTP/1.1\r\n"
  18868. "Host: localhost\r\n"
  18869. "Connection: close\r\n"
  18870. "\r\n",
  18871. &resp));
  18872. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18873. // PUT without Content-Length
  18874. resp.clear();
  18875. ASSERT_TRUE(send_request(5,
  18876. "PUT /put HTTP/1.1\r\n"
  18877. "Host: localhost\r\n"
  18878. "Connection: close\r\n"
  18879. "\r\n",
  18880. &resp));
  18881. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18882. // PATCH without Content-Length
  18883. resp.clear();
  18884. ASSERT_TRUE(send_request(5,
  18885. "PATCH /patch HTTP/1.1\r\n"
  18886. "Host: localhost\r\n"
  18887. "Connection: close\r\n"
  18888. "\r\n",
  18889. &resp));
  18890. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18891. // DELETE without Content-Length
  18892. resp.clear();
  18893. ASSERT_TRUE(send_request(5,
  18894. "DELETE /delete HTTP/1.1\r\n"
  18895. "Host: localhost\r\n"
  18896. "Connection: close\r\n"
  18897. "\r\n",
  18898. &resp));
  18899. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18900. }
  18901. #endif
  18902. //==============================================================================
  18903. // open_stream() Tests
  18904. //==============================================================================
  18905. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18906. std::string result;
  18907. char buf[8192];
  18908. ssize_t n;
  18909. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18910. result.append(buf, static_cast<size_t>(n));
  18911. }
  18912. return result;
  18913. }
  18914. // Mock stream for unit tests
  18915. class MockStream : public Stream {
  18916. public:
  18917. std::string data;
  18918. size_t pos = 0;
  18919. ssize_t error_after = -1; // -1 = no error
  18920. explicit MockStream(const std::string &d, ssize_t err = -1)
  18921. : data(d), error_after(err) {}
  18922. bool is_readable() const override { return true; }
  18923. bool wait_readable() const override { return true; }
  18924. bool wait_writable() const override { return true; }
  18925. ssize_t read(char *ptr, size_t size) override {
  18926. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18927. if (pos >= data.size()) return 0;
  18928. size_t limit =
  18929. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18930. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18931. std::memcpy(ptr, data.data() + pos, to_read);
  18932. pos += to_read;
  18933. return static_cast<ssize_t>(to_read);
  18934. }
  18935. ssize_t write(const char *, size_t) override { return -1; }
  18936. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18937. ip = "127.0.0.1";
  18938. port = 0;
  18939. }
  18940. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18941. ip = "127.0.0.1";
  18942. port = 0;
  18943. }
  18944. socket_t socket() const override { return INVALID_SOCKET; }
  18945. time_t duration() const override { return 0; }
  18946. };
  18947. TEST(StreamHandleTest, Basic) {
  18948. ClientImpl::StreamHandle handle;
  18949. EXPECT_FALSE(handle.is_valid());
  18950. handle.response = detail::make_unique<Response>();
  18951. handle.error = Error::Connection;
  18952. EXPECT_FALSE(handle.is_valid());
  18953. handle.error = Error::Success;
  18954. EXPECT_TRUE(handle.is_valid());
  18955. }
  18956. TEST(BodyReaderTest, Basic) {
  18957. MockStream stream("Hello, World!");
  18958. detail::BodyReader reader;
  18959. reader.stream = &stream;
  18960. reader.content_length = 13;
  18961. char buf[32];
  18962. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18963. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18964. EXPECT_TRUE(reader.eof);
  18965. }
  18966. TEST(BodyReaderTest, NoStream) {
  18967. detail::BodyReader reader;
  18968. char buf[32];
  18969. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18970. EXPECT_EQ(Error::Connection, reader.last_error);
  18971. }
  18972. TEST(BodyReaderTest, Error) {
  18973. MockStream stream("Hello, World!", 5);
  18974. detail::BodyReader reader;
  18975. reader.stream = &stream;
  18976. reader.content_length = 13;
  18977. char buf[32];
  18978. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18979. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18980. EXPECT_EQ(Error::Read, reader.last_error);
  18981. }
  18982. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18983. // Mock-based StreamHandle tests relying on private internals are removed.
  18984. class OpenStreamTest : public ::testing::Test {
  18985. protected:
  18986. void SetUp() override {
  18987. svr_.Get("/hello", [](const Request &, Response &res) {
  18988. res.set_content("Hello World!", "text/plain");
  18989. });
  18990. svr_.Get("/large", [](const Request &, Response &res) {
  18991. res.set_content(std::string(10000, 'X'), "text/plain");
  18992. });
  18993. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18994. res.set_content("Hello World!", "image/jpeg");
  18995. res.set_header("Content-Encoding", "UTF-8");
  18996. });
  18997. svr_.Get("/chunked", [](const Request &, Response &res) {
  18998. res.set_chunked_content_provider("text/plain",
  18999. [](size_t offset, DataSink &sink) {
  19000. if (offset < 15) {
  19001. sink.write("chunk", 5);
  19002. return true;
  19003. }
  19004. sink.done();
  19005. return true;
  19006. });
  19007. });
  19008. svr_.Get("/compressible", [](const Request &, Response &res) {
  19009. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19010. DataSink &sink) {
  19011. if (offset < 100 * 1024) {
  19012. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19013. sink.write(chunk.data(), chunk.size());
  19014. return true;
  19015. }
  19016. sink.done();
  19017. return true;
  19018. });
  19019. });
  19020. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19021. [](const Request & /*req*/, Response &res) {
  19022. auto i = new int(0);
  19023. res.set_header("Trailer", "Content-Length, X-Allowed");
  19024. res.set_chunked_content_provider(
  19025. "text/plain",
  19026. [i](size_t /*offset*/, DataSink &sink) {
  19027. switch (*i) {
  19028. case 0: sink.os << "123"; break;
  19029. case 1: sink.os << "456"; break;
  19030. case 2: sink.os << "789"; break;
  19031. case 3: {
  19032. sink.done_with_trailer(
  19033. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19034. } break;
  19035. }
  19036. (*i)++;
  19037. return true;
  19038. },
  19039. [i](bool success) {
  19040. EXPECT_TRUE(success);
  19041. delete i;
  19042. });
  19043. });
  19044. // Echo headers endpoint for header-related tests
  19045. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19046. std::string body;
  19047. for (const auto &h : req.headers) {
  19048. body.append(h.first);
  19049. body.push_back(':');
  19050. body.append(h.second);
  19051. body.push_back('\n');
  19052. }
  19053. res.set_content(body, "text/plain");
  19054. });
  19055. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19056. std::string body;
  19057. for (const auto &h : req.headers) {
  19058. body.append(h.first);
  19059. body.push_back(':');
  19060. body.append(h.second);
  19061. body.push_back('\n');
  19062. }
  19063. res.set_content(body, "text/plain");
  19064. });
  19065. port_ = svr_.bind_to_any_port("127.0.0.1");
  19066. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19067. svr_.wait_until_ready();
  19068. }
  19069. void TearDown() override {
  19070. svr_.stop();
  19071. if (thread_.joinable()) thread_.join();
  19072. }
  19073. Server svr_;
  19074. std::thread thread_;
  19075. int port_ = 0;
  19076. };
  19077. TEST_F(OpenStreamTest, Basic) {
  19078. Client cli("127.0.0.1", port_);
  19079. auto handle = cli.open_stream("GET", "/hello");
  19080. EXPECT_TRUE(handle.is_valid());
  19081. EXPECT_EQ("Hello World!", read_all(handle));
  19082. }
  19083. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19084. Client cli("127.0.0.1", port_);
  19085. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19086. ASSERT_TRUE(handle.is_valid());
  19087. EXPECT_EQ("Hello World!", read_all(handle));
  19088. }
  19089. TEST_F(OpenStreamTest, SmallBuffer) {
  19090. Client cli("127.0.0.1", port_);
  19091. auto handle = cli.open_stream("GET", "/hello");
  19092. std::string result;
  19093. char buf[4];
  19094. ssize_t n;
  19095. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19096. result.append(buf, static_cast<size_t>(n));
  19097. EXPECT_EQ("Hello World!", result);
  19098. }
  19099. TEST_F(OpenStreamTest, DefaultHeaders) {
  19100. Client cli("127.0.0.1", port_);
  19101. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19102. {
  19103. auto handle = cli.open_stream("GET", "/echo-headers");
  19104. ASSERT_TRUE(handle.is_valid());
  19105. auto body = read_all(handle);
  19106. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19107. std::string::npos);
  19108. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19109. std::string::npos);
  19110. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19111. }
  19112. // open_stream POST with body and no explicit content_type should NOT add
  19113. // text/plain Content-Type (behavior differs from non-streaming path), but
  19114. // should include Content-Length
  19115. {
  19116. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19117. ASSERT_TRUE(handle.is_valid());
  19118. auto body = read_all(handle);
  19119. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19120. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19121. }
  19122. // open_stream POST with explicit Content-Type should preserve it
  19123. {
  19124. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19125. {{"Content-Type", "application/custom"}},
  19126. "{}", "application/custom");
  19127. ASSERT_TRUE(handle.is_valid());
  19128. auto body = read_all(handle);
  19129. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19130. }
  19131. // User-specified User-Agent must not be overwritten for stream API
  19132. {
  19133. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19134. {{"User-Agent", "MyAgent/1.2"}});
  19135. ASSERT_TRUE(handle.is_valid());
  19136. auto body = read_all(handle);
  19137. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19138. }
  19139. }
  19140. TEST_F(OpenStreamTest, Large) {
  19141. Client cli("127.0.0.1", port_);
  19142. auto handle = cli.open_stream("GET", "/large");
  19143. EXPECT_EQ(10000u, read_all(handle).size());
  19144. }
  19145. TEST_F(OpenStreamTest, ConnectionError) {
  19146. Client cli("127.0.0.1", 9999);
  19147. auto handle = cli.open_stream("GET", "/hello");
  19148. EXPECT_FALSE(handle.is_valid());
  19149. }
  19150. TEST_F(OpenStreamTest, Chunked) {
  19151. Client cli("127.0.0.1", port_);
  19152. auto handle = cli.open_stream("GET", "/chunked");
  19153. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19154. "Transfer-Encoding") == "chunked");
  19155. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19156. }
  19157. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19158. Client cli("127.0.0.1", port_);
  19159. auto handle =
  19160. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19161. ASSERT_TRUE(handle.is_valid());
  19162. // Consume body to allow trailers to be received/parsed
  19163. auto body = read_all(handle);
  19164. // Explicitly parse trailers (ensure trailers are available for assertion)
  19165. handle.parse_trailers_if_needed();
  19166. EXPECT_EQ(std::string("123456789"), body);
  19167. // The response should include a Trailer header declaring both names
  19168. ASSERT_TRUE(handle.response);
  19169. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19170. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19171. handle.response->get_header_value("Trailer"));
  19172. // Prohibited trailer must not be present
  19173. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19174. // Allowed trailer should be present
  19175. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19176. EXPECT_EQ(std::string("yes"),
  19177. handle.response->get_trailer_value("X-Allowed"));
  19178. // Verify trailers are NOT present as regular headers
  19179. EXPECT_EQ(std::string(""),
  19180. handle.response->get_header_value("Content-Length"));
  19181. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19182. }
  19183. // Accepts one connection on an OS-assigned port, which it hands over through
  19184. // port_promise, reads the request head and sends back response. after_send,
  19185. // if given, runs on the connection before it is closed.
  19186. static std::thread
  19187. serve_single_response(std::promise<int> &port_promise,
  19188. const std::string &response,
  19189. std::function<void(socket_t)> after_send = nullptr) {
  19190. return std::thread([&port_promise, response, after_send] {
  19191. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19192. default_socket_options(srv);
  19193. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19194. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19195. sockaddr_in addr{};
  19196. addr.sin_family = AF_INET;
  19197. addr.sin_port = htons(0); // Let OS assign a free port
  19198. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19199. int opt = 1;
  19200. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19201. #ifdef _WIN32
  19202. reinterpret_cast<const char *>(&opt),
  19203. #else
  19204. &opt,
  19205. #endif
  19206. sizeof(opt));
  19207. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19208. ::listen(srv, 1) != 0) {
  19209. port_promise.set_value(-1);
  19210. detail::close_socket(srv);
  19211. return;
  19212. }
  19213. socklen_t addr_len = sizeof(addr);
  19214. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19215. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19216. sockaddr_in cli_addr{};
  19217. socklen_t cli_len = sizeof(cli_addr);
  19218. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19219. if (cli != INVALID_SOCKET) {
  19220. // Read the complete HTTP request (until the blank line that terminates
  19221. // headers) before sending the response. If the server closes the socket
  19222. // while the client's request data is still unread in the kernel receive
  19223. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19224. // connection on both sides: it discards the client's receive buffer
  19225. // (which already holds our response) and causes any in-progress write on
  19226. // the client to fail with ECONNRESET. Reading all request data first
  19227. // ensures close() emits a graceful FIN.
  19228. {
  19229. char rbuf[256];
  19230. std::string req;
  19231. while (req.find("\r\n\r\n") == std::string::npos) {
  19232. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19233. if (n <= 0) { break; }
  19234. req.append(rbuf, static_cast<size_t>(n));
  19235. }
  19236. }
  19237. ::send(cli,
  19238. #ifdef _WIN32
  19239. static_cast<const char *>(response.c_str()),
  19240. static_cast<int>(response.size()),
  19241. #else
  19242. response.c_str(), response.size(),
  19243. #endif
  19244. 0);
  19245. if (after_send) { after_send(cli); }
  19246. detail::close_socket(cli);
  19247. }
  19248. detail::close_socket(srv);
  19249. });
  19250. }
  19251. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19252. #ifndef _WIN32
  19253. signal(SIGPIPE, SIG_IGN);
  19254. #endif
  19255. std::promise<int> port_promise;
  19256. auto port_future = port_promise.get_future();
  19257. auto server_thread =
  19258. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19259. "Content-Type: text/plain\r\n"
  19260. "Content-Length: not-a-number\r\n"
  19261. "Connection: close\r\n"
  19262. "\r\n"
  19263. "hello");
  19264. auto port = port_future.get();
  19265. ASSERT_GT(port, 0);
  19266. Client cli("127.0.0.1", port);
  19267. auto handle = cli.open_stream("GET", "/");
  19268. EXPECT_FALSE(handle.is_valid());
  19269. server_thread.join();
  19270. }
  19271. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19272. #ifndef _WIN32
  19273. signal(SIGPIPE, SIG_IGN);
  19274. #endif
  19275. std::promise<int> port_promise;
  19276. auto port_future = port_promise.get_future();
  19277. auto server_thread = serve_single_response(
  19278. port_promise, "HTTP/1.1 200 OK\r\n"
  19279. "Content-Type: text/plain\r\n"
  19280. "Content-Length: 99999999999999999999999999\r\n"
  19281. "Connection: close\r\n"
  19282. "\r\n"
  19283. "hello");
  19284. auto port = port_future.get();
  19285. ASSERT_GT(port, 0);
  19286. // Historically std::stoull would throw std::out_of_range here and crash
  19287. // the process, then parsing silently clamped to a bogus framing length and
  19288. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19289. // so the stream fails to open, matching the not-a-number case above. The
  19290. // process still must NOT terminate.
  19291. Client cli("127.0.0.1", port);
  19292. auto handle = cli.open_stream("GET", "/");
  19293. EXPECT_FALSE(handle.is_valid());
  19294. server_thread.join();
  19295. }
  19296. // Serves `response` to the single request `fn` makes with a fresh client.
  19297. template <typename Fn>
  19298. static void with_single_response(const std::string &response, Fn fn) {
  19299. #ifndef _WIN32
  19300. signal(SIGPIPE, SIG_IGN);
  19301. #endif
  19302. std::promise<int> port_promise;
  19303. auto port_future = port_promise.get_future();
  19304. auto server_thread = serve_single_response(port_promise, response);
  19305. auto se = detail::scope_exit([&] { server_thread.join(); });
  19306. auto port = port_future.get();
  19307. ASSERT_GT(port, 0);
  19308. Client cli("127.0.0.1", port);
  19309. fn(cli);
  19310. }
  19311. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19312. const char *responses[] = {
  19313. "HTTP/1.1 103 Early Hints\r\n"
  19314. "Link: </style.css>; rel=preload\r\n"
  19315. "\r\n"
  19316. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19317. "HTTP/1.1 100 Continue\r\n"
  19318. "X-Note: interim\r\n"
  19319. "\r\n"
  19320. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19321. };
  19322. for (auto response : responses) {
  19323. with_single_response(response, [](Client &cli) {
  19324. auto res = cli.Get("/");
  19325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19326. EXPECT_EQ(StatusCode::OK_200, res->status);
  19327. EXPECT_EQ("ok", res->body);
  19328. });
  19329. }
  19330. }
  19331. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19332. #ifndef _WIN32
  19333. signal(SIGPIPE, SIG_IGN);
  19334. #endif
  19335. // The server answers the head without asking for the body. Bytes it then
  19336. // reads on the connection would be taken for the body the request declared.
  19337. auto closed_by_client = false;
  19338. std::promise<int> port_promise;
  19339. auto server_thread = serve_single_response(
  19340. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19341. [&](socket_t sock) {
  19342. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19343. char buf[256];
  19344. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19345. });
  19346. Client cli("127.0.0.1", port_promise.get_future().get());
  19347. cli.set_keep_alive(true);
  19348. cli.set_read_timeout(1, 0);
  19349. // Long enough for the client to send Expect: 100-continue.
  19350. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19352. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19353. cli.Get("/second");
  19354. server_thread.join();
  19355. EXPECT_TRUE(closed_by_client);
  19356. }
  19357. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19358. // Long enough for the client to send Expect: 100-continue
  19359. with_single_response(
  19360. "HTTP/1.1 103 Early Hints\r\n"
  19361. "Link: </style.css>; rel=preload\r\n"
  19362. "\r\n"
  19363. "HTTP/1.1 401 Unauthorized\r\n"
  19364. "Content-Length: 0\r\n\r\n",
  19365. [](Client &cli) {
  19366. cli.set_read_timeout(2, 0);
  19367. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19369. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19370. });
  19371. }
  19372. #ifdef CPPHTTPLIB_SSL_ENABLED
  19373. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19374. #ifndef _WIN32
  19375. signal(SIGPIPE, SIG_IGN);
  19376. #endif
  19377. auto reused = false;
  19378. std::promise<int> port_promise;
  19379. auto server_thread = serve_single_response(
  19380. port_promise,
  19381. "HTTP/1.1 401 Unauthorized\r\n"
  19382. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19383. "Content-Length: 0\r\n\r\n",
  19384. [&](socket_t sock) {
  19385. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19386. char buf[256];
  19387. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19388. });
  19389. Client cli("127.0.0.1", port_promise.get_future().get());
  19390. cli.set_keep_alive(true);
  19391. cli.set_digest_auth("user", "pass");
  19392. cli.set_read_timeout(1, 0);
  19393. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19394. server_thread.join();
  19395. EXPECT_FALSE(reused);
  19396. }
  19397. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19398. // Any other answer to CONNECT would read as the origin's response.
  19399. struct {
  19400. const char *response;
  19401. bool passed_on;
  19402. } cases[] = {
  19403. {"HTTP/1.1 201 Created\r\n"
  19404. "Set-Cookie: session=from-proxy\r\n"
  19405. "Content-Length: 0\r\n\r\n",
  19406. false},
  19407. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19408. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19409. "Content-Length: 0\r\n\r\n",
  19410. true},
  19411. };
  19412. for (const auto &c : cases) {
  19413. std::promise<int> port_promise;
  19414. auto server_thread = serve_single_response(port_promise, c.response);
  19415. SSLClient cli("example.com", 443);
  19416. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19417. auto res = cli.Get("/");
  19418. server_thread.join();
  19419. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19420. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19421. if (res) {
  19422. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19423. }
  19424. }
  19425. }
  19426. #endif
  19427. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19428. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19429. // the chunked coding and drop Content-Length, so a front-end that trusts
  19430. // Content-Length would disagree about where the body ends (response
  19431. // smuggling). The client must reject such a response.
  19432. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19433. for (const char *te : {"chunked", "gzip, chunked"}) {
  19434. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19435. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19436. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19437. "5\r\nhello\r\n0\r\n\r\n";
  19438. with_single_response(response, [&](Client &cli) {
  19439. auto res = cli.Get("/");
  19440. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19441. EXPECT_EQ(Error::Read, res.error()) << te;
  19442. });
  19443. with_single_response(response, [&](Client &cli) {
  19444. auto handle = cli.open_stream("GET", "/");
  19445. EXPECT_FALSE(handle.is_valid()) << te;
  19446. EXPECT_EQ(Error::Read, handle.error) << te;
  19447. });
  19448. }
  19449. }
  19450. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19451. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19452. // closing the connection (unlike a request, which must be rejected).
  19453. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19454. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19455. "Transfer-Encoding: chunked\r\n"
  19456. "Connection: close\r\n"
  19457. "\r\n"
  19458. "5\r\nhello\r\n0\r\n\r\n",
  19459. "HTTP/1.1 200 OK\r\n"
  19460. "Transfer-Encoding: gzip\r\n"
  19461. "Connection: close\r\n"
  19462. "\r\n"
  19463. "hello"}) {
  19464. with_single_response(response, [&](Client &cli) {
  19465. auto res = cli.Get("/");
  19466. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19467. EXPECT_EQ("hello", res->body);
  19468. });
  19469. with_single_response(response, [&](Client &cli) {
  19470. auto handle = cli.open_stream("GET", "/");
  19471. ASSERT_TRUE(handle.is_valid()) << response;
  19472. EXPECT_EQ("hello", read_all(handle));
  19473. });
  19474. }
  19475. }
  19476. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19477. // framing headers describe nothing to read and must not be rejected.
  19478. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19479. const std::string framing = "Content-Length: 5\r\n"
  19480. "Transfer-Encoding: chunked\r\n"
  19481. "Connection: close\r\n"
  19482. "\r\n";
  19483. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19484. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19485. });
  19486. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19487. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19488. });
  19489. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19490. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19491. with_single_response(response, [&](Client &cli) {
  19492. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19493. });
  19494. with_single_response(response, [&](Client &cli) {
  19495. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19496. });
  19497. }
  19498. }
  19499. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19500. // response, is faulty framing, so the connection is not reused after it.
  19501. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19502. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19503. "Content-Length: 0\r\n"
  19504. "Transfer-Encoding: chunked\r\n"
  19505. "\r\n"
  19506. "5\r\nhello\r\n0\r\n\r\n",
  19507. "HTTP/1.0 200 Connection established\r\n"
  19508. "Connection: keep-alive\r\n"
  19509. "Transfer-Encoding: chunked\r\n"
  19510. "\r\n"
  19511. "5\r\nhello\r\n0\r\n\r\n"}) {
  19512. with_single_response(response, [&](Client &cli) {
  19513. cli.set_keep_alive(true);
  19514. auto res = cli.Get("/");
  19515. ASSERT_TRUE(res) << response;
  19516. EXPECT_EQ("hello", res->body);
  19517. EXPECT_FALSE(cli.is_socket_open()) << response;
  19518. });
  19519. }
  19520. }
  19521. // A payload max length of 0 means no limit, however the body is framed.
  19522. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19523. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19524. "Transfer-Encoding: chunked\r\n"
  19525. "\r\n"
  19526. "5\r\nhello\r\n0\r\n\r\n",
  19527. "HTTP/1.1 200 OK\r\n"
  19528. "Connection: close\r\n"
  19529. "\r\n"
  19530. "hello"}) {
  19531. with_single_response(response, [&](Client &cli) {
  19532. cli.set_payload_max_length(0);
  19533. auto res = cli.Get("/");
  19534. ASSERT_TRUE(res) << response;
  19535. EXPECT_EQ("hello", res->body) << response;
  19536. });
  19537. }
  19538. }
  19539. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19540. Server svr;
  19541. svr.set_payload_max_length(0);
  19542. svr.Post("/echo", [](const Request &req, Response &res) {
  19543. res.set_content(req.body, "text/plain");
  19544. });
  19545. auto port = svr.bind_to_any_port(HOST);
  19546. thread t = thread([&] { svr.listen_after_bind(); });
  19547. auto se = detail::scope_exit([&] {
  19548. svr.stop();
  19549. t.join();
  19550. ASSERT_FALSE(svr.is_running());
  19551. });
  19552. svr.wait_until_ready();
  19553. Client cli(HOST, port);
  19554. auto res = cli.Post(
  19555. "/echo",
  19556. [](size_t /*offset*/, DataSink &sink) {
  19557. sink.write("hello", 5);
  19558. sink.done();
  19559. return true;
  19560. },
  19561. "text/plain");
  19562. ASSERT_TRUE(res);
  19563. EXPECT_EQ(StatusCode::OK_200, res->status);
  19564. EXPECT_EQ("hello", res->body);
  19565. }
  19566. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19567. TEST_F(OpenStreamTest, Gzip) {
  19568. Client cli("127.0.0.1", port_);
  19569. auto handle = cli.open_stream("GET", "/compressible", {},
  19570. {{"Accept-Encoding", "gzip"}});
  19571. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19572. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19573. }
  19574. #endif
  19575. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19576. TEST_F(OpenStreamTest, Brotli) {
  19577. Client cli("127.0.0.1", port_);
  19578. auto handle =
  19579. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19580. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19581. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19582. }
  19583. #endif
  19584. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19585. TEST_F(OpenStreamTest, Zstd) {
  19586. Client cli("127.0.0.1", port_);
  19587. auto handle = cli.open_stream("GET", "/compressible", {},
  19588. {{"Accept-Encoding", "zstd"}});
  19589. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19590. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19591. }
  19592. #endif
  19593. #ifdef CPPHTTPLIB_SSL_ENABLED
  19594. class SSLOpenStreamTest : public ::testing::Test {
  19595. protected:
  19596. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19597. void SetUp() override {
  19598. svr_.Get("/hello", [](const Request &, Response &res) {
  19599. res.set_content("Hello SSL World!", "text/plain");
  19600. });
  19601. svr_.Get("/chunked", [](const Request &, Response &res) {
  19602. res.set_chunked_content_provider("text/plain",
  19603. [](size_t offset, DataSink &sink) {
  19604. if (offset < 15) {
  19605. sink.write("chunk", 5);
  19606. return true;
  19607. }
  19608. sink.done();
  19609. return true;
  19610. });
  19611. });
  19612. svr_.Post("/echo", [](const Request &req, Response &res) {
  19613. res.set_content(req.body, req.get_header_value("Content-Type"));
  19614. });
  19615. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19616. std::string body = req.body;
  19617. res.set_chunked_content_provider(
  19618. "text/plain", [body](size_t offset, DataSink &sink) {
  19619. if (offset < body.size()) {
  19620. sink.write(body.data() + offset, body.size() - offset);
  19621. }
  19622. sink.done();
  19623. return true;
  19624. });
  19625. });
  19626. port_ = svr_.bind_to_any_port("127.0.0.1");
  19627. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19628. svr_.wait_until_ready();
  19629. }
  19630. void TearDown() override {
  19631. svr_.stop();
  19632. if (thread_.joinable()) thread_.join();
  19633. }
  19634. SSLServer svr_;
  19635. std::thread thread_;
  19636. int port_ = 0;
  19637. };
  19638. TEST_F(SSLOpenStreamTest, Basic) {
  19639. SSLClient cli("127.0.0.1", port_);
  19640. cli.enable_server_certificate_verification(false);
  19641. auto handle = cli.open_stream("GET", "/hello");
  19642. ASSERT_TRUE(handle.is_valid());
  19643. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19644. }
  19645. TEST_F(SSLOpenStreamTest, Chunked) {
  19646. SSLClient cli("127.0.0.1", port_);
  19647. cli.enable_server_certificate_verification(false);
  19648. auto handle = cli.open_stream("GET", "/chunked");
  19649. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19650. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19651. "Transfer-Encoding") == "chunked");
  19652. auto body = read_all(handle);
  19653. EXPECT_EQ("chunkchunkchunk", body);
  19654. }
  19655. TEST_F(SSLOpenStreamTest, Post) {
  19656. SSLClient cli("127.0.0.1", port_);
  19657. cli.enable_server_certificate_verification(false);
  19658. auto handle =
  19659. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19660. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19661. EXPECT_EQ(200, handle.response->status);
  19662. auto body = read_all(handle);
  19663. EXPECT_EQ("Hello SSL POST", body);
  19664. }
  19665. TEST_F(SSLOpenStreamTest, PostChunked) {
  19666. SSLClient cli("127.0.0.1", port_);
  19667. cli.enable_server_certificate_verification(false);
  19668. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19669. "Chunked SSL Data", "text/plain");
  19670. ASSERT_TRUE(handle.is_valid());
  19671. EXPECT_EQ(200, handle.response->status);
  19672. auto body = read_all(handle);
  19673. EXPECT_EQ("Chunked SSL Data", body);
  19674. }
  19675. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19676. // Content-Length is terminated by the server closing the connection. When the
  19677. // SSL peer sends a close_notify after the body, the client must treat it as a
  19678. // clean EOF and return a successful response rather than an error.
  19679. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19681. ASSERT_TRUE(svr.is_valid());
  19682. svr.set_keep_alive_max_count(1);
  19683. const std::string expected_body = "Hello from connection-close response!";
  19684. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19685. res.set_content_provider("text/plain",
  19686. [&](size_t offset, DataSink &sink) -> bool {
  19687. if (offset < expected_body.size()) {
  19688. sink.write(expected_body.data() + offset,
  19689. expected_body.size() - offset);
  19690. }
  19691. sink.done();
  19692. return true;
  19693. });
  19694. });
  19695. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19696. auto se = detail::scope_exit([&] {
  19697. svr.stop();
  19698. listen_thread.join();
  19699. ASSERT_FALSE(svr.is_running());
  19700. });
  19701. svr.wait_until_ready();
  19702. SSLClient cli(HOST, PORT);
  19703. cli.enable_server_certificate_verification(false);
  19704. auto res = cli.Get("/no-content-length");
  19705. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19706. EXPECT_EQ(StatusCode::OK_200, res->status);
  19707. EXPECT_EQ(expected_body, res->body);
  19708. }
  19709. #endif // CPPHTTPLIB_SSL_ENABLED
  19710. //==============================================================================
  19711. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19712. // results for various scenarios.
  19713. //==============================================================================
  19714. TEST(ParityTest, GetVsOpenStream) {
  19715. Server svr;
  19716. const std::string path = "/parity";
  19717. const std::string content = "Parity test content: hello world";
  19718. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19719. res.set_content(content, "text/plain");
  19720. });
  19721. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19722. auto se = detail::scope_exit([&] {
  19723. svr.stop();
  19724. t.join();
  19725. ASSERT_FALSE(svr.is_running());
  19726. });
  19727. svr.wait_until_ready();
  19728. Client cli(HOST, PORT);
  19729. // Non-stream path
  19730. auto r1 = cli.Get(path);
  19731. ASSERT_TRUE(r1);
  19732. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19733. // Stream path
  19734. auto h = cli.open_stream("GET", path);
  19735. ASSERT_TRUE(h.is_valid());
  19736. EXPECT_EQ(r1->body, read_all(h));
  19737. }
  19738. // Helper to compress data with provided compressor type T
  19739. template <typename Compressor>
  19740. static std::string compress_payload_for_parity(const std::string &in) {
  19741. std::string out;
  19742. Compressor compressor;
  19743. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19744. [&](const char *data, size_t n) {
  19745. out.append(data, n);
  19746. return true;
  19747. });
  19748. EXPECT_TRUE(ok);
  19749. return out;
  19750. }
  19751. // Helper function for compression parity tests
  19752. template <typename Compressor>
  19753. static void test_compression_parity(const std::string &original,
  19754. const std::string &path,
  19755. const std::string &encoding) {
  19756. const std::string compressed =
  19757. compress_payload_for_parity<Compressor>(original);
  19758. Server svr;
  19759. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19760. res.set_content(compressed, "application/octet-stream");
  19761. res.set_header("Content-Encoding", encoding);
  19762. });
  19763. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19764. auto se = detail::scope_exit([&] {
  19765. svr.stop();
  19766. t.join();
  19767. ASSERT_FALSE(svr.is_running());
  19768. });
  19769. svr.wait_until_ready();
  19770. Client cli(HOST, PORT);
  19771. // Non-streaming
  19772. {
  19773. auto res = cli.Get(path);
  19774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19775. EXPECT_EQ(StatusCode::OK_200, res->status);
  19776. EXPECT_EQ(original, res->body);
  19777. }
  19778. // Streaming
  19779. {
  19780. auto h = cli.open_stream("GET", path);
  19781. ASSERT_TRUE(h.is_valid());
  19782. EXPECT_EQ(original, read_all(h));
  19783. }
  19784. }
  19785. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19786. TEST(ParityTest, Gzip) {
  19787. test_compression_parity<detail::gzip_compressor>(
  19788. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19789. }
  19790. #endif
  19791. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19792. TEST(ParityTest, Brotli) {
  19793. test_compression_parity<detail::brotli_compressor>(
  19794. "Hello, brotli parity test payload", "/parity-br", "br");
  19795. }
  19796. #endif
  19797. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19798. TEST(ParityTest, Zstd) {
  19799. test_compression_parity<detail::zstd_compressor>(
  19800. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19801. }
  19802. #endif
  19803. //==============================================================================
  19804. // New Stream API Tests
  19805. //==============================================================================
  19806. inline std::string read_body(httplib::stream::Result &result) {
  19807. std::string body;
  19808. while (result.next()) {
  19809. body.append(result.data(), result.size());
  19810. }
  19811. return body;
  19812. }
  19813. TEST(ClientConnectionTest, Basic) {
  19814. httplib::ClientConnection conn;
  19815. EXPECT_FALSE(conn.is_open());
  19816. conn.sock = 1;
  19817. EXPECT_TRUE(conn.is_open());
  19818. httplib::ClientConnection conn2(std::move(conn));
  19819. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19820. conn2.sock = INVALID_SOCKET;
  19821. }
  19822. // Unified test server for all stream::* tests
  19823. class StreamApiTest : public ::testing::Test {
  19824. protected:
  19825. void SetUp() override {
  19826. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19827. res.set_content("Hello World!", "text/plain");
  19828. });
  19829. svr_.Get("/echo-params",
  19830. [](const httplib::Request &req, httplib::Response &res) {
  19831. std::string r;
  19832. for (const auto &p : req.params) {
  19833. if (!r.empty()) r += "&";
  19834. r += p.first + "=" + p.second;
  19835. }
  19836. res.set_content(r, "text/plain");
  19837. });
  19838. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19839. res.set_content(req.body, req.get_header_value("Content-Type"));
  19840. });
  19841. svr_.Post("/echo-headers",
  19842. [](const httplib::Request &req, httplib::Response &res) {
  19843. std::string r;
  19844. for (const auto &h : req.headers)
  19845. r += h.first + ": " + h.second + "\n";
  19846. res.set_content(r, "text/plain");
  19847. });
  19848. svr_.Post("/echo-params",
  19849. [](const httplib::Request &req, httplib::Response &res) {
  19850. std::string r = "params:";
  19851. for (const auto &p : req.params)
  19852. r += p.first + "=" + p.second + ";";
  19853. res.set_content(r + " body:" + req.body, "text/plain");
  19854. });
  19855. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19856. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19857. });
  19858. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19859. res.set_content("PUT:" + req.body, "text/plain");
  19860. });
  19861. svr_.Patch("/echo",
  19862. [](const httplib::Request &req, httplib::Response &res) {
  19863. res.set_content("PATCH:" + req.body, "text/plain");
  19864. });
  19865. svr_.Delete(
  19866. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19867. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19868. "text/plain");
  19869. });
  19870. svr_.Get("/head-test",
  19871. [](const httplib::Request &, httplib::Response &res) {
  19872. res.set_content("body for HEAD", "text/plain");
  19873. });
  19874. svr_.Options("/options",
  19875. [](const httplib::Request &, httplib::Response &res) {
  19876. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19877. });
  19878. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19879. svr_.wait_until_ready();
  19880. }
  19881. void TearDown() override {
  19882. svr_.stop();
  19883. if (thread_.joinable()) thread_.join();
  19884. }
  19885. httplib::Server svr_;
  19886. std::thread thread_;
  19887. };
  19888. // stream::Get tests
  19889. TEST_F(StreamApiTest, GetBasic) {
  19890. httplib::Client cli(HOST, PORT);
  19891. auto result = httplib::stream::Get(cli, "/hello");
  19892. ASSERT_TRUE(result.is_valid());
  19893. EXPECT_EQ(200, result.status());
  19894. EXPECT_EQ("Hello World!", read_body(result));
  19895. }
  19896. TEST_F(StreamApiTest, GetWithParams) {
  19897. httplib::Client cli(HOST, PORT);
  19898. httplib::Params params{{"foo", "bar"}};
  19899. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19900. ASSERT_TRUE(result.is_valid());
  19901. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19902. }
  19903. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19904. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19905. httplib::Client cli(HOST, PORT);
  19906. cli.set_payload_max_length(0);
  19907. auto result = httplib::stream::Get(cli, "/hello");
  19908. ASSERT_TRUE(result.is_valid());
  19909. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19910. EXPECT_EQ("Hello World!", read_body(result));
  19911. }
  19912. #endif
  19913. TEST_F(StreamApiTest, GetConnectionError) {
  19914. httplib::Client cli(HOST, 9999);
  19915. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19916. }
  19917. TEST_F(StreamApiTest, Get404) {
  19918. httplib::Client cli(HOST, PORT);
  19919. auto result = httplib::stream::Get(cli, "/nonexistent");
  19920. EXPECT_TRUE(result.is_valid());
  19921. EXPECT_EQ(404, result.status());
  19922. }
  19923. // stream::Post tests
  19924. TEST_F(StreamApiTest, PostBasic) {
  19925. httplib::Client cli(HOST, PORT);
  19926. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19927. "application/json");
  19928. ASSERT_TRUE(result.is_valid());
  19929. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19930. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19931. }
  19932. TEST_F(StreamApiTest, PostWithHeaders) {
  19933. httplib::Client cli(HOST, PORT);
  19934. httplib::Headers headers{{"X-Custom", "value"}};
  19935. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19936. "text/plain");
  19937. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19938. }
  19939. TEST_F(StreamApiTest, PostWithParams) {
  19940. httplib::Client cli(HOST, PORT);
  19941. httplib::Params params{{"k", "v"}};
  19942. auto result =
  19943. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19944. auto body = read_body(result);
  19945. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19946. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19947. }
  19948. TEST_F(StreamApiTest, PostLarge) {
  19949. httplib::Client cli(HOST, PORT);
  19950. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19951. size_t total = 0;
  19952. while (result.next()) {
  19953. total += result.size();
  19954. }
  19955. EXPECT_EQ(100u * 1024u, total);
  19956. }
  19957. // stream::Put/Patch tests
  19958. TEST_F(StreamApiTest, PutAndPatch) {
  19959. httplib::Client cli(HOST, PORT);
  19960. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19961. EXPECT_EQ("PUT:test", read_body(put));
  19962. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19963. EXPECT_EQ("PATCH:test", read_body(patch));
  19964. }
  19965. // stream::Delete tests
  19966. TEST_F(StreamApiTest, Delete) {
  19967. httplib::Client cli(HOST, PORT);
  19968. auto del1 = httplib::stream::Delete(cli, "/resource");
  19969. EXPECT_EQ("Deleted", read_body(del1));
  19970. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19971. EXPECT_EQ("Deleted:data", read_body(del2));
  19972. }
  19973. // stream::Head/Options tests
  19974. TEST_F(StreamApiTest, HeadAndOptions) {
  19975. httplib::Client cli(HOST, PORT);
  19976. auto head = httplib::stream::Head(cli, "/head-test");
  19977. EXPECT_TRUE(head.is_valid());
  19978. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19979. auto opts = httplib::stream::Options(cli, "/options");
  19980. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19981. }
  19982. // SSL stream::* tests
  19983. #ifdef CPPHTTPLIB_SSL_ENABLED
  19984. class SSLStreamApiTest : public ::testing::Test {
  19985. protected:
  19986. void SetUp() override {
  19987. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19988. res.set_content("Hello SSL!", "text/plain");
  19989. });
  19990. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19991. res.set_content(req.body, "text/plain");
  19992. });
  19993. port_ = svr_.bind_to_any_port("127.0.0.1");
  19994. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19995. svr_.wait_until_ready();
  19996. }
  19997. void TearDown() override {
  19998. svr_.stop();
  19999. if (thread_.joinable()) thread_.join();
  20000. }
  20001. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20002. std::thread thread_;
  20003. int port_ = 0;
  20004. };
  20005. TEST_F(SSLStreamApiTest, GetAndPost) {
  20006. httplib::SSLClient cli("127.0.0.1", port_);
  20007. cli.enable_server_certificate_verification(false);
  20008. auto get = httplib::stream::Get(cli, "/hello");
  20009. EXPECT_EQ("Hello SSL!", read_body(get));
  20010. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20011. EXPECT_EQ("test", read_body(post));
  20012. }
  20013. #endif
  20014. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20015. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20016. // BodyReader
  20017. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20018. // Test that read timeout during streaming is detected
  20019. // Use a large content-length response where server delays mid-stream
  20020. Server svr;
  20021. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20022. // Send a large response with delay in the middle
  20023. res.set_content_provider(
  20024. 1000, // content_length
  20025. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20026. if (offset < 100) {
  20027. // Send first 100 bytes immediately
  20028. std::string data(100, 'A');
  20029. sink.write(data.c_str(), data.size());
  20030. return true;
  20031. }
  20032. // Then delay longer than client timeout
  20033. std::this_thread::sleep_for(std::chrono::seconds(3));
  20034. std::string data(900, 'B');
  20035. sink.write(data.c_str(), data.size());
  20036. return true;
  20037. });
  20038. });
  20039. auto port = 8091;
  20040. std::thread t([&]() { svr.listen("localhost", port); });
  20041. svr.wait_until_ready();
  20042. Client cli("localhost", port);
  20043. cli.set_read_timeout(1, 0); // 1 second timeout
  20044. auto handle = cli.open_stream("GET", "/slow-stream");
  20045. ASSERT_TRUE(handle.is_valid());
  20046. char buf[256];
  20047. ssize_t total = 0;
  20048. ssize_t n;
  20049. bool got_error = false;
  20050. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20051. total += n;
  20052. }
  20053. if (n < 0) {
  20054. got_error = true;
  20055. // Should be timeout or read error
  20056. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20057. handle.get_read_error() == Error::Read)
  20058. << "Actual error: " << to_string(handle.get_read_error());
  20059. }
  20060. // Either we got an error, or we got less data than expected
  20061. EXPECT_TRUE(got_error || total < 1000)
  20062. << "Expected timeout but got all " << total << " bytes";
  20063. svr.stop();
  20064. t.join();
  20065. }
  20066. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20067. // Test connection closed detection via BodyReader
  20068. Server svr;
  20069. std::atomic<bool> close_now{false};
  20070. svr.Get("/will-close", [&](const Request &, Response &res) {
  20071. res.set_content_provider(
  20072. 10000, // Large content_length that we won't fully send
  20073. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20074. if (offset < 100) {
  20075. std::string data(100, 'X');
  20076. sink.write(data.c_str(), data.size());
  20077. return true;
  20078. }
  20079. // Wait for signal then abort
  20080. while (!close_now) {
  20081. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20082. }
  20083. return false; // Abort - server will close connection
  20084. });
  20085. });
  20086. auto port = 8092;
  20087. std::thread t([&]() { svr.listen("localhost", port); });
  20088. svr.wait_until_ready();
  20089. Client cli("localhost", port);
  20090. auto handle = cli.open_stream("GET", "/will-close");
  20091. ASSERT_TRUE(handle.is_valid());
  20092. char buf[256];
  20093. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20094. EXPECT_GT(n, 0) << "First read should succeed";
  20095. // Signal server to close
  20096. close_now = true;
  20097. // Keep reading until error or EOF
  20098. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20099. // Keep reading
  20100. }
  20101. // Should get an error since content_length wasn't satisfied
  20102. if (n < 0) {
  20103. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20104. handle.get_read_error() == Error::Read)
  20105. << "Actual error: " << to_string(handle.get_read_error());
  20106. }
  20107. svr.stop();
  20108. t.join();
  20109. }
  20110. #ifdef CPPHTTPLIB_SSL_ENABLED
  20111. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20112. // Test that read timeout during SSL streaming is detected
  20113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20114. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20115. res.set_content_provider(
  20116. 1000, "text/plain",
  20117. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20118. if (offset < 100) {
  20119. std::string data(100, 'A');
  20120. sink.write(data.c_str(), data.size());
  20121. return true;
  20122. }
  20123. std::this_thread::sleep_for(std::chrono::seconds(3));
  20124. std::string data(900, 'B');
  20125. sink.write(data.c_str(), data.size());
  20126. return true;
  20127. });
  20128. });
  20129. auto port = 8093;
  20130. std::thread t([&]() { svr.listen("localhost", port); });
  20131. svr.wait_until_ready();
  20132. SSLClient cli("localhost", port);
  20133. cli.enable_server_certificate_verification(false);
  20134. cli.set_read_timeout(1, 0); // 1 second timeout
  20135. auto handle = cli.open_stream("GET", "/slow-stream");
  20136. ASSERT_TRUE(handle.is_valid());
  20137. char buf[256];
  20138. ssize_t total = 0;
  20139. ssize_t n;
  20140. bool got_error = false;
  20141. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20142. total += n;
  20143. }
  20144. if (n < 0) {
  20145. got_error = true;
  20146. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20147. handle.get_read_error() == Error::Read)
  20148. << "Actual error: " << to_string(handle.get_read_error());
  20149. }
  20150. EXPECT_TRUE(got_error || total < 1000)
  20151. << "Expected timeout but got all " << total << " bytes";
  20152. svr.stop();
  20153. t.join();
  20154. }
  20155. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20156. // Test SSL connection closed detection
  20157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20158. std::atomic<bool> close_now{false};
  20159. svr.Get("/will-close", [&](const Request &, Response &res) {
  20160. res.set_content_provider(
  20161. 10000, "text/plain",
  20162. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20163. if (offset < 100) {
  20164. std::string data(100, 'X');
  20165. sink.write(data.c_str(), data.size());
  20166. return true;
  20167. }
  20168. while (!close_now) {
  20169. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20170. }
  20171. return false;
  20172. });
  20173. });
  20174. auto port = 8094;
  20175. std::thread t([&]() { svr.listen("localhost", port); });
  20176. svr.wait_until_ready();
  20177. SSLClient cli("localhost", port);
  20178. cli.enable_server_certificate_verification(false);
  20179. auto handle = cli.open_stream("GET", "/will-close");
  20180. ASSERT_TRUE(handle.is_valid());
  20181. char buf[256];
  20182. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20183. EXPECT_GT(n, 0);
  20184. // Signal server to close
  20185. close_now = true;
  20186. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20187. // Keep reading
  20188. }
  20189. if (n < 0) {
  20190. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20191. handle.get_read_error() == Error::Read)
  20192. << "Actual error: " << to_string(handle.get_read_error());
  20193. }
  20194. svr.stop();
  20195. t.join();
  20196. }
  20197. #endif
  20198. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20199. using namespace httplib;
  20200. // Create a test file
  20201. const char *fname = "etag_testfile.txt";
  20202. const char *content = "etag-content";
  20203. {
  20204. std::ofstream ofs(fname);
  20205. ofs << content;
  20206. ASSERT_TRUE(ofs.good());
  20207. }
  20208. Server svr;
  20209. svr.set_mount_point("/static", ".");
  20210. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20211. svr.wait_until_ready();
  20212. Client cli(HOST, PORT);
  20213. // First request: should get 200 with ETag header
  20214. auto res1 = cli.Get("/static/etag_testfile.txt");
  20215. ASSERT_TRUE(res1);
  20216. ASSERT_EQ(200, res1->status);
  20217. ASSERT_TRUE(res1->has_header("ETag"));
  20218. std::string etag = res1->get_header_value("ETag");
  20219. EXPECT_FALSE(etag.empty());
  20220. // Verify ETag format: W/"hex-hex"
  20221. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20222. EXPECT_EQ('W', etag[0]);
  20223. EXPECT_EQ('/', etag[1]);
  20224. EXPECT_EQ('"', etag[2]);
  20225. EXPECT_EQ('"', etag.back());
  20226. // Exact match: expect 304 Not Modified
  20227. Headers h2 = {{"If-None-Match", etag}};
  20228. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20229. ASSERT_TRUE(res2);
  20230. EXPECT_EQ(304, res2->status);
  20231. // Wildcard match: expect 304 Not Modified
  20232. Headers h3 = {{"If-None-Match", "*"}};
  20233. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20234. ASSERT_TRUE(res3);
  20235. EXPECT_EQ(304, res3->status);
  20236. // Non-matching ETag: expect 200
  20237. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20238. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20239. ASSERT_TRUE(res4);
  20240. EXPECT_EQ(200, res4->status);
  20241. // Multiple ETags with one matching: expect 304
  20242. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20243. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20244. ASSERT_TRUE(res5);
  20245. EXPECT_EQ(304, res5->status);
  20246. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20247. // that equivalent to the single comma-separated list above, so the match on
  20248. // the second line must still be found.
  20249. Headers h6;
  20250. h6.emplace("If-None-Match", "W/\"other\"");
  20251. h6.emplace("If-None-Match", etag);
  20252. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20253. ASSERT_TRUE(res6);
  20254. EXPECT_EQ(304, res6->status);
  20255. svr.stop();
  20256. t.join();
  20257. std::remove(fname);
  20258. }
  20259. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20260. using namespace httplib;
  20261. Server svr;
  20262. svr.set_mount_point("/static", ".");
  20263. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20264. svr.wait_until_ready();
  20265. Client cli(HOST, PORT);
  20266. // Send If-None-Match: * to a non-existent file
  20267. Headers h = {{"If-None-Match", "*"}};
  20268. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20270. EXPECT_EQ(404, res->status);
  20271. svr.stop();
  20272. t.join();
  20273. }
  20274. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20275. using namespace httplib;
  20276. // Create a test file
  20277. const char *fname = "etag_boundary_testfile.txt";
  20278. const char *content = "boundary-test";
  20279. {
  20280. std::ofstream ofs(fname);
  20281. ofs << content;
  20282. ASSERT_TRUE(ofs.good());
  20283. }
  20284. Server svr;
  20285. svr.set_mount_point("/static", ".");
  20286. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20287. svr.wait_until_ready();
  20288. Client cli(HOST, PORT);
  20289. // Get the actual ETag
  20290. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20291. ASSERT_TRUE(res1);
  20292. ASSERT_EQ(200, res1->status);
  20293. ASSERT_TRUE(res1->has_header("ETag"));
  20294. std::string etag = res1->get_header_value("ETag");
  20295. // Test 1: Very long ETag value (longer than actual ETag)
  20296. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20297. Headers h1 = {{"If-None-Match", "W/"
  20298. "\"very-long-etag-value-that-is-much-longer-"
  20299. "than-the-actual-etag-value\""}};
  20300. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20301. ASSERT_TRUE(res2);
  20302. EXPECT_EQ(200, res2->status); // Should not match
  20303. // Test 2: Long string followed by wildcard
  20304. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20305. // string)
  20306. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20307. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20308. ASSERT_TRUE(res3);
  20309. EXPECT_EQ(304, res3->status); // Should match on "*"
  20310. // Test 3: Wildcard followed by long string
  20311. // Should match on "*" immediately and return 304
  20312. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20313. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20314. ASSERT_TRUE(res4);
  20315. EXPECT_EQ(304, res4->status); // Should match on "*"
  20316. // Test 4: Multiple long non-matching values
  20317. // Should NOT match and return 200 (test that all comparisons are safe)
  20318. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20319. "W/\"second-long-non-matching-value\", "
  20320. "W/\"third-long-non-matching-value\""}};
  20321. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20322. ASSERT_TRUE(res5);
  20323. EXPECT_EQ(200, res5->status); // Should not match
  20324. // Test 5: Single character that is not "*" (edge case)
  20325. Headers h5 = {{"If-None-Match", "X"}};
  20326. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20327. ASSERT_TRUE(res6);
  20328. EXPECT_EQ(200, res6->status); // Should not match
  20329. svr.stop();
  20330. t.join();
  20331. std::remove(fname);
  20332. }
  20333. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20334. using namespace httplib;
  20335. // Create a test file
  20336. const char *fname = "ims_testfile.txt";
  20337. const char *content = "if-modified-since-test";
  20338. {
  20339. std::ofstream ofs(fname);
  20340. ofs << content;
  20341. ASSERT_TRUE(ofs.good());
  20342. }
  20343. Server svr;
  20344. svr.set_mount_point("/static", ".");
  20345. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20346. svr.wait_until_ready();
  20347. Client cli(HOST, PORT);
  20348. // First request: should get 200 with Last-Modified header
  20349. auto res1 = cli.Get("/static/ims_testfile.txt");
  20350. ASSERT_TRUE(res1);
  20351. ASSERT_EQ(200, res1->status);
  20352. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20353. std::string last_modified = res1->get_header_value("Last-Modified");
  20354. EXPECT_FALSE(last_modified.empty());
  20355. // If-Modified-Since with same time: expect 304
  20356. Headers h2 = {{"If-Modified-Since", last_modified}};
  20357. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20358. ASSERT_TRUE(res2);
  20359. EXPECT_EQ(304, res2->status);
  20360. // If-Modified-Since with future time: expect 304
  20361. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20362. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20363. ASSERT_TRUE(res3);
  20364. EXPECT_EQ(304, res3->status);
  20365. // If-Modified-Since with past time: expect 200
  20366. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20367. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20368. ASSERT_TRUE(res4);
  20369. EXPECT_EQ(200, res4->status);
  20370. // If-None-Match takes precedence over If-Modified-Since
  20371. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20372. ASSERT_TRUE(res1->has_header("ETag"));
  20373. std::string etag = res1->get_header_value("ETag");
  20374. Headers h5 = {{"If-None-Match", etag},
  20375. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20376. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20377. ASSERT_TRUE(res5);
  20378. EXPECT_EQ(304, res5->status);
  20379. svr.stop();
  20380. t.join();
  20381. std::remove(fname);
  20382. }
  20383. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20384. using namespace httplib;
  20385. Server svr;
  20386. // Endpoint that returns compressible content
  20387. svr.Get("/compressible", [](const Request &, Response &res) {
  20388. // Return a large enough body to trigger compression
  20389. std::string body(1000, 'a');
  20390. res.set_content(body, "text/plain");
  20391. });
  20392. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20393. svr.wait_until_ready();
  20394. Client cli(HOST, PORT);
  20395. // Request with gzip support: should get Vary header when compressed
  20396. cli.set_compress(true);
  20397. auto res1 = cli.Get("/compressible");
  20398. ASSERT_TRUE(res1);
  20399. EXPECT_EQ(200, res1->status);
  20400. // If Content-Encoding is set, Vary should also be set
  20401. if (res1->has_header("Content-Encoding")) {
  20402. EXPECT_TRUE(res1->has_header("Vary"));
  20403. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20404. }
  20405. // Request without Accept-Encoding header: should not have compression
  20406. Headers h_no_compress;
  20407. auto res2 = cli.Get("/compressible", h_no_compress);
  20408. ASSERT_TRUE(res2);
  20409. EXPECT_EQ(200, res2->status);
  20410. // Verify Vary header is present when compression is applied
  20411. // (the exact behavior depends on server configuration)
  20412. svr.stop();
  20413. t.join();
  20414. }
  20415. TEST(ETagTest, IfRangeWithETag) {
  20416. using namespace httplib;
  20417. // Create a test file with known content
  20418. const char *fname = "if_range_testfile.txt";
  20419. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20420. {
  20421. std::ofstream ofs(fname);
  20422. ofs << content;
  20423. ASSERT_TRUE(ofs.good());
  20424. }
  20425. Server svr;
  20426. svr.set_mount_point("/static", ".");
  20427. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20428. svr.wait_until_ready();
  20429. Client cli(HOST, PORT);
  20430. // First request: get ETag
  20431. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20432. ASSERT_TRUE(res1);
  20433. ASSERT_EQ(200, res1->status);
  20434. ASSERT_TRUE(res1->has_header("ETag"));
  20435. std::string etag = res1->get_header_value("ETag");
  20436. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20437. // Since our server generates weak ETags (W/"..."), If-Range with our
  20438. // ETag should NOT result in partial content - it should return full content.
  20439. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20440. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20441. ASSERT_TRUE(res2);
  20442. // Weak ETag in If-Range -> full content (200), not partial (206)
  20443. EXPECT_EQ(200, res2->status);
  20444. EXPECT_EQ(content, res2->body);
  20445. EXPECT_FALSE(res2->has_header("Content-Range"));
  20446. // Range request with non-matching If-Range (ETag): should get 200 (full
  20447. // content)
  20448. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20449. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20450. ASSERT_TRUE(res3);
  20451. EXPECT_EQ(200, res3->status);
  20452. EXPECT_EQ(content, res3->body);
  20453. EXPECT_FALSE(res3->has_header("Content-Range"));
  20454. // Range request with strong ETag (hypothetical - our server doesn't generate
  20455. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20456. // should return full content)
  20457. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20458. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20459. ASSERT_TRUE(res4);
  20460. EXPECT_EQ(200, res4->status);
  20461. EXPECT_EQ(content, res4->body);
  20462. EXPECT_FALSE(res4->has_header("Content-Range"));
  20463. svr.stop();
  20464. t.join();
  20465. std::remove(fname);
  20466. }
  20467. TEST(ETagTest, IfRangeWithDate) {
  20468. using namespace httplib;
  20469. // Create a test file
  20470. const char *fname = "if_range_date_testfile.txt";
  20471. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20472. {
  20473. std::ofstream ofs(fname);
  20474. ofs << content;
  20475. ASSERT_TRUE(ofs.good());
  20476. }
  20477. Server svr;
  20478. svr.set_mount_point("/static", ".");
  20479. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20480. svr.wait_until_ready();
  20481. Client cli(HOST, PORT);
  20482. // First request: get Last-Modified
  20483. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20484. ASSERT_TRUE(res1);
  20485. ASSERT_EQ(200, res1->status);
  20486. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20487. std::string last_modified = res1->get_header_value("Last-Modified");
  20488. // Range request with matching If-Range (date): should get 206
  20489. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20490. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20491. ASSERT_TRUE(res2);
  20492. EXPECT_EQ(206, res2->status);
  20493. EXPECT_EQ("FGHIJ", res2->body);
  20494. // Range request with old If-Range date: should get 200 (full content)
  20495. Headers h3 = {{"Range", "bytes=5-9"},
  20496. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20497. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20498. ASSERT_TRUE(res3);
  20499. EXPECT_EQ(200, res3->status);
  20500. EXPECT_EQ(content, res3->body);
  20501. // Range request with future If-Range date: should get 206
  20502. Headers h4 = {{"Range", "bytes=0-4"},
  20503. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20504. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20505. ASSERT_TRUE(res4);
  20506. EXPECT_EQ(206, res4->status);
  20507. EXPECT_EQ("ABCDE", res4->body);
  20508. svr.stop();
  20509. t.join();
  20510. std::remove(fname);
  20511. }
  20512. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20513. using namespace httplib;
  20514. const char *fname = "etag_malformed.txt";
  20515. const char *content = "malformed-etag";
  20516. {
  20517. std::ofstream ofs(fname);
  20518. ofs << content;
  20519. ASSERT_TRUE(ofs.good());
  20520. }
  20521. Server svr;
  20522. svr.set_mount_point("/static", ".");
  20523. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20524. svr.wait_until_ready();
  20525. Client cli(HOST, PORT);
  20526. // baseline: should get 200 and an ETag
  20527. auto res1 = cli.Get("/static/etag_malformed.txt");
  20528. ASSERT_TRUE(res1);
  20529. ASSERT_EQ(200, res1->status);
  20530. ASSERT_TRUE(res1->has_header("ETag"));
  20531. // Malformed ETag value (missing quotes) should be treated as non-matching
  20532. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20533. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20534. ASSERT_TRUE(res_bad);
  20535. EXPECT_EQ(200, res_bad->status);
  20536. // Whitespace-only header value should be considered invalid / non-matching
  20537. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20538. "Host: localhost\r\n"
  20539. "If-None-Match: \r\n"
  20540. "Connection: close\r\n"
  20541. "\r\n";
  20542. std::string out;
  20543. ASSERT_TRUE(send_request(5, raw_req, &out));
  20544. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20545. svr.stop();
  20546. t.join();
  20547. std::remove(fname);
  20548. }
  20549. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20550. using namespace httplib;
  20551. const char *fname = "ims_invalid_format.txt";
  20552. const char *content = "ims-bad-format";
  20553. {
  20554. std::ofstream ofs(fname);
  20555. ofs << content;
  20556. ASSERT_TRUE(ofs.good());
  20557. }
  20558. Server svr;
  20559. svr.set_mount_point("/static", ".");
  20560. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20561. svr.wait_until_ready();
  20562. Client cli(HOST, PORT);
  20563. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20564. ASSERT_TRUE(res1);
  20565. ASSERT_EQ(200, res1->status);
  20566. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20567. // If-Modified-Since with invalid format should not result in 304
  20568. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20569. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20570. ASSERT_TRUE(res_bad);
  20571. EXPECT_EQ(200, res_bad->status);
  20572. // If-Range with invalid date format should be treated as mismatch -> full
  20573. // content (200)
  20574. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20575. {"If-Range", "invalid-date"}};
  20576. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20577. ASSERT_TRUE(res_ifrange);
  20578. EXPECT_EQ(200, res_ifrange->status);
  20579. svr.stop();
  20580. t.join();
  20581. std::remove(fname);
  20582. }
  20583. TEST(ETagTest, IfRangeWithMalformedETag) {
  20584. using namespace httplib;
  20585. const char *fname = "ifrange_malformed.txt";
  20586. const std::string content = "0123456789";
  20587. {
  20588. std::ofstream ofs(fname);
  20589. ofs << content;
  20590. ASSERT_TRUE(ofs.good());
  20591. }
  20592. Server svr;
  20593. svr.set_mount_point("/static", ".");
  20594. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20595. svr.wait_until_ready();
  20596. Client cli(HOST, PORT);
  20597. // First request: get ETag
  20598. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20599. ASSERT_TRUE(res1);
  20600. ASSERT_EQ(200, res1->status);
  20601. ASSERT_TRUE(res1->has_header("ETag"));
  20602. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20603. // full content (200)
  20604. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20605. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20606. ASSERT_TRUE(res2);
  20607. EXPECT_EQ(200, res2->status);
  20608. EXPECT_EQ(content, res2->body);
  20609. svr.stop();
  20610. t.join();
  20611. std::remove(fname);
  20612. }
  20613. TEST(ETagTest, ExtremeLargeDateValues) {
  20614. using namespace httplib;
  20615. const char *fname = "ims_extreme_date.txt";
  20616. const char *content = "ims-extreme-date";
  20617. {
  20618. std::ofstream ofs(fname);
  20619. ofs << content;
  20620. ASSERT_TRUE(ofs.good());
  20621. }
  20622. Server svr;
  20623. svr.set_mount_point("/static", ".");
  20624. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20625. svr.wait_until_ready();
  20626. Client cli(HOST, PORT);
  20627. auto res1 = cli.Get(std::string("/static/") + fname);
  20628. ASSERT_TRUE(res1);
  20629. ASSERT_EQ(200, res1->status);
  20630. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20631. // Extremely large year that may overflow date parsing routines.
  20632. Headers h_large_date = {
  20633. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20634. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20635. ASSERT_TRUE(res_bad);
  20636. // Expect server to treat this as invalid/mismatch and return full content
  20637. EXPECT_EQ(200, res_bad->status);
  20638. // If-Range with extremely large date should be treated as mismatch -> full
  20639. // content (200)
  20640. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20641. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20642. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20643. ASSERT_TRUE(res_ifrange);
  20644. EXPECT_EQ(200, res_ifrange->status);
  20645. svr.stop();
  20646. t.join();
  20647. std::remove(fname);
  20648. }
  20649. TEST(ETagTest, NegativeFileModificationTime) {
  20650. using namespace httplib;
  20651. const char *fname = "ims_negative_mtime.txt";
  20652. const std::string content = "negative-mtime";
  20653. {
  20654. std::ofstream ofs(fname);
  20655. ofs << content;
  20656. ASSERT_TRUE(ofs.good());
  20657. }
  20658. // Try to set file mtime to a negative value. This may fail on some
  20659. // platforms/filesystems; if it fails, the test will still verify server
  20660. // behaves safely by performing a regular conditional request.
  20661. #if defined(__APPLE__) || defined(__linux__)
  20662. bool set_negative = false;
  20663. do {
  20664. struct timeval times[2];
  20665. // access time: now
  20666. times[0].tv_sec = time(nullptr);
  20667. times[0].tv_usec = 0;
  20668. // modification time: negative (e.g., -1)
  20669. times[1].tv_sec = -1;
  20670. times[1].tv_usec = 0;
  20671. if (utimes(fname, times) == 0) { set_negative = true; }
  20672. } while (0);
  20673. #else
  20674. bool set_negative = false;
  20675. #endif
  20676. Server svr;
  20677. svr.set_mount_point("/static", ".");
  20678. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20679. svr.wait_until_ready();
  20680. Client cli(HOST, PORT);
  20681. auto res1 = cli.Get(std::string("/static/") + fname);
  20682. ASSERT_TRUE(res1);
  20683. ASSERT_EQ(200, res1->status);
  20684. bool has_last_modified = res1->has_header("Last-Modified");
  20685. std::string last_modified;
  20686. if (has_last_modified) {
  20687. last_modified = res1->get_header_value("Last-Modified");
  20688. }
  20689. if (set_negative) {
  20690. // If we successfully set a negative mtime, ensure server returns a
  20691. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20692. // with an old date and ensure server handles it without crash.
  20693. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20694. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20695. ASSERT_TRUE(res2);
  20696. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20697. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20698. } else {
  20699. // Could not set negative mtime on this platform; fall back to verifying
  20700. // that normal invalid/malformed dates are treated safely (non-304).
  20701. Headers h_bad_date = {
  20702. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20703. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20704. ASSERT_TRUE(res_bad);
  20705. EXPECT_EQ(200, res_bad->status);
  20706. }
  20707. svr.stop();
  20708. t.join();
  20709. std::remove(fname);
  20710. }
  20711. //==============================================================================
  20712. // Integration Tests with Server
  20713. //==============================================================================
  20714. class SSEIntegrationTest : public ::testing::Test {
  20715. protected:
  20716. void SetUp() override {
  20717. stop_server_.store(false);
  20718. events_.clear();
  20719. server_ = httplib::detail::make_unique<Server>();
  20720. setup_server();
  20721. start_server();
  20722. }
  20723. void TearDown() override {
  20724. stop_server_.store(true);
  20725. event_cv_.notify_all();
  20726. server_->stop();
  20727. if (server_thread_.joinable()) { server_thread_.join(); }
  20728. }
  20729. void setup_server() {
  20730. // Simple SSE endpoint
  20731. server_->Get("/events", [this](const Request &req, Response &res) {
  20732. auto last_id = req.get_header_value("Last-Event-ID");
  20733. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20734. res.set_chunked_content_provider(
  20735. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20736. std::unique_lock<std::mutex> lock(event_mutex_);
  20737. if (event_cv_.wait_for(
  20738. lock, std::chrono::milliseconds(200), [this] {
  20739. return !events_.empty() || stop_server_.load();
  20740. })) {
  20741. if (stop_server_.load()) { return false; }
  20742. if (!events_.empty()) {
  20743. std::string event = events_.front();
  20744. events_.erase(events_.begin());
  20745. sink.write(event.data(), event.size());
  20746. return true;
  20747. }
  20748. }
  20749. return !stop_server_.load();
  20750. });
  20751. });
  20752. // Endpoint that returns error
  20753. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20754. res.status = 500;
  20755. res.set_content("Internal Server Error", "text/plain");
  20756. });
  20757. // Endpoint for custom event types
  20758. server_->Get("/custom-events", [](const Request &, Response &res) {
  20759. res.set_chunked_content_provider(
  20760. "text/event-stream", [](size_t offset, DataSink &sink) {
  20761. if (offset == 0) {
  20762. std::string event = "event: update\ndata: updated\n\n"
  20763. "event: delete\ndata: deleted\n\n";
  20764. sink.write(event.data(), event.size());
  20765. }
  20766. return false; // End stream after sending
  20767. });
  20768. });
  20769. }
  20770. void start_server() {
  20771. port_ = server_->bind_to_any_port(HOST);
  20772. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20773. // Wait for server to start
  20774. while (!server_->is_running()) {
  20775. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20776. }
  20777. }
  20778. int get_port() const { return port_; }
  20779. void send_event(const std::string &event) {
  20780. std::lock_guard<std::mutex> lock(event_mutex_);
  20781. events_.push_back(event);
  20782. event_cv_.notify_all();
  20783. }
  20784. std::unique_ptr<Server> server_;
  20785. std::thread server_thread_;
  20786. std::mutex event_mutex_;
  20787. std::condition_variable event_cv_;
  20788. std::vector<std::string> events_;
  20789. std::atomic<bool> stop_server_{false};
  20790. std::string last_received_event_id_;
  20791. int port_ = 0;
  20792. };
  20793. //==============================================================================
  20794. // SSE Parsing Tests
  20795. //==============================================================================
  20796. class SSEParsingTest : public SSEIntegrationTest {
  20797. protected:
  20798. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20799. // A trailing sentinel event tells when the whole stream has been parsed.
  20800. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20801. auto body = stream + "event: end\ndata: end\n\n";
  20802. server_->Get("/parse", [body](const Request &, Response &res) {
  20803. res.set_content(body, "text/event-stream");
  20804. });
  20805. return collect("/parse");
  20806. }
  20807. // Runs SSEClient against path until an "end" event arrives and returns the
  20808. // messages dispatched before it
  20809. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20810. Client client(HOST, get_port());
  20811. sse::SSEClient sse(client, path);
  20812. std::mutex mutex;
  20813. std::condition_variable cv;
  20814. std::vector<sse::SSEMessage> messages;
  20815. auto done = false;
  20816. sse.on_message([&](const sse::SSEMessage &msg) {
  20817. std::lock_guard<std::mutex> lock(mutex);
  20818. // Ignore a replay from a reconnect that races with stop()
  20819. if (!done) { messages.push_back(msg); }
  20820. });
  20821. sse.on_event("end", [&](const sse::SSEMessage &) {
  20822. std::lock_guard<std::mutex> lock(mutex);
  20823. done = true;
  20824. cv.notify_all();
  20825. });
  20826. sse.set_reconnect_interval(100);
  20827. sse.start_async();
  20828. {
  20829. std::unique_lock<std::mutex> lock(mutex);
  20830. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20831. }
  20832. sse.stop();
  20833. EXPECT_TRUE(done);
  20834. return messages;
  20835. }
  20836. };
  20837. TEST_F(SSEParsingTest, SingleLineData) {
  20838. auto msgs = parse("data: hello\n\n");
  20839. ASSERT_EQ(msgs.size(), 1u);
  20840. EXPECT_EQ(msgs[0].data, "hello");
  20841. EXPECT_EQ(msgs[0].event, "message");
  20842. }
  20843. TEST_F(SSEParsingTest, MultiLineData) {
  20844. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20845. ASSERT_EQ(msgs.size(), 1u);
  20846. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20847. }
  20848. TEST_F(SSEParsingTest, CustomEventType) {
  20849. auto msgs = parse("event: update\ndata: payload\n\n");
  20850. ASSERT_EQ(msgs.size(), 1u);
  20851. EXPECT_EQ(msgs[0].event, "update");
  20852. EXPECT_EQ(msgs[0].data, "payload");
  20853. }
  20854. TEST_F(SSEParsingTest, EventIdHandling) {
  20855. auto msgs = parse("id: 12345\ndata: test\n\n");
  20856. ASSERT_EQ(msgs.size(), 1u);
  20857. EXPECT_EQ(msgs[0].id, "12345");
  20858. }
  20859. TEST_F(SSEParsingTest, EmptyEventId) {
  20860. auto msgs = parse("id:\ndata: test\n\n");
  20861. ASSERT_EQ(msgs.size(), 1u);
  20862. EXPECT_EQ(msgs[0].id, "");
  20863. }
  20864. TEST_F(SSEParsingTest, CommentsIgnored) {
  20865. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20866. ASSERT_EQ(msgs.size(), 1u);
  20867. EXPECT_EQ(msgs[0].data, "hello");
  20868. EXPECT_EQ(msgs[0].event, "message");
  20869. }
  20870. TEST_F(SSEParsingTest, ColonInValue) {
  20871. auto msgs = parse("data: hello:world:test\n\n");
  20872. ASSERT_EQ(msgs.size(), 1u);
  20873. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20874. }
  20875. TEST_F(SSEParsingTest, FieldNameOnly) {
  20876. // A line without a colon is a field name with an empty value
  20877. auto msgs = parse("data\n\n");
  20878. ASSERT_EQ(msgs.size(), 1u);
  20879. EXPECT_EQ(msgs[0].data, "");
  20880. }
  20881. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20882. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20883. ASSERT_EQ(msgs.size(), 1u);
  20884. EXPECT_EQ(msgs[0].event, "update");
  20885. EXPECT_EQ(msgs[0].data, "hello");
  20886. }
  20887. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20888. auto msgs = parse("data\r\n\r\n");
  20889. ASSERT_EQ(msgs.size(), 1u);
  20890. EXPECT_EQ(msgs[0].data, "");
  20891. }
  20892. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20893. auto msgs = parse("event: update\rdata: hello\r\r");
  20894. ASSERT_EQ(msgs.size(), 1u);
  20895. EXPECT_EQ(msgs[0].event, "update");
  20896. EXPECT_EQ(msgs[0].data, "hello");
  20897. }
  20898. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20899. // Chunk boundaries fall inside every \r\n and right before the first one
  20900. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20901. "\n\r", "\nevent: end\ndata: end\n\n"};
  20902. server_->Get("/split", [chunks](const Request &, Response &res) {
  20903. auto i = std::make_shared<size_t>(0);
  20904. res.set_chunked_content_provider(
  20905. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20906. if (*i == chunks.size()) {
  20907. sink.done();
  20908. } else {
  20909. sink.write(chunks[*i].data(), chunks[*i].size());
  20910. (*i)++;
  20911. }
  20912. return true;
  20913. });
  20914. });
  20915. auto msgs = collect("/split");
  20916. ASSERT_EQ(msgs.size(), 1u);
  20917. EXPECT_EQ(msgs[0].event, "update");
  20918. EXPECT_EQ(msgs[0].data, "hello");
  20919. }
  20920. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20921. // Only a BOM at the start of the stream is ignored
  20922. auto msgs = parse("\xEF\xBB\xBF"
  20923. "data: first\n\n"
  20924. "\xEF\xBB\xBF"
  20925. "data: second\n\n");
  20926. ASSERT_EQ(msgs.size(), 1u);
  20927. EXPECT_EQ(msgs[0].data, "first");
  20928. }
  20929. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20930. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20931. ASSERT_EQ(msgs.size(), 1u);
  20932. EXPECT_EQ(msgs[0].data, "hello");
  20933. EXPECT_EQ(msgs[0].event, "message");
  20934. }
  20935. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20936. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20937. ASSERT_EQ(msgs.size(), 2u);
  20938. EXPECT_EQ(msgs[0].data, "hello");
  20939. EXPECT_EQ(msgs[1].data, "hello");
  20940. }
  20941. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20942. // An event without data is not dispatched, and its type must not leak
  20943. // into the next event
  20944. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20945. ASSERT_EQ(msgs.size(), 1u);
  20946. EXPECT_EQ(msgs[0].event, "message");
  20947. EXPECT_EQ(msgs[0].data, "hello");
  20948. }
  20949. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20950. // The first connection sends only an id; the second echoes back the
  20951. // Last-Event-ID it was reconnected with
  20952. std::atomic<int> connection_count{0};
  20953. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20954. if (connection_count++ == 0) {
  20955. res.set_content("id: 42\n\n", "text/event-stream");
  20956. } else {
  20957. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20958. "\n\nevent: end\ndata: end\n\n",
  20959. "text/event-stream");
  20960. }
  20961. });
  20962. auto msgs = collect("/id-only");
  20963. ASSERT_EQ(msgs.size(), 1u);
  20964. EXPECT_EQ(msgs[0].data, "42");
  20965. }
  20966. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20967. // The first connection sets an id and then clears it with an empty one; the
  20968. // second reports whether it was reconnected with a Last-Event-ID
  20969. std::atomic<int> connection_count{0};
  20970. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20971. if (connection_count++ == 0) {
  20972. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20973. "text/event-stream");
  20974. } else {
  20975. res.set_content(
  20976. std::string("data: ") +
  20977. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20978. "\n\nevent: end\ndata: end\n\n",
  20979. "text/event-stream");
  20980. }
  20981. });
  20982. auto msgs = collect("/id-clear");
  20983. ASSERT_EQ(msgs.size(), 3u);
  20984. EXPECT_EQ(msgs[0].id, "1");
  20985. EXPECT_EQ(msgs[1].id, "");
  20986. EXPECT_EQ(msgs[2].data, "not sent");
  20987. }
  20988. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20989. // The first connection sets an id and then sends ids that cannot be carried
  20990. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20991. // with
  20992. std::atomic<int> connection_count{0};
  20993. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20994. if (connection_count++ == 0) {
  20995. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20996. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20997. "text/event-stream");
  20998. } else {
  20999. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21000. "\n\nevent: end\ndata: end\n\n",
  21001. "text/event-stream");
  21002. }
  21003. });
  21004. auto msgs = collect("/id-unsendable");
  21005. ASSERT_EQ(msgs.size(), 1u);
  21006. EXPECT_EQ(msgs[0].data, "42");
  21007. }
  21008. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21009. auto msgs = parse("event: notification\nid: evt-42\n"
  21010. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21011. ASSERT_EQ(msgs.size(), 1u);
  21012. EXPECT_EQ(msgs[0].event, "notification");
  21013. EXPECT_EQ(msgs[0].id, "evt-42");
  21014. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21015. }
  21016. TEST(SSEMessageTest, Clear) {
  21017. sse::SSEMessage msg;
  21018. msg.event = "custom";
  21019. msg.data = "some data";
  21020. msg.id = "123";
  21021. msg.clear();
  21022. EXPECT_EQ(msg.event, "message");
  21023. EXPECT_EQ(msg.data, "");
  21024. EXPECT_EQ(msg.id, "");
  21025. }
  21026. //==============================================================================
  21027. // SSE Integration Tests
  21028. //==============================================================================
  21029. // Test: Successful connection and on_open callback
  21030. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21031. // Add a simple endpoint that sends one event and closes
  21032. server_->Get("/simple-event", [](const Request &, Response &res) {
  21033. res.set_chunked_content_provider(
  21034. "text/event-stream", [](size_t offset, DataSink &sink) {
  21035. if (offset == 0) {
  21036. std::string event = "data: hello\n\n";
  21037. sink.write(event.data(), event.size());
  21038. }
  21039. return false; // Close stream after sending
  21040. });
  21041. });
  21042. Client client("localhost", get_port());
  21043. sse::SSEClient sse(client, "/simple-event");
  21044. std::atomic<bool> open_called{false};
  21045. std::atomic<bool> message_received{false};
  21046. sse.on_open([&open_called]() { open_called.store(true); });
  21047. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21048. if (msg.data == "hello") { message_received.store(true); }
  21049. });
  21050. sse.set_reconnect_interval(100);
  21051. sse.set_max_reconnect_attempts(1);
  21052. // Start async
  21053. sse.start_async();
  21054. // Wait for message to be processed
  21055. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21056. sse.stop();
  21057. EXPECT_TRUE(open_called.load());
  21058. EXPECT_TRUE(message_received.load());
  21059. }
  21060. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21061. // A data line that never ends.
  21062. server_->Get("/endless-line", [](const Request &, Response &res) {
  21063. res.set_chunked_content_provider(
  21064. "text/event-stream", [](size_t offset, DataSink &sink) {
  21065. if (offset == 0) { sink.write("data: ", 6); }
  21066. std::string chunk(64 * 1024, 'A');
  21067. return sink.write(chunk.data(), chunk.size());
  21068. });
  21069. });
  21070. Client client("localhost", get_port());
  21071. sse::SSEClient sse(client, "/endless-line");
  21072. std::atomic<bool> too_long{false};
  21073. sse.on_error([&](Error err) {
  21074. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21075. });
  21076. sse.set_max_reconnect_attempts(1);
  21077. sse.start_async();
  21078. for (int i = 0; i < 500 && !too_long; i++) {
  21079. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21080. }
  21081. sse.stop();
  21082. EXPECT_TRUE(too_long);
  21083. }
  21084. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21085. // Far more in all than the client's payload limit below.
  21086. server_->Get("/many-events", [](const Request &, Response &res) {
  21087. res.set_chunked_content_provider(
  21088. "text/event-stream", [](size_t offset, DataSink &sink) {
  21089. if (offset == 0) {
  21090. std::string events;
  21091. for (int i = 0; i < 1000; i++) {
  21092. events += "data: message\n\n";
  21093. }
  21094. sink.write(events.data(), events.size());
  21095. }
  21096. return false;
  21097. });
  21098. });
  21099. Client client("localhost", get_port());
  21100. client.set_payload_max_length(1024);
  21101. sse::SSEClient sse(client, "/many-events");
  21102. std::atomic<int> messages{0};
  21103. std::atomic<bool> too_large{false};
  21104. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21105. sse.on_error([&](Error err) {
  21106. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21107. });
  21108. sse.set_max_reconnect_attempts(1);
  21109. sse.start_async();
  21110. for (int i = 0; i < 500 && messages < 1000; i++) {
  21111. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21112. }
  21113. sse.stop();
  21114. EXPECT_GE(messages.load(), 1000);
  21115. EXPECT_FALSE(too_large);
  21116. }
  21117. // Test: on_message callback
  21118. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21119. // Endpoint that sends multiple events then closes
  21120. server_->Get("/multi-event", [](const Request &, Response &res) {
  21121. res.set_chunked_content_provider(
  21122. "text/event-stream", [](size_t offset, DataSink &sink) {
  21123. if (offset == 0) {
  21124. std::string events = "data: message1\n\ndata: message2\n\n";
  21125. sink.write(events.data(), events.size());
  21126. }
  21127. return false;
  21128. });
  21129. });
  21130. Client client("localhost", get_port());
  21131. sse::SSEClient sse(client, "/multi-event");
  21132. std::vector<std::string> received_messages;
  21133. std::mutex messages_mutex;
  21134. sse.on_message([&](const sse::SSEMessage &msg) {
  21135. std::lock_guard<std::mutex> lock(messages_mutex);
  21136. received_messages.push_back(msg.data);
  21137. });
  21138. sse.set_reconnect_interval(100);
  21139. sse.set_max_reconnect_attempts(1);
  21140. sse.start_async();
  21141. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21142. sse.stop();
  21143. std::lock_guard<std::mutex> lock(messages_mutex);
  21144. EXPECT_GE(received_messages.size(), 2u);
  21145. if (received_messages.size() >= 2) {
  21146. EXPECT_EQ(received_messages[0], "message1");
  21147. EXPECT_EQ(received_messages[1], "message2");
  21148. }
  21149. }
  21150. // Test: on_event for specific types
  21151. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21152. Client client("localhost", get_port());
  21153. sse::SSEClient sse(client, "/custom-events");
  21154. std::atomic<bool> update_received{false};
  21155. std::atomic<bool> delete_received{false};
  21156. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21157. if (msg.data == "updated") { update_received.store(true); }
  21158. });
  21159. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21160. if (msg.data == "deleted") { delete_received.store(true); }
  21161. });
  21162. sse.set_max_reconnect_attempts(1);
  21163. sse.start_async();
  21164. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21165. sse.stop();
  21166. EXPECT_TRUE(update_received.load());
  21167. EXPECT_TRUE(delete_received.load());
  21168. }
  21169. // Test: on_error callback on connection failure
  21170. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21171. // Connect to a non-existent port
  21172. Client client("localhost", 59999);
  21173. sse::SSEClient sse(client, "/events");
  21174. std::atomic<bool> error_called{false};
  21175. Error received_error = Error::Success;
  21176. sse.on_error([&](Error err) {
  21177. error_called.store(true);
  21178. received_error = err;
  21179. });
  21180. sse.set_reconnect_interval(50);
  21181. sse.set_max_reconnect_attempts(1);
  21182. sse.start_async();
  21183. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21184. sse.stop();
  21185. EXPECT_TRUE(error_called.load());
  21186. EXPECT_NE(received_error, Error::Success);
  21187. }
  21188. // Test: Last-Event-ID header sent on reconnect
  21189. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21190. // Endpoint that sends event with ID
  21191. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21192. res.set_chunked_content_provider(
  21193. "text/event-stream", [](size_t offset, DataSink &sink) {
  21194. if (offset == 0) {
  21195. std::string event = "id: evt-123\ndata: test\n\n";
  21196. sink.write(event.data(), event.size());
  21197. }
  21198. return false;
  21199. });
  21200. });
  21201. Client client("localhost", get_port());
  21202. sse::SSEClient sse(client, "/event-with-id");
  21203. std::atomic<bool> id_received{false};
  21204. sse.on_message([&](const sse::SSEMessage &msg) {
  21205. if (!msg.id.empty()) { id_received.store(true); }
  21206. });
  21207. sse.set_reconnect_interval(100);
  21208. sse.set_max_reconnect_attempts(1);
  21209. sse.start_async();
  21210. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21211. sse.stop();
  21212. EXPECT_TRUE(id_received.load());
  21213. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21214. }
  21215. // Test: Manual stop
  21216. TEST_F(SSEIntegrationTest, ManualStop) {
  21217. // Endpoint that sends one event and stays open briefly
  21218. std::atomic<bool> handler_running{true};
  21219. server_->Get("/stay-open", [&handler_running](const Request &,
  21220. Response &res) {
  21221. res.set_chunked_content_provider(
  21222. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21223. if (offset == 0) {
  21224. std::string event = "data: connected\n\n";
  21225. sink.write(event.data(), event.size());
  21226. }
  21227. // Keep connection open while handler_running is true
  21228. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21229. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21230. }
  21231. return false;
  21232. });
  21233. });
  21234. Client client("localhost", get_port());
  21235. sse::SSEClient sse(client, "/stay-open");
  21236. std::atomic<bool> connected{false};
  21237. sse.on_open([&connected]() { connected.store(true); });
  21238. sse.set_reconnect_interval(100);
  21239. sse.set_max_reconnect_attempts(1);
  21240. sse.start_async();
  21241. // Wait for connection to establish
  21242. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21243. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21244. }
  21245. EXPECT_TRUE(connected.load());
  21246. EXPECT_TRUE(sse.is_connected());
  21247. // Signal handler to stop
  21248. handler_running.store(false);
  21249. // Stop SSE client
  21250. sse.stop();
  21251. EXPECT_FALSE(sse.is_connected());
  21252. }
  21253. // Test: SSEClient with custom headers
  21254. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21255. // Setup a server endpoint that checks for custom header
  21256. std::atomic<bool> header_received{false};
  21257. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21258. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21259. header_received.store(true);
  21260. }
  21261. res.set_chunked_content_provider("text/event-stream",
  21262. [](size_t, DataSink &) { return false; });
  21263. });
  21264. Client client("localhost", get_port());
  21265. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21266. sse::SSEClient sse(client, "/header-check", headers);
  21267. sse.set_max_reconnect_attempts(1);
  21268. sse.start_async();
  21269. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21270. sse.stop();
  21271. EXPECT_TRUE(header_received.load());
  21272. }
  21273. // Test: Reconnect interval configuration
  21274. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21275. Client client("localhost", get_port());
  21276. sse::SSEClient sse(client, "/events");
  21277. auto &result = sse.set_reconnect_interval(500);
  21278. // Builder pattern should return reference to self
  21279. EXPECT_EQ(&result, &sse);
  21280. }
  21281. // Test: Max reconnect attempts
  21282. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21283. // Connect to non-existent port to force reconnects
  21284. Client client("localhost", 59998);
  21285. sse::SSEClient sse(client, "/events");
  21286. std::atomic<int> error_count{0};
  21287. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21288. sse.set_reconnect_interval(50);
  21289. sse.set_max_reconnect_attempts(2);
  21290. auto start = std::chrono::steady_clock::now();
  21291. sse.start(); // Blocking call
  21292. auto end = std::chrono::steady_clock::now();
  21293. // Should have stopped after 2 failed attempts
  21294. EXPECT_GE(error_count.load(), 2);
  21295. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21296. auto duration =
  21297. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21298. #ifdef _WIN32
  21299. // Windows is much slower for socket connection failures
  21300. EXPECT_LT(duration.count(), 7000);
  21301. #else
  21302. EXPECT_LT(duration.count(), 1000);
  21303. #endif
  21304. }
  21305. // Test: Multi-line data in integration
  21306. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21307. // Endpoint with multi-line data
  21308. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21309. res.set_chunked_content_provider(
  21310. "text/event-stream", [](size_t offset, DataSink &sink) {
  21311. if (offset == 0) {
  21312. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21313. sink.write(event.data(), event.size());
  21314. }
  21315. return false;
  21316. });
  21317. });
  21318. Client client("localhost", get_port());
  21319. sse::SSEClient sse(client, "/multiline-data");
  21320. std::string received_data;
  21321. std::mutex data_mutex;
  21322. sse.on_message([&](const sse::SSEMessage &msg) {
  21323. std::lock_guard<std::mutex> lock(data_mutex);
  21324. received_data = msg.data;
  21325. });
  21326. sse.set_reconnect_interval(100);
  21327. sse.set_max_reconnect_attempts(1);
  21328. sse.start_async();
  21329. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21330. sse.stop();
  21331. std::lock_guard<std::mutex> lock(data_mutex);
  21332. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21333. }
  21334. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21335. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21336. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21337. DataSink &sink) {
  21338. if (offset == 0) {
  21339. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21340. sink.write(events.data(), events.size());
  21341. }
  21342. return false;
  21343. });
  21344. });
  21345. Client client("localhost", get_port());
  21346. sse::SSEClient sse(client, "/empty-data-lines");
  21347. std::mutex mutex;
  21348. std::condition_variable cv;
  21349. std::vector<std::string> received;
  21350. sse.on_message([&](const sse::SSEMessage &msg) {
  21351. std::lock_guard<std::mutex> lock(mutex);
  21352. received.push_back(msg.data);
  21353. cv.notify_all();
  21354. });
  21355. sse.set_max_reconnect_attempts(1);
  21356. sse.start_async();
  21357. {
  21358. std::unique_lock<std::mutex> lock(mutex);
  21359. cv.wait_for(lock, std::chrono::seconds(2),
  21360. [&] { return received.size() >= 3; });
  21361. }
  21362. sse.stop();
  21363. ASSERT_GE(received.size(), 3u);
  21364. EXPECT_EQ(received[0], "");
  21365. EXPECT_EQ(received[1], "\nhello");
  21366. EXPECT_EQ(received[2], "");
  21367. }
  21368. // Test: Auto-reconnect after server disconnection
  21369. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21370. std::atomic<int> connection_count{0};
  21371. std::atomic<int> message_count{0};
  21372. // Endpoint that sends one event and closes, forcing reconnect
  21373. server_->Get("/reconnect-test",
  21374. [&connection_count](const Request &, Response &res) {
  21375. connection_count.fetch_add(1);
  21376. res.set_chunked_content_provider(
  21377. "text/event-stream", [](size_t offset, DataSink &sink) {
  21378. if (offset == 0) {
  21379. std::string event = "data: hello\n\n";
  21380. sink.write(event.data(), event.size());
  21381. }
  21382. return false; // Close connection after sending
  21383. });
  21384. });
  21385. Client client("localhost", get_port());
  21386. sse::SSEClient sse(client, "/reconnect-test");
  21387. sse.on_message([&message_count](const sse::SSEMessage &) {
  21388. message_count.fetch_add(1);
  21389. });
  21390. sse.set_reconnect_interval(100);
  21391. sse.set_max_reconnect_attempts(3);
  21392. sse.start_async();
  21393. // Wait long enough for multiple reconnects
  21394. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21395. sse.stop();
  21396. // Should have connected multiple times (initial + reconnects)
  21397. EXPECT_GE(connection_count.load(), 2);
  21398. // Should have received messages from multiple connections
  21399. EXPECT_GE(message_count.load(), 2);
  21400. }
  21401. // Test: A retry field that is not all ASCII digits is ignored
  21402. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21403. std::atomic<int> connection_count{0};
  21404. server_->Get("/bad-retry",
  21405. [&connection_count](const Request &, Response &res) {
  21406. connection_count.fetch_add(1);
  21407. res.set_chunked_content_provider(
  21408. "text/event-stream", [](size_t offset, DataSink &sink) {
  21409. if (offset == 0) {
  21410. std::string event = "retry: -1\ndata: hello\n\n";
  21411. sink.write(event.data(), event.size());
  21412. }
  21413. return false;
  21414. });
  21415. });
  21416. Client client("localhost", get_port());
  21417. sse::SSEClient sse(client, "/bad-retry");
  21418. sse.set_reconnect_interval(10000);
  21419. sse.start_async();
  21420. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21421. sse.stop();
  21422. EXPECT_EQ(connection_count.load(), 1);
  21423. }
  21424. // Test: A retry field of all ASCII digits sets the reconnection time
  21425. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21426. std::mutex mutex;
  21427. std::condition_variable cv;
  21428. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21429. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21430. {
  21431. std::lock_guard<std::mutex> lock(mutex);
  21432. connected_at.push_back(std::chrono::steady_clock::now());
  21433. cv.notify_all();
  21434. }
  21435. res.set_chunked_content_provider(
  21436. "text/event-stream", [](size_t offset, DataSink &sink) {
  21437. if (offset == 0) {
  21438. std::string event = "retry: 0\ndata: hello\n\n";
  21439. sink.write(event.data(), event.size());
  21440. }
  21441. return false;
  21442. });
  21443. });
  21444. Client client("localhost", get_port());
  21445. sse::SSEClient sse(client, "/zero-retry");
  21446. sse.set_reconnect_interval(10000);
  21447. sse.start_async();
  21448. {
  21449. std::unique_lock<std::mutex> lock(mutex);
  21450. cv.wait_for(lock, std::chrono::seconds(5),
  21451. [&] { return connected_at.size() >= 2; });
  21452. }
  21453. sse.stop();
  21454. // The server-supplied interval is applied, but never below 100ms, so
  21455. // "retry: 0" does not cause a busy reconnect loop
  21456. std::lock_guard<std::mutex> lock(mutex);
  21457. ASSERT_GE(connected_at.size(), 2u);
  21458. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21459. connected_at[1] - connected_at[0])
  21460. .count();
  21461. EXPECT_GE(interval_ms, 100);
  21462. }
  21463. // Test: Last-Event-ID sent on reconnect
  21464. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21465. std::atomic<int> connection_count{0};
  21466. std::vector<std::string> received_last_event_ids;
  21467. std::mutex id_mutex;
  21468. // Endpoint that checks Last-Event-ID header and sends event with ID
  21469. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21470. int conn = connection_count.fetch_add(1);
  21471. // Capture the Last-Event-ID header from each connection
  21472. {
  21473. std::lock_guard<std::mutex> lock(id_mutex);
  21474. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21475. }
  21476. res.set_chunked_content_provider(
  21477. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21478. if (offset == 0) {
  21479. std::string event =
  21480. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21481. sink.write(event.data(), event.size());
  21482. }
  21483. return false;
  21484. });
  21485. });
  21486. Client client("localhost", get_port());
  21487. sse::SSEClient sse(client, "/reconnect-with-id");
  21488. sse.set_reconnect_interval(100);
  21489. sse.set_max_reconnect_attempts(3);
  21490. sse.start_async();
  21491. // Wait for at least 2 connections
  21492. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21493. sse.stop();
  21494. // Verify behavior
  21495. std::lock_guard<std::mutex> lock(id_mutex);
  21496. EXPECT_GE(received_last_event_ids.size(), 2u);
  21497. // First connection should have no Last-Event-ID
  21498. if (!received_last_event_ids.empty()) {
  21499. EXPECT_EQ(received_last_event_ids[0], "");
  21500. }
  21501. // Second connection should have Last-Event-ID from first connection
  21502. if (received_last_event_ids.size() >= 2) {
  21503. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21504. }
  21505. }
  21506. // Test: set_headers updates headers used on reconnect
  21507. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21508. std::vector<std::string> received_tokens;
  21509. std::mutex token_mutex;
  21510. // Endpoint that captures Authorization header
  21511. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21512. {
  21513. std::lock_guard<std::mutex> lock(token_mutex);
  21514. received_tokens.push_back(req.get_header_value("Authorization"));
  21515. }
  21516. res.set_chunked_content_provider(
  21517. "text/event-stream", [](size_t offset, DataSink &sink) {
  21518. if (offset == 0) {
  21519. std::string event = "data: hello\n\n";
  21520. sink.write(event.data(), event.size());
  21521. }
  21522. return false; // Close connection to trigger reconnect
  21523. });
  21524. });
  21525. Client client("localhost", get_port());
  21526. Headers headers = {{"Authorization", "Bearer old-token"}};
  21527. sse::SSEClient sse(client, "/auth-check", headers);
  21528. // Update headers on each successful connection
  21529. sse.on_open(
  21530. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21531. sse.set_reconnect_interval(100);
  21532. sse.set_max_reconnect_attempts(3);
  21533. sse.start_async();
  21534. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21535. sse.stop();
  21536. std::lock_guard<std::mutex> lock(token_mutex);
  21537. ASSERT_GE(received_tokens.size(), 2u);
  21538. // First connection uses original header
  21539. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21540. // Second connection uses updated header from set_headers
  21541. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21542. }
  21543. // Test: 401 allows reconnection (so on_error can refresh headers)
  21544. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21545. std::atomic<int> connection_count{0};
  21546. // Endpoint: returns 401 on first attempt, 200 on second
  21547. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21548. int conn = connection_count.fetch_add(1);
  21549. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21550. res.status = StatusCode::Unauthorized_401;
  21551. res.set_content("Unauthorized", "text/plain");
  21552. return;
  21553. }
  21554. res.set_chunked_content_provider(
  21555. "text/event-stream", [](size_t offset, DataSink &sink) {
  21556. if (offset == 0) {
  21557. std::string event = "data: authenticated\n\n";
  21558. sink.write(event.data(), event.size());
  21559. }
  21560. return false;
  21561. });
  21562. });
  21563. Client client("localhost", get_port());
  21564. Headers headers = {{"Authorization", "Bearer expired"}};
  21565. sse::SSEClient sse(client, "/auth-retry", headers);
  21566. std::atomic<bool> message_received{false};
  21567. // Refresh token on error
  21568. sse.on_error(
  21569. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21570. sse.on_message([&](const sse::SSEMessage &msg) {
  21571. if (msg.data == "authenticated") { message_received.store(true); }
  21572. });
  21573. sse.set_reconnect_interval(100);
  21574. sse.set_max_reconnect_attempts(3);
  21575. sse.start_async();
  21576. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21577. sse.stop();
  21578. // Should have reconnected after 401 and succeeded with new token
  21579. EXPECT_GE(connection_count.load(), 2);
  21580. EXPECT_TRUE(message_received.load());
  21581. }
  21582. TEST(Issue2318Test, EmptyHostString) {
  21583. {
  21584. httplib::Client cli_empty("", PORT);
  21585. auto res = cli_empty.Get("/");
  21586. ASSERT_FALSE(res);
  21587. EXPECT_EQ(httplib::Error::Connection, res.error());
  21588. }
  21589. {
  21590. httplib::Client cli(" ", PORT);
  21591. auto res = cli.Get("/");
  21592. ASSERT_FALSE(res);
  21593. EXPECT_EQ(httplib::Error::Connection, res.error());
  21594. }
  21595. }
  21596. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21597. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21598. Server svr;
  21599. // Set a small payload limit (1KB)
  21600. svr.set_payload_max_length(1024);
  21601. svr.Post("/test", [&](const Request &req, Response &res) {
  21602. res.set_content("Body size: " + std::to_string(req.body.size()),
  21603. "text/plain");
  21604. });
  21605. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21606. auto se = detail::scope_exit([&] {
  21607. svr.stop();
  21608. listen_thread.join();
  21609. });
  21610. svr.wait_until_ready();
  21611. // Create data that compresses well but exceeds limit when decompressed
  21612. // 8KB of repeated null bytes compresses to a very small size
  21613. std::string original_data(8 * 1024, '\0');
  21614. // Compress the data using gzip
  21615. std::string compressed_data;
  21616. detail::gzip_compressor compressor;
  21617. compressor.compress(original_data.data(), original_data.size(), true,
  21618. [&](const char *data, size_t size) {
  21619. compressed_data.append(data, size);
  21620. return true;
  21621. });
  21622. // Verify compression worked (compressed should be much smaller)
  21623. ASSERT_LT(compressed_data.size(), original_data.size());
  21624. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21625. // Send compressed data with Content-Encoding: gzip
  21626. Client cli(HOST, PORT);
  21627. Headers headers = {{"Content-Encoding", "gzip"}};
  21628. auto res =
  21629. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21630. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21632. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21633. }
  21634. #endif
  21635. // ============================================================================
  21636. // OpenSSL-Specific Tests
  21637. // ============================================================================
  21638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21639. X509 *readCertificate(const std::string &strFileName) {
  21640. std::ifstream inStream(strFileName);
  21641. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21642. std::istreambuf_iterator<char>());
  21643. if (strCertPEM.empty()) return (nullptr);
  21644. BIO *pbCert = BIO_new(BIO_s_mem());
  21645. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21646. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21647. BIO_free(pbCert);
  21648. return (pCert);
  21649. }
  21650. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21651. std::ifstream inStream(strFileName);
  21652. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21653. std::istreambuf_iterator<char>());
  21654. if (strPrivateKeyPEM.empty()) return (nullptr);
  21655. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21656. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21657. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21658. BIO_free(pbPrivKey);
  21659. return (pPrivateKey);
  21660. }
  21661. TEST(BindServerTest, UpdateCerts) {
  21662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21663. int port = svr.bind_to_any_port("0.0.0.0");
  21664. ASSERT_TRUE(svr.is_valid());
  21665. ASSERT_TRUE(port > 0);
  21666. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21667. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21668. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21669. ASSERT_TRUE(cert != nullptr);
  21670. ASSERT_TRUE(ca_cert != nullptr);
  21671. ASSERT_TRUE(key != nullptr);
  21672. X509_STORE *cert_store = X509_STORE_new();
  21673. X509_STORE_add_cert(cert_store, ca_cert);
  21674. // svr.update_certs(cert, key, cert_store); // deprecated
  21675. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21676. CLIENT_CA_CERT_FILE);
  21677. ASSERT_TRUE(svr.is_valid());
  21678. svr.stop();
  21679. X509_STORE_free(cert_store);
  21680. X509_free(cert);
  21681. X509_free(ca_cert);
  21682. EVP_PKEY_free(key);
  21683. }
  21684. // Test that update_certs() updates client CA list correctly
  21685. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21686. // Start with file-based constructor
  21687. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21688. ASSERT_TRUE(svr.is_valid());
  21689. // Initially no client CA list should be set
  21690. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21691. ASSERT_TRUE(ssl_ctx != nullptr);
  21692. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21693. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21694. EXPECT_EQ(0, count_before);
  21695. // Now update with client CA (PEM string)
  21696. std::string cert_pem, key_pem, ca_pem;
  21697. read_file(SERVER_CERT_FILE, cert_pem);
  21698. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21699. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21700. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21701. ASSERT_TRUE(svr.is_valid());
  21702. // Now client CA list should be set
  21703. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21704. ASSERT_TRUE(ca_list_after != nullptr);
  21705. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21706. }
  21707. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21708. // Test that the file-path SSLServer constructor properly sets the client CA
  21709. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21711. ASSERT_TRUE(svr.is_valid());
  21712. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21713. ASSERT_TRUE(ssl_ctx != nullptr);
  21714. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21715. ASSERT_TRUE(ca_list != nullptr);
  21716. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21717. }
  21718. #endif
  21719. // ============================================================================
  21720. // MbedTLS-Specific Tests
  21721. // ============================================================================
  21722. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21723. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21724. using namespace httplib::tls;
  21725. // Track if callback was invoked
  21726. bool callback_invoked = false;
  21727. // The callback receives void* ctx which is actually MbedTlsContext*
  21728. // We can access the mbedtls_ssl_config via the context
  21729. auto setup_callback = [&callback_invoked](void *ctx) {
  21730. callback_invoked = true;
  21731. // Cast to MbedTlsContext* to access the ssl config
  21732. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21733. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21734. // Use static variables to hold certificate data (simplified for test)
  21735. static mbedtls_x509_crt own_cert;
  21736. static mbedtls_pk_context own_key;
  21737. static mbedtls_x509_crt ca_chain;
  21738. static bool initialized = false;
  21739. if (!initialized) {
  21740. mbedtls_x509_crt_init(&own_cert);
  21741. mbedtls_pk_init(&own_key);
  21742. mbedtls_x509_crt_init(&ca_chain);
  21743. // Load server certificate
  21744. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21745. return false;
  21746. }
  21747. // Load server private key.
  21748. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21749. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21750. #if MBEDTLS_VERSION_MAJOR == 3
  21751. ,
  21752. mbedtls_ctr_drbg_random, nullptr
  21753. #endif
  21754. ) != 0) {
  21755. return false;
  21756. }
  21757. // Load CA chain for client verification
  21758. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21759. return false;
  21760. }
  21761. initialized = true;
  21762. }
  21763. // Configure the SSL config
  21764. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21765. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21766. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21767. // Set minimum TLS version using mbedTLS native API
  21768. #if MBEDTLS_VERSION_MAJOR >= 3
  21769. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21770. #else
  21771. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21772. MBEDTLS_SSL_MINOR_VERSION_3);
  21773. #endif
  21774. return true;
  21775. };
  21776. SSLServer svr(setup_callback);
  21777. ASSERT_TRUE(svr.is_valid());
  21778. ASSERT_TRUE(callback_invoked);
  21779. svr.Get("/test", [&](const Request &req, Response &res) {
  21780. res.set_content("test", "text/plain");
  21781. auto cert = req.peer_cert();
  21782. ASSERT_TRUE(static_cast<bool>(cert));
  21783. auto common_name = cert.subject_cn();
  21784. EXPECT_EQ("Common Name", common_name);
  21785. });
  21786. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21787. auto se = detail::scope_exit([&] {
  21788. svr.stop();
  21789. t.join();
  21790. ASSERT_FALSE(svr.is_running());
  21791. });
  21792. svr.wait_until_ready();
  21793. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21794. cli.enable_server_certificate_verification(false);
  21795. cli.set_connection_timeout(30);
  21796. auto res = cli.Get("/test");
  21797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21798. ASSERT_EQ(StatusCode::OK_200, res->status);
  21799. }
  21800. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21801. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21802. // keep-alive SSL session, which reads through that config in
  21803. // mbedtls_ssl_close_notify.
  21804. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21806. ASSERT_TRUE(svr.is_valid());
  21807. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21808. res.set_content("test", "text/plain");
  21809. });
  21810. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21811. auto se = detail::scope_exit([&] {
  21812. svr.stop();
  21813. t.join();
  21814. ASSERT_FALSE(svr.is_running());
  21815. });
  21816. svr.wait_until_ready();
  21817. {
  21818. SSLClient cli(HOST, PORT);
  21819. cli.enable_server_certificate_verification(false);
  21820. cli.set_keep_alive(true);
  21821. auto res = cli.Get("/test");
  21822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21823. ASSERT_EQ(StatusCode::OK_200, res->status);
  21824. // cli is destructed here with the keep-alive SSL session still open.
  21825. }
  21826. }
  21827. #endif
  21828. // WebSocket Tests
  21829. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21830. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21831. // defining the meaning of these bits has been negotiated.
  21832. auto make_frame = [](uint8_t first_byte) {
  21833. std::string frame;
  21834. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21835. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21836. frame += "Hello";
  21837. return frame;
  21838. };
  21839. // RSV1 set (0x40)
  21840. {
  21841. detail::BufferStream strm;
  21842. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21843. ws::Opcode opcode;
  21844. std::string payload;
  21845. bool fin;
  21846. EXPECT_EQ(
  21847. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21848. ws::impl::FrameRead::Fail);
  21849. }
  21850. // RSV2 set (0x20)
  21851. {
  21852. detail::BufferStream strm;
  21853. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21854. ws::Opcode opcode;
  21855. std::string payload;
  21856. bool fin;
  21857. EXPECT_EQ(
  21858. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21859. ws::impl::FrameRead::Fail);
  21860. }
  21861. // RSV3 set (0x10)
  21862. {
  21863. detail::BufferStream strm;
  21864. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21865. ws::Opcode opcode;
  21866. std::string payload;
  21867. bool fin;
  21868. EXPECT_EQ(
  21869. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21870. ws::impl::FrameRead::Fail);
  21871. }
  21872. // No RSV bits set - should succeed
  21873. {
  21874. detail::BufferStream strm;
  21875. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21876. ws::Opcode opcode;
  21877. std::string payload;
  21878. bool fin;
  21879. EXPECT_EQ(
  21880. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21881. ws::impl::FrameRead::Ok);
  21882. EXPECT_EQ(ws::Opcode::Text, opcode);
  21883. EXPECT_EQ("Hello", payload);
  21884. EXPECT_TRUE(fin);
  21885. }
  21886. }
  21887. TEST(WebSocketTest, ControlFrameValidation) {
  21888. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21889. // payload length <= 125.
  21890. // Ping with FIN=0 - must be rejected
  21891. {
  21892. detail::BufferStream strm;
  21893. std::string frame;
  21894. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21895. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21896. strm.write(frame.data(), frame.size());
  21897. ws::Opcode opcode;
  21898. std::string payload;
  21899. bool fin;
  21900. EXPECT_EQ(
  21901. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21902. ws::impl::FrameRead::Fail);
  21903. }
  21904. // Close with FIN=0 - must be rejected
  21905. {
  21906. detail::BufferStream strm;
  21907. std::string frame;
  21908. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21909. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21910. strm.write(frame.data(), frame.size());
  21911. ws::Opcode opcode;
  21912. std::string payload;
  21913. bool fin;
  21914. EXPECT_EQ(
  21915. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21916. ws::impl::FrameRead::Fail);
  21917. }
  21918. // Ping with payload_len=126 (extended length) - must be rejected
  21919. {
  21920. detail::BufferStream strm;
  21921. std::string frame;
  21922. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21923. frame += static_cast<char>(126); // payload_len=126 (>125)
  21924. frame += static_cast<char>(0x00); // extended length high byte
  21925. frame += static_cast<char>(126); // extended length low byte
  21926. frame += std::string(126, 'x');
  21927. strm.write(frame.data(), frame.size());
  21928. ws::Opcode opcode;
  21929. std::string payload;
  21930. bool fin;
  21931. EXPECT_EQ(
  21932. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21933. ws::impl::FrameRead::Fail);
  21934. }
  21935. // Ping with FIN=1 and payload_len=125 - should succeed
  21936. {
  21937. detail::BufferStream strm;
  21938. std::string frame;
  21939. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21940. frame += static_cast<char>(125); // payload_len=125
  21941. frame += std::string(125, 'x');
  21942. strm.write(frame.data(), frame.size());
  21943. ws::Opcode opcode;
  21944. std::string payload;
  21945. bool fin;
  21946. EXPECT_EQ(
  21947. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21948. ws::impl::FrameRead::Ok);
  21949. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21950. EXPECT_EQ(125u, payload.size());
  21951. EXPECT_TRUE(fin);
  21952. }
  21953. }
  21954. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21955. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21956. // length MUST be 0.
  21957. // MSB set - must be rejected
  21958. {
  21959. detail::BufferStream strm;
  21960. std::string frame;
  21961. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21962. frame += static_cast<char>(127); // 64-bit extended length
  21963. frame += static_cast<char>(0x80); // MSB set (invalid)
  21964. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21965. strm.write(frame.data(), frame.size());
  21966. ws::Opcode opcode;
  21967. std::string payload;
  21968. bool fin;
  21969. EXPECT_EQ(
  21970. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21971. ws::impl::FrameRead::Fail);
  21972. }
  21973. // MSB clear - should pass length parsing (will be rejected by max_len,
  21974. // but that's a different check; use a small length to verify)
  21975. {
  21976. detail::BufferStream strm;
  21977. std::string frame;
  21978. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21979. frame += static_cast<char>(127); // 64-bit extended length
  21980. frame += std::string(7, '\0'); // high bytes = 0
  21981. frame += static_cast<char>(0x03); // length = 3
  21982. frame += "abc";
  21983. strm.write(frame.data(), frame.size());
  21984. ws::Opcode opcode;
  21985. std::string payload;
  21986. bool fin;
  21987. EXPECT_EQ(
  21988. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21989. ws::impl::FrameRead::Ok);
  21990. EXPECT_EQ(ws::Opcode::Text, opcode);
  21991. EXPECT_EQ("abc", payload);
  21992. }
  21993. }
  21994. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21995. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21996. // Valid UTF-8
  21997. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21998. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21999. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22000. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22001. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22002. // Invalid UTF-8
  22003. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22004. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22005. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22006. EXPECT_FALSE(
  22007. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22008. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22009. }
  22010. TEST(WebSocketTest, ConnectAndDisconnect) {
  22011. Server svr;
  22012. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22013. std::string msg;
  22014. while (ws.read(msg)) {}
  22015. });
  22016. auto port = svr.bind_to_any_port(HOST);
  22017. std::thread t([&]() { svr.listen_after_bind(); });
  22018. svr.wait_until_ready();
  22019. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22020. auto res = client.connect();
  22021. ASSERT_TRUE(res);
  22022. EXPECT_EQ(Error::Success, res.error());
  22023. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22024. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22025. EXPECT_TRUE(client.is_open());
  22026. client.close();
  22027. EXPECT_FALSE(client.is_open());
  22028. svr.stop();
  22029. t.join();
  22030. }
  22031. TEST(WebSocketTest, ValidURL) {
  22032. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22033. EXPECT_TRUE(ws1.is_valid());
  22034. ws::WebSocketClient ws2("ws://example.com/path");
  22035. EXPECT_TRUE(ws2.is_valid());
  22036. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22037. EXPECT_TRUE(ws3.is_valid());
  22038. #ifdef CPPHTTPLIB_SSL_ENABLED
  22039. ws::WebSocketClient wss1("wss://example.com/path");
  22040. EXPECT_TRUE(wss1.is_valid());
  22041. ws::WebSocketClient wss2("wss://example.com:443/path");
  22042. EXPECT_TRUE(wss2.is_valid());
  22043. #endif
  22044. }
  22045. TEST(WebSocketTest, InvalidURL) {
  22046. // No scheme
  22047. ws::WebSocketClient ws1("localhost:8080/path");
  22048. EXPECT_FALSE(ws1.is_valid());
  22049. // No path
  22050. ws::WebSocketClient ws2("ws://localhost:8080");
  22051. EXPECT_FALSE(ws2.is_valid());
  22052. // Empty string
  22053. ws::WebSocketClient ws3("");
  22054. EXPECT_FALSE(ws3.is_valid());
  22055. // Missing host
  22056. ws::WebSocketClient ws4("ws://:8080/path");
  22057. EXPECT_FALSE(ws4.is_valid());
  22058. // Port number overflow — should not crash
  22059. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22060. EXPECT_FALSE(ws5.is_valid());
  22061. // Port out of range
  22062. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22063. EXPECT_FALSE(ws6.is_valid());
  22064. }
  22065. TEST(WebSocketTest, UnsupportedScheme) {
  22066. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22067. ws::WebSocketClient ws1("http://localhost:8080/path");
  22068. EXPECT_FALSE(ws1.is_valid());
  22069. ws::WebSocketClient ws2("https://localhost:8080/path");
  22070. EXPECT_FALSE(ws2.is_valid());
  22071. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22072. EXPECT_FALSE(ws3.is_valid());
  22073. #else
  22074. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22075. std::invalid_argument);
  22076. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22077. std::invalid_argument);
  22078. #endif
  22079. }
  22080. TEST(WebSocketTest, ConnectWhenInvalid) {
  22081. ws::WebSocketClient ws("not a valid url");
  22082. EXPECT_FALSE(ws.is_valid());
  22083. auto res = ws.connect();
  22084. EXPECT_FALSE(res);
  22085. EXPECT_EQ(Error::Connection, res.error());
  22086. EXPECT_EQ(-1, res.status());
  22087. }
  22088. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22089. // Grab a port that is free, then close it again so nothing listens there
  22090. Server svr;
  22091. auto port = svr.bind_to_any_port(HOST);
  22092. svr.stop();
  22093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22094. auto res = client.connect();
  22095. ASSERT_FALSE(res);
  22096. EXPECT_EQ(Error::Connection, res.error());
  22097. EXPECT_EQ(-1, res.status());
  22098. }
  22099. TEST(WebSocketTest, DefaultPort) {
  22100. ws::WebSocketClient ws1("ws://example.com/path");
  22101. EXPECT_TRUE(ws1.is_valid());
  22102. // ws:// defaults to port 80 (verified by successful parse)
  22103. #ifdef CPPHTTPLIB_SSL_ENABLED
  22104. ws::WebSocketClient ws2("wss://example.com/path");
  22105. EXPECT_TRUE(ws2.is_valid());
  22106. // wss:// defaults to port 443 (verified by successful parse)
  22107. #endif
  22108. }
  22109. TEST(WebSocketTest, IPv6LiteralAddress) {
  22110. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22111. EXPECT_TRUE(ws1.is_valid());
  22112. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22113. EXPECT_TRUE(ws2.is_valid());
  22114. }
  22115. TEST(WebSocketTest, ComplexPath) {
  22116. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22117. EXPECT_TRUE(ws1.is_valid());
  22118. ws::WebSocketClient ws2("ws://localhost:8080/");
  22119. EXPECT_TRUE(ws2.is_valid());
  22120. }
  22121. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22122. Server svr;
  22123. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22124. std::string msg;
  22125. while (ws.read(msg)) {}
  22126. });
  22127. auto port = svr.bind_to_any_port(HOST);
  22128. std::thread t([&]() { svr.listen_after_bind(); });
  22129. svr.wait_until_ready();
  22130. auto another_host = "example.com";
  22131. auto wrong_ip = "192.0.2.1";
  22132. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22133. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22134. ASSERT_TRUE(client.connect());
  22135. EXPECT_TRUE(client.is_open());
  22136. client.close();
  22137. svr.stop();
  22138. t.join();
  22139. }
  22140. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22141. Server svr;
  22142. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22143. std::string msg;
  22144. while (ws.read(msg)) {}
  22145. });
  22146. auto port = svr.bind_to_any_port(HOST);
  22147. std::thread t([&]() { svr.listen_after_bind(); });
  22148. svr.wait_until_ready();
  22149. auto wrong_ip = "192.0.2.1";
  22150. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22151. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22152. client.set_connection_timeout(1);
  22153. client.set_read_timeout(1);
  22154. client.set_write_timeout(1);
  22155. EXPECT_FALSE(client.connect());
  22156. EXPECT_FALSE(client.is_open());
  22157. svr.stop();
  22158. t.join();
  22159. }
  22160. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22161. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22162. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22163. // (RFC 6761) is only a map key and the Host header value.
  22164. auto host = "target.invalid";
  22165. Server svr;
  22166. std::string received_host;
  22167. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22168. received_host = req.get_header_value("Host");
  22169. std::string msg;
  22170. while (ws.read(msg)) {}
  22171. });
  22172. auto port = svr.bind_to_any_port(HOST);
  22173. std::thread t([&]() { svr.listen_after_bind(); });
  22174. // ASSERT_* below returns from the test body, which would leave t joinable
  22175. // and make ~thread call std::terminate.
  22176. auto se = detail::scope_exit([&] {
  22177. svr.stop();
  22178. if (t.joinable()) { t.join(); }
  22179. });
  22180. svr.wait_until_ready();
  22181. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22182. std::to_string(port) + "/ws");
  22183. client.set_hostname_addr_map({{host, HOST}});
  22184. ASSERT_TRUE(client.connect());
  22185. EXPECT_TRUE(client.is_open());
  22186. client.close();
  22187. svr.stop();
  22188. t.join();
  22189. // The mapping only redirects the connection; the identity stays host_.
  22190. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22191. }
  22192. class WebSocketIntegrationTest : public ::testing::Test {
  22193. protected:
  22194. void SetUp() override {
  22195. server_ = httplib::detail::make_unique<Server>();
  22196. setup_server();
  22197. start_server();
  22198. }
  22199. void TearDown() override {
  22200. server_->stop();
  22201. if (server_thread_.joinable()) { server_thread_.join(); }
  22202. }
  22203. void setup_server() {
  22204. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22205. std::string msg;
  22206. ws::ReadResult ret;
  22207. while ((ret = ws.read(msg))) {
  22208. if (ret == ws::Binary) {
  22209. ws.send(msg.data(), msg.size());
  22210. } else {
  22211. ws.send(msg);
  22212. }
  22213. }
  22214. });
  22215. server_->WebSocket("/ws-echo-string",
  22216. [](const Request &, ws::WebSocket &ws) {
  22217. std::string msg;
  22218. while (ws.read(msg)) {
  22219. ws.send("echo: " + msg);
  22220. }
  22221. });
  22222. server_->WebSocket(
  22223. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22224. // Echo back request metadata
  22225. ws.send("path:" + req.path);
  22226. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22227. std::string msg;
  22228. while (ws.read(msg)) {}
  22229. });
  22230. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22231. std::string msg;
  22232. ws.read(msg); // wait for a message
  22233. ws.close();
  22234. });
  22235. server_->WebSocket("/ws-close-status",
  22236. [](const Request &, ws::WebSocket &ws) {
  22237. std::string msg;
  22238. ws.read(msg); // wait for a message
  22239. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22240. });
  22241. server_->WebSocket(
  22242. "/ws-subprotocol",
  22243. [](const Request &, ws::WebSocket &ws) {
  22244. std::string msg;
  22245. while (ws.read(msg)) {
  22246. ws.send(msg);
  22247. }
  22248. },
  22249. [](const std::vector<std::string> &protocols) -> std::string {
  22250. for (const auto &p : protocols) {
  22251. if (p == "graphql-ws") { return p; }
  22252. }
  22253. return "";
  22254. });
  22255. server_->WebSocket(
  22256. "/ws-subprotocol-unoffered",
  22257. [](const Request &, ws::WebSocket &ws) {
  22258. std::string msg;
  22259. while (ws.read(msg)) {
  22260. ws.send(msg);
  22261. }
  22262. },
  22263. [](const std::vector<std::string> &) -> std::string {
  22264. return "admin";
  22265. });
  22266. }
  22267. void start_server() {
  22268. port_ = server_->bind_to_any_port(HOST);
  22269. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22270. server_->wait_until_ready();
  22271. }
  22272. std::unique_ptr<Server> server_;
  22273. std::thread server_thread_;
  22274. int port_ = 0;
  22275. };
  22276. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22277. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22278. "/ws-echo");
  22279. ASSERT_TRUE(client.connect());
  22280. ASSERT_TRUE(client.is_open());
  22281. ASSERT_TRUE(client.send("Hello WebSocket"));
  22282. std::string msg;
  22283. EXPECT_EQ(ws::Text, client.read(msg));
  22284. EXPECT_EQ("Hello WebSocket", msg);
  22285. client.close();
  22286. }
  22287. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22288. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22289. "/ws-echo");
  22290. ASSERT_TRUE(client.connect());
  22291. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22292. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22293. std::string msg;
  22294. EXPECT_EQ(ws::Binary, client.read(msg));
  22295. EXPECT_EQ(binary_data, msg);
  22296. client.close();
  22297. }
  22298. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22300. "/ws-echo");
  22301. ASSERT_TRUE(client.connect());
  22302. for (int i = 0; i < 10; i++) {
  22303. auto text = "message " + std::to_string(i);
  22304. ASSERT_TRUE(client.send(text));
  22305. std::string msg;
  22306. ASSERT_TRUE(client.read(msg));
  22307. EXPECT_EQ(text, msg);
  22308. }
  22309. client.close();
  22310. }
  22311. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22312. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22313. "/ws-close");
  22314. ASSERT_TRUE(client.connect());
  22315. // Send a message to trigger the server to close
  22316. ASSERT_TRUE(client.send("trigger close"));
  22317. // The server will close, so read should return false
  22318. std::string msg;
  22319. EXPECT_FALSE(client.read(msg));
  22320. EXPECT_FALSE(client.is_open());
  22321. }
  22322. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22323. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22324. "/ws-echo");
  22325. ASSERT_TRUE(client.connect());
  22326. // 128KB message
  22327. std::string large_data(128 * 1024, 'X');
  22328. ASSERT_TRUE(client.send(large_data));
  22329. std::string msg;
  22330. ASSERT_TRUE(client.read(msg));
  22331. EXPECT_EQ(large_data, msg);
  22332. client.close();
  22333. }
  22334. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22336. "/ws-echo");
  22337. ASSERT_TRUE(client.connect());
  22338. const int num_threads = 4;
  22339. std::vector<std::thread> threads;
  22340. std::atomic<int> send_count{0};
  22341. for (int t = 0; t < num_threads; t++) {
  22342. threads.emplace_back([&client, &send_count, t]() {
  22343. for (int i = 0; i < 5; i++) {
  22344. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22345. if (client.send(text)) { send_count++; }
  22346. }
  22347. });
  22348. }
  22349. for (auto &th : threads) {
  22350. th.join();
  22351. }
  22352. int received = 0;
  22353. std::string msg;
  22354. while (received < send_count.load()) {
  22355. if (!client.read(msg)) { break; }
  22356. received++;
  22357. }
  22358. EXPECT_EQ(send_count.load(), received);
  22359. client.close();
  22360. }
  22361. TEST_F(WebSocketIntegrationTest, ReadString) {
  22362. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22363. "/ws-echo-string");
  22364. ASSERT_TRUE(client.connect());
  22365. ASSERT_TRUE(client.send("hello"));
  22366. std::string msg;
  22367. ASSERT_TRUE(client.read(msg));
  22368. EXPECT_EQ("echo: hello", msg);
  22369. ASSERT_TRUE(client.send("world"));
  22370. ASSERT_TRUE(client.read(msg));
  22371. EXPECT_EQ("echo: world", msg);
  22372. client.close();
  22373. }
  22374. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22375. Headers headers = {{"X-Test-Header", "test-value"}};
  22376. ws::WebSocketClient client(
  22377. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22378. ASSERT_TRUE(client.connect());
  22379. std::string msg;
  22380. ASSERT_TRUE(client.read(msg));
  22381. EXPECT_EQ("path:/ws-request-info", msg);
  22382. ASSERT_TRUE(client.read(msg));
  22383. EXPECT_EQ("header:test-value", msg);
  22384. client.close();
  22385. }
  22386. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22388. "/ws-echo");
  22389. client.set_read_timeout(1, 0); // 1 second
  22390. ASSERT_TRUE(client.connect());
  22391. // Don't send anything — server echo handler waits for a message, so read()
  22392. // should time out. The connection survives it: nothing was consumed.
  22393. std::string msg;
  22394. EXPECT_EQ(client.read(msg), ws::Timeout);
  22395. EXPECT_TRUE(client.is_open());
  22396. // And it is still usable afterwards.
  22397. EXPECT_TRUE(client.send("after timeout"));
  22398. EXPECT_EQ(client.read(msg), ws::Text);
  22399. EXPECT_EQ(msg, "after timeout");
  22400. }
  22401. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22402. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22403. "/ws-echo");
  22404. client.set_read_timeout(1, 0);
  22405. ASSERT_TRUE(client.connect());
  22406. ASSERT_TRUE(client.send("first"));
  22407. std::string msg;
  22408. ASSERT_EQ(client.read(msg), ws::Text);
  22409. ASSERT_EQ(msg, "first");
  22410. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22411. // not be used with a read timeout: it would reprocess the previous message.
  22412. EXPECT_EQ(client.read(msg), ws::Timeout);
  22413. EXPECT_EQ(msg, "first");
  22414. }
  22415. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22416. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22417. "/ws-echo");
  22418. ASSERT_TRUE(client.connect());
  22419. // Setting it once the connection is open reaches the live stream, not just
  22420. // the seed for the next connect().
  22421. client.set_read_timeout(1, 0);
  22422. std::string msg;
  22423. EXPECT_EQ(client.read(msg), ws::Timeout);
  22424. EXPECT_TRUE(client.is_open());
  22425. }
  22426. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22428. "/ws-echo");
  22429. client.set_read_timeout(5, 0);
  22430. ASSERT_TRUE(client.connect());
  22431. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22432. // The server should reject it and close the connection.
  22433. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22434. client.send(oversized);
  22435. // The server's read() should have failed due to payload limit,
  22436. // so our read() should return false (connection closed).
  22437. std::string msg;
  22438. EXPECT_FALSE(client.read(msg));
  22439. }
  22440. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22441. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22442. "/ws-echo");
  22443. client.set_read_timeout(10, 0);
  22444. ASSERT_TRUE(client.connect());
  22445. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22446. // This should succeed.
  22447. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22448. ASSERT_TRUE(client.send(at_limit));
  22449. std::string msg;
  22450. ASSERT_TRUE(client.read(msg));
  22451. EXPECT_EQ(at_limit.size(), msg.size());
  22452. client.close();
  22453. }
  22454. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22455. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22456. "/nonexistent");
  22457. auto res = client.connect();
  22458. EXPECT_FALSE(res);
  22459. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22460. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22461. EXPECT_FALSE(client.is_open());
  22462. }
  22463. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22465. "/ws-echo");
  22466. ASSERT_TRUE(client.connect());
  22467. ASSERT_TRUE(client.send(""));
  22468. std::string msg;
  22469. EXPECT_EQ(ws::Text, client.read(msg));
  22470. EXPECT_EQ("", msg);
  22471. client.close();
  22472. }
  22473. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22474. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22475. "/ws-echo");
  22476. // First connection
  22477. ASSERT_TRUE(client.connect());
  22478. ASSERT_TRUE(client.send("first"));
  22479. std::string msg;
  22480. ASSERT_TRUE(client.read(msg));
  22481. EXPECT_EQ("first", msg);
  22482. client.close();
  22483. EXPECT_FALSE(client.is_open());
  22484. // Reconnect using the same client object
  22485. ASSERT_TRUE(client.connect());
  22486. ASSERT_TRUE(client.is_open());
  22487. ASSERT_TRUE(client.send("second"));
  22488. ASSERT_TRUE(client.read(msg));
  22489. EXPECT_EQ("second", msg);
  22490. client.close();
  22491. }
  22492. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22493. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22494. "/ws-close-status");
  22495. ASSERT_TRUE(client.connect());
  22496. // Trigger the server to close with GoingAway status
  22497. ASSERT_TRUE(client.send("trigger"));
  22498. // read() should return false after receiving the close frame
  22499. std::string msg;
  22500. EXPECT_FALSE(client.read(msg));
  22501. EXPECT_FALSE(client.is_open());
  22502. }
  22503. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22504. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22505. "/ws-echo");
  22506. ASSERT_TRUE(client.connect());
  22507. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22508. EXPECT_FALSE(client.is_open());
  22509. }
  22510. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22511. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22512. ws::WebSocketClient client(
  22513. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22514. ASSERT_TRUE(client.connect());
  22515. // Server should have selected graphql-ws
  22516. EXPECT_EQ("graphql-ws", client.subprotocol());
  22517. client.close();
  22518. }
  22519. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22520. Headers headers;
  22521. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22522. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22523. ws::WebSocketClient client(
  22524. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22525. ASSERT_TRUE(client.connect());
  22526. // The offer on the second field line counts too, so graphql-ws is selected
  22527. EXPECT_EQ("graphql-ws", client.subprotocol());
  22528. client.close();
  22529. }
  22530. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22531. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22532. ws::WebSocketClient client(
  22533. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22534. ASSERT_TRUE(client.connect());
  22535. // Server should not have selected any subprotocol
  22536. EXPECT_TRUE(client.subprotocol().empty());
  22537. client.close();
  22538. }
  22539. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22540. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22541. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22542. "/ws-subprotocol-unoffered",
  22543. headers);
  22544. ASSERT_TRUE(client.connect());
  22545. EXPECT_TRUE(client.subprotocol().empty());
  22546. client.close();
  22547. }
  22548. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22549. // Connect without requesting any subprotocol
  22550. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22551. "/ws-subprotocol");
  22552. ASSERT_TRUE(client.connect());
  22553. EXPECT_TRUE(client.subprotocol().empty());
  22554. client.close();
  22555. }
  22556. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22557. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22558. "/ws-echo");
  22559. client.set_tcp_nodelay(true);
  22560. client.set_connection_timeout(3, 0);
  22561. bool socket_options_called = false;
  22562. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22563. ASSERT_TRUE(client.connect());
  22564. ASSERT_TRUE(client.is_open());
  22565. EXPECT_TRUE(socket_options_called);
  22566. ASSERT_TRUE(client.send("hello"));
  22567. std::string msg;
  22568. auto result = client.read(msg);
  22569. EXPECT_EQ(result, ws::ReadResult::Text);
  22570. EXPECT_EQ(msg, "hello");
  22571. client.close();
  22572. }
  22573. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22574. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22575. "/ws-echo");
  22576. client.set_connection_timeout(std::chrono::seconds(3));
  22577. client.set_write_timeout(std::chrono::seconds(3));
  22578. // A sub-second remainder exercises the seconds/microseconds split.
  22579. client.set_read_timeout(std::chrono::milliseconds(1500));
  22580. ASSERT_TRUE(client.connect());
  22581. auto start = std::chrono::steady_clock::now();
  22582. std::string msg;
  22583. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22584. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22585. std::chrono::steady_clock::now() - start)
  22586. .count();
  22587. // Above 1s so that dropping the microseconds half of the split fails here.
  22588. // Ignoring the setter altogether would not reach this line at all: a client
  22589. // waits forever by default.
  22590. EXPECT_GE(elapsed, 1400);
  22591. EXPECT_LT(elapsed, 30000);
  22592. }
  22593. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22594. Server svr;
  22595. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22596. if (!req.has_header("Authorization")) {
  22597. res.status = StatusCode::Unauthorized_401;
  22598. res.set_content("Unauthorized", "text/plain");
  22599. return Server::HandlerResponse::Handled;
  22600. }
  22601. return Server::HandlerResponse::Unhandled;
  22602. });
  22603. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22604. std::string msg;
  22605. while (ws.read(msg)) {
  22606. ws.send(msg);
  22607. }
  22608. });
  22609. auto port = svr.bind_to_any_port("localhost");
  22610. std::thread t([&]() { svr.listen_after_bind(); });
  22611. svr.wait_until_ready();
  22612. // Without Authorization header - should be rejected before upgrade
  22613. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22614. EXPECT_FALSE(client1.connect());
  22615. // The rejection is framed like any other HTTP response
  22616. {
  22617. Client cli("localhost", port);
  22618. Headers headers = {{"Upgrade", "websocket"},
  22619. {"Connection", "Upgrade"},
  22620. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22621. {"Sec-WebSocket-Version", "13"}};
  22622. auto res = cli.Get("/ws", headers);
  22623. ASSERT_TRUE(res);
  22624. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22625. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22626. EXPECT_EQ("Unauthorized", res->body);
  22627. }
  22628. // With Authorization header - should succeed
  22629. Headers headers = {{"Authorization", "Bearer token123"}};
  22630. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22631. headers);
  22632. ASSERT_TRUE(client2.connect());
  22633. ASSERT_TRUE(client2.send("hello"));
  22634. std::string msg;
  22635. ASSERT_TRUE(client2.read(msg));
  22636. EXPECT_EQ("hello", msg);
  22637. client2.close();
  22638. svr.stop();
  22639. t.join();
  22640. }
  22641. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22642. Server svr;
  22643. std::atomic<int> pre_request_calls{0};
  22644. std::atomic<bool> route_matched{false};
  22645. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22646. pre_request_calls++;
  22647. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22648. if (req.get_header_value("Authorization") != "Bearer token123") {
  22649. res.status = StatusCode::Unauthorized_401;
  22650. res.set_content("Unauthorized", "text/plain");
  22651. return Server::HandlerResponse::Handled;
  22652. }
  22653. return Server::HandlerResponse::Unhandled;
  22654. });
  22655. std::atomic<bool> handler_called{false};
  22656. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22657. handler_called = true;
  22658. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22659. });
  22660. auto port = svr.bind_to_any_port("localhost");
  22661. std::thread t([&]() { svr.listen_after_bind(); });
  22662. svr.wait_until_ready();
  22663. // Without Authorization header - should be rejected before upgrade
  22664. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22665. "/ws/1");
  22666. EXPECT_FALSE(client1.connect());
  22667. EXPECT_FALSE(handler_called);
  22668. EXPECT_EQ(1, pre_request_calls);
  22669. EXPECT_TRUE(route_matched);
  22670. // The rejection is an ordinary HTTP response, not a protocol switch
  22671. {
  22672. Client cli("localhost", port);
  22673. Headers headers = {{"Upgrade", "websocket"},
  22674. {"Connection", "Upgrade"},
  22675. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22676. {"Sec-WebSocket-Version", "13"}};
  22677. auto res = cli.Get("/ws/1", headers);
  22678. ASSERT_TRUE(res);
  22679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22680. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22681. EXPECT_EQ("Unauthorized", res->body);
  22682. }
  22683. EXPECT_FALSE(handler_called);
  22684. // With Authorization header - should succeed
  22685. Headers headers = {{"Authorization", "Bearer token123"}};
  22686. ws::WebSocketClient client2(
  22687. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22688. ASSERT_TRUE(client2.connect());
  22689. std::string msg;
  22690. ASSERT_TRUE(client2.read(msg));
  22691. EXPECT_EQ("/ws/:id 2", msg);
  22692. EXPECT_TRUE(handler_called);
  22693. client2.close();
  22694. svr.stop();
  22695. t.join();
  22696. }
  22697. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22698. Server svr;
  22699. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22700. // A read timeout is how a handler gets control back. Without it, a handler
  22701. // parked in read() can never write on the connection it is reading.
  22702. ws.set_read_timeout(std::chrono::milliseconds(100));
  22703. std::string msg;
  22704. while (ws.is_open()) {
  22705. auto r = ws.read(msg);
  22706. if (r == httplib::ws::Timeout) {
  22707. ws.send("tick");
  22708. continue;
  22709. }
  22710. if (r == httplib::ws::Fail) { break; }
  22711. ws.send(msg);
  22712. }
  22713. });
  22714. auto port = svr.bind_to_any_port("localhost");
  22715. std::thread t([&]() { svr.listen_after_bind(); });
  22716. svr.wait_until_ready();
  22717. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22718. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22719. ASSERT_TRUE(client.connect());
  22720. // The client sends nothing, so anything it receives came out of the
  22721. // handler's timeout path.
  22722. std::string msg;
  22723. ASSERT_EQ(client.read(msg), ws::Text);
  22724. EXPECT_EQ("tick", msg);
  22725. client.close();
  22726. svr.stop();
  22727. t.join();
  22728. }
  22729. // Stream::read may return fewer bytes than asked for. This is that contract at
  22730. // its worst -- one byte per call -- which is what a frame header straddling a
  22731. // read buffer's boundary looks like to the frame parser.
  22732. class WsByteAtATimeStream : public Stream {
  22733. public:
  22734. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22735. bool is_readable() const override { return true; }
  22736. bool wait_readable() const override { return true; }
  22737. bool wait_writable() const override { return true; }
  22738. ssize_t read(char *ptr, size_t size) override {
  22739. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22740. *ptr = data_[pos_++];
  22741. return 1;
  22742. }
  22743. ssize_t write(const char *, size_t size) override {
  22744. return static_cast<ssize_t>(size);
  22745. }
  22746. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22747. ip = "127.0.0.1";
  22748. port = 0;
  22749. }
  22750. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22751. ip = "127.0.0.1";
  22752. port = 0;
  22753. }
  22754. socket_t socket() const override { return INVALID_SOCKET; }
  22755. time_t duration() const override { return 0; }
  22756. private:
  22757. std::string data_;
  22758. size_t pos_ = 0;
  22759. };
  22760. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22761. // The payload uses the 16-bit extended length, so the header, the length
  22762. // and the mask key are all multi-byte fields here. Each used to be read
  22763. // with a single read() call, which fails as soon as one is split. The
  22764. // payload is also a little over one read chunk, so it is read in two.
  22765. std::string body;
  22766. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22767. body += static_cast<char>(i % 251);
  22768. }
  22769. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22770. std::string frame;
  22771. frame += static_cast<char>(0x81); // FIN + Text
  22772. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22773. frame += static_cast<char>(body.size() >> 8);
  22774. frame += static_cast<char>(body.size() & 0xff);
  22775. for (size_t i = 0; i < 4; i++) {
  22776. frame += static_cast<char>(mask[i]);
  22777. }
  22778. for (size_t i = 0; i < body.size(); i++) {
  22779. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22780. }
  22781. WsByteAtATimeStream strm(frame);
  22782. ws::Opcode opcode;
  22783. std::string payload;
  22784. bool fin = false;
  22785. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22786. /*expect_masked=*/true, body.size()),
  22787. ws::impl::FrameRead::Ok);
  22788. EXPECT_TRUE(fin);
  22789. EXPECT_EQ(opcode, ws::Opcode::Text);
  22790. EXPECT_EQ(payload, body);
  22791. }
  22792. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22793. std::string body(2000, 'x');
  22794. std::string frame;
  22795. frame += static_cast<char>(0x82); // FIN + Binary
  22796. frame += static_cast<char>(126); // 16-bit length follows
  22797. frame += static_cast<char>(body.size() >> 8);
  22798. frame += static_cast<char>(body.size() & 0xff);
  22799. frame += body;
  22800. detail::BufferStream strm;
  22801. strm.write(frame.data(), frame.size());
  22802. ws::Opcode opcode;
  22803. std::string payload;
  22804. bool fin;
  22805. EXPECT_EQ(
  22806. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22807. ws::impl::FrameRead::Ok);
  22808. EXPECT_EQ(body, payload);
  22809. }
  22810. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22811. // The header announces the largest payload allowed, and only 3 bytes of it
  22812. // ever arrive.
  22813. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22814. std::string frame;
  22815. frame += static_cast<char>(0x82); // FIN + Binary
  22816. frame += static_cast<char>(127); // 64-bit length follows
  22817. for (int shift = 56; shift >= 0; shift -= 8) {
  22818. frame += static_cast<char>((len >> shift) & 0xff);
  22819. }
  22820. frame += "abc";
  22821. detail::BufferStream strm;
  22822. strm.write(frame.data(), frame.size());
  22823. ws::Opcode opcode;
  22824. std::string payload;
  22825. bool fin;
  22826. EXPECT_EQ(
  22827. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22828. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22829. ws::impl::FrameRead::Fail);
  22830. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22831. }
  22832. TEST(WebSocketTest, QueryStringInHandshake) {
  22833. Server svr;
  22834. std::mutex mtx;
  22835. std::string received_target;
  22836. std::string received_token;
  22837. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22838. {
  22839. std::lock_guard<std::mutex> lock(mtx);
  22840. received_target = req.target;
  22841. if (req.has_param("token")) {
  22842. received_token = req.get_param_value("token");
  22843. }
  22844. }
  22845. std::string msg;
  22846. while (ws.read(msg)) {
  22847. ws.send(msg);
  22848. }
  22849. });
  22850. auto port = svr.bind_to_any_port("localhost");
  22851. std::thread t([&]() { svr.listen_after_bind(); });
  22852. svr.wait_until_ready();
  22853. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22854. "/ws?token=ABC&session=123");
  22855. ASSERT_TRUE(client.connect());
  22856. // Round-trip ensures the handler has run and captured the request.
  22857. ASSERT_TRUE(client.send("hello"));
  22858. std::string msg;
  22859. ASSERT_TRUE(client.read(msg));
  22860. EXPECT_EQ("hello", msg);
  22861. client.close();
  22862. {
  22863. std::lock_guard<std::mutex> lock(mtx);
  22864. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22865. EXPECT_EQ("ABC", received_token);
  22866. }
  22867. svr.stop();
  22868. t.join();
  22869. }
  22870. // Run a handshake against a throwaway server and hand the request the server
  22871. // received back to the caller, so tests can assert on the headers the client
  22872. // actually put on the wire.
  22873. static void capture_websocket_handshake_request(
  22874. const Headers &client_headers,
  22875. std::function<void(const Request &, int port)> verify) {
  22876. Server svr;
  22877. std::mutex mtx;
  22878. Request received;
  22879. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22880. {
  22881. std::lock_guard<std::mutex> lock(mtx);
  22882. received = req;
  22883. }
  22884. std::string msg;
  22885. while (ws.read(msg)) {
  22886. ws.send(msg);
  22887. }
  22888. });
  22889. auto port = svr.bind_to_any_port("localhost");
  22890. std::thread t([&]() { svr.listen_after_bind(); });
  22891. auto se = detail::scope_exit([&] {
  22892. svr.stop();
  22893. t.join();
  22894. });
  22895. svr.wait_until_ready();
  22896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22897. client_headers);
  22898. ASSERT_TRUE(client.connect());
  22899. ASSERT_TRUE(client.send("hello"));
  22900. std::string msg;
  22901. ASSERT_TRUE(client.read(msg));
  22902. client.close();
  22903. {
  22904. std::lock_guard<std::mutex> lock(mtx);
  22905. verify(received, port);
  22906. }
  22907. }
  22908. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22909. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22910. // Non-default port must be present in the Host header. Default ports
  22911. // (80/443) are omitted; that logic is covered by
  22912. // MakeHostAndPortStringTest.
  22913. EXPECT_EQ("localhost:" + std::to_string(port),
  22914. req.get_header_value("Host"));
  22915. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22916. req.get_header_value("User-Agent"));
  22917. EXPECT_FALSE(req.has_header("Accept"));
  22918. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22919. EXPECT_FALSE(req.has_header("Content-Length"));
  22920. });
  22921. }
  22922. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22923. capture_websocket_handshake_request(
  22924. {{"Host", "example.com"},
  22925. {"User-Agent", "custom-agent"},
  22926. {"X-Custom", "value"}},
  22927. [](const Request &req, int) {
  22928. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22929. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22930. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22931. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22932. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22933. });
  22934. }
  22935. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22936. capture_websocket_handshake_request(
  22937. {{"Upgrade", "bogus"},
  22938. {"Connection", "close"},
  22939. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22940. {"Sec-WebSocket-Version", "8"}},
  22941. [](const Request &req, int) {
  22942. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22943. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22944. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22945. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22946. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22947. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22948. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22949. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22950. req.get_header_value("Sec-WebSocket-Key"));
  22951. });
  22952. }
  22953. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22954. // A header the client refuses to send must abort the handshake before any
  22955. // part of it reaches the wire; a lone request line would otherwise sit in
  22956. // the peer's buffer as a truncated request.
  22957. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22958. ASSERT_NE(INVALID_SOCKET, srv);
  22959. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22960. sockaddr_in addr{};
  22961. addr.sin_family = AF_INET;
  22962. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22963. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22964. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22965. ASSERT_EQ(0, ::listen(srv, 1));
  22966. sockaddr_in bound{};
  22967. socklen_t bound_len = sizeof(bound);
  22968. ASSERT_EQ(
  22969. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22970. auto port = ntohs(bound.sin_port);
  22971. ssize_t received = -1;
  22972. std::thread t([&] {
  22973. // Bound every blocking call so a regression fails the test with a bad
  22974. // value instead of hanging the suite.
  22975. fd_set rfds;
  22976. FD_ZERO(&rfds);
  22977. FD_SET(srv, &rfds);
  22978. timeval tv{5, 0};
  22979. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22980. 0) {
  22981. return;
  22982. }
  22983. sockaddr_in cli_addr{};
  22984. socklen_t cli_len = sizeof(cli_addr);
  22985. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22986. if (cli == INVALID_SOCKET) { return; }
  22987. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22988. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22989. char buf[4096];
  22990. received = ::recv(cli, buf, sizeof(buf), 0);
  22991. });
  22992. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22993. // connect() has already shut the socket down by the time it returns false,
  22994. // so the peer sees EOF without waiting for the client to be destroyed.
  22995. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22996. {{"X-Bad", "a\r\nInjected: 1"}});
  22997. EXPECT_FALSE(client.connect());
  22998. t.join();
  22999. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23000. EXPECT_EQ(0, received);
  23001. }
  23002. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23003. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23004. // contains "upgrade" as a substring is a different token and must not
  23005. // start a WebSocket handshake.
  23006. auto make_request = [](const std::vector<std::string> &connection_values) {
  23007. Request req;
  23008. req.method = "GET";
  23009. req.headers.emplace("Upgrade", "websocket");
  23010. for (const auto &value : connection_values) {
  23011. req.headers.emplace("Connection", value);
  23012. }
  23013. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23014. req.headers.emplace("Sec-WebSocket-Version", "13");
  23015. return req;
  23016. };
  23017. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23018. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23019. EXPECT_TRUE(
  23020. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23021. EXPECT_TRUE(
  23022. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23023. EXPECT_TRUE(
  23024. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23025. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23026. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23027. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23028. EXPECT_FALSE(
  23029. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23030. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23031. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23032. }
  23033. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23034. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23035. // asks recipients to match each protocol-name case-insensitively, and RFC
  23036. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23037. // client naming websocket alongside another protocol, or on a second field
  23038. // line, is offering websocket; a value that merely contains "websocket" as a
  23039. // substring is a different protocol name and is not.
  23040. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23041. Request req;
  23042. req.method = "GET";
  23043. for (const auto &value : upgrade_values) {
  23044. req.headers.emplace("Upgrade", value);
  23045. }
  23046. req.headers.emplace("Connection", "Upgrade");
  23047. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23048. req.headers.emplace("Sec-WebSocket-Version", "13");
  23049. return req;
  23050. };
  23051. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23052. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23053. EXPECT_TRUE(
  23054. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23055. EXPECT_TRUE(
  23056. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23057. EXPECT_TRUE(
  23058. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23059. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23060. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23061. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23062. EXPECT_FALSE(
  23063. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23064. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23065. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23066. }
  23067. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23068. Server svr;
  23069. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23070. auto port = svr.bind_to_any_port("localhost");
  23071. std::thread t([&]() { svr.listen_after_bind(); });
  23072. auto se = detail::scope_exit([&] {
  23073. svr.stop();
  23074. t.join();
  23075. });
  23076. svr.wait_until_ready();
  23077. Headers headers = {{"Upgrade", "websocket"},
  23078. {"Connection", "notupgrade"},
  23079. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23080. {"Sec-WebSocket-Version", "13"}};
  23081. Client cli("localhost", port);
  23082. auto res = cli.Get("/ws", headers);
  23083. // The route exists only as a WebSocket route, so a request that fails the
  23084. // handshake check falls through to ordinary routing.
  23085. ASSERT_TRUE(res);
  23086. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23087. }
  23088. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23089. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23090. // Connection value is the only thing left for the client to reject.
  23091. Server svr;
  23092. svr.Get("/ws", [](const Request &req, Response &res) {
  23093. res.status = StatusCode::SwitchingProtocol_101;
  23094. res.set_header("Upgrade", "websocket");
  23095. res.set_header("Connection", "notupgrade");
  23096. res.set_header("Sec-WebSocket-Accept",
  23097. detail::websocket_accept_key(
  23098. req.get_header_value("Sec-WebSocket-Key")));
  23099. });
  23100. auto port = svr.bind_to_any_port("localhost");
  23101. std::thread t([&]() { svr.listen_after_bind(); });
  23102. auto se = detail::scope_exit([&] {
  23103. svr.stop();
  23104. t.join();
  23105. });
  23106. svr.wait_until_ready();
  23107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23108. auto res = client.connect();
  23109. EXPECT_FALSE(res);
  23110. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23111. EXPECT_FALSE(client.is_open());
  23112. }
  23113. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23114. Server svr;
  23115. svr.Get("/ws", [](const Request &req, Response &res) {
  23116. res.status = StatusCode::SwitchingProtocol_101;
  23117. res.set_header("Upgrade", "websocket");
  23118. res.set_header("Connection", "Upgrade");
  23119. res.set_header("Sec-WebSocket-Accept",
  23120. detail::websocket_accept_key(
  23121. req.get_header_value("Sec-WebSocket-Key")));
  23122. res.set_header("Sec-WebSocket-Protocol", "admin");
  23123. });
  23124. auto port = svr.bind_to_any_port("localhost");
  23125. std::thread t([&]() { svr.listen_after_bind(); });
  23126. auto se = detail::scope_exit([&] {
  23127. svr.stop();
  23128. t.join();
  23129. });
  23130. svr.wait_until_ready();
  23131. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23132. // Server selects a subprotocol the client never offered
  23133. {
  23134. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23135. ws::WebSocketClient client(url, headers);
  23136. auto res = client.connect();
  23137. EXPECT_FALSE(res);
  23138. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23139. EXPECT_FALSE(client.is_open());
  23140. EXPECT_TRUE(client.subprotocol().empty());
  23141. }
  23142. // Client offered none but the server named one anyway
  23143. {
  23144. ws::WebSocketClient client(url);
  23145. auto res = client.connect();
  23146. EXPECT_FALSE(res);
  23147. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23148. EXPECT_FALSE(client.is_open());
  23149. EXPECT_TRUE(client.subprotocol().empty());
  23150. }
  23151. }
  23152. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23153. // The socket path doubles as the URL host, so it must not contain '/'.
  23154. const char *shard = getenv("GTEST_SHARD_INDEX");
  23155. const std::string sock_path =
  23156. shard ? std::string("httplib-ws-") + shard + ".sock"
  23157. : std::string("httplib-ws.sock");
  23158. std::remove(sock_path.c_str());
  23159. Server svr;
  23160. std::mutex mtx;
  23161. std::string received_host;
  23162. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23163. {
  23164. std::lock_guard<std::mutex> lock(mtx);
  23165. received_host = req.get_header_value("Host");
  23166. }
  23167. std::string msg;
  23168. while (ws.read(msg)) {
  23169. ws.send(msg);
  23170. }
  23171. });
  23172. svr.set_address_family(AF_UNIX);
  23173. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23174. auto se = detail::scope_exit([&] {
  23175. svr.stop();
  23176. t.join();
  23177. std::remove(sock_path.c_str());
  23178. });
  23179. svr.wait_until_ready();
  23180. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23181. client.set_address_family(AF_UNIX);
  23182. ASSERT_TRUE(client.connect());
  23183. ASSERT_TRUE(client.send("hello"));
  23184. std::string msg;
  23185. ASSERT_TRUE(client.read(msg));
  23186. client.close();
  23187. {
  23188. std::lock_guard<std::mutex> lock(mtx);
  23189. // There is no host:port for a Unix socket, so the same "localhost"
  23190. // placeholder the HTTP client uses is expected.
  23191. EXPECT_EQ("localhost", received_host);
  23192. }
  23193. }
  23194. // Two threads must never parse WebSocket frames from the same stream.
  23195. // close() used to read the peer's Close reply with its own frame read, so it
  23196. // raced a reader thread that was in the middle of a payload: the payload loop
  23197. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23198. // so bytes taken by close() were replaced with bytes from further along the
  23199. // stream. The message kept its length and silently changed content.
  23200. //
  23201. // The raw peer below sends a frame header plus part of the payload, waits for
  23202. // the handler to call close(), and only then sends the rest. Whichever thread
  23203. // would win the race for those bytes, the message must arrive intact, because
  23204. // close() must not touch the stream while read() owns it.
  23205. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23206. #ifndef _WIN32
  23207. signal(SIGPIPE, SIG_IGN);
  23208. #endif
  23209. const size_t payload_len = 120; // fits the 7-bit length field
  23210. const size_t prefix_len = 8;
  23211. const int attempts = 8;
  23212. std::string expected(payload_len, '\0');
  23213. for (size_t i = 0; i < payload_len; i++) {
  23214. expected[i] = static_cast<char>('a' + i % 26);
  23215. }
  23216. std::atomic<bool> peer_stalled{false};
  23217. std::atomic<bool> handler_done{false};
  23218. std::mutex received_mutex;
  23219. std::vector<std::string> received;
  23220. // Bound every wait, so a regression fails the test instead of hanging the
  23221. // suite.
  23222. auto wait_for = [](const std::atomic<bool> &flag) {
  23223. for (int i = 0; i < 500 && !flag; i++) {
  23224. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23225. }
  23226. };
  23227. Server svr;
  23228. svr.set_websocket_ping_interval(0);
  23229. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23230. std::thread reader([&]() {
  23231. std::string msg;
  23232. while (ws.read(msg)) {
  23233. std::lock_guard<std::mutex> guard(received_mutex);
  23234. received.push_back(msg);
  23235. }
  23236. });
  23237. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23238. // inside read_websocket_frame() when close() runs.
  23239. wait_for(peer_stalled);
  23240. ws.close();
  23241. reader.join();
  23242. handler_done = true;
  23243. });
  23244. auto port = svr.bind_to_any_port("127.0.0.1");
  23245. std::thread t([&]() { svr.listen_after_bind(); });
  23246. auto se = detail::scope_exit([&] {
  23247. svr.stop();
  23248. t.join();
  23249. });
  23250. svr.wait_until_ready();
  23251. auto send_bytes = [](socket_t s, const std::string &data) {
  23252. #ifdef _WIN32
  23253. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23254. #else
  23255. auto n = ::send(s, data.data(), data.size(), 0);
  23256. #endif
  23257. return n == static_cast<decltype(n)>(data.size());
  23258. };
  23259. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23260. // Every length used here fits the 7-bit length field.
  23261. auto masked_header = [](uint8_t first_byte, size_t len) {
  23262. std::string h;
  23263. h += static_cast<char>(first_byte);
  23264. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23265. h.append(4, '\0'); // mask key
  23266. return h;
  23267. };
  23268. for (int attempt = 0; attempt < attempts; attempt++) {
  23269. peer_stalled = false;
  23270. handler_done = false;
  23271. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23272. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23273. auto se_sock = detail::scope_exit([&] {
  23274. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23275. });
  23276. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23277. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23278. sockaddr_in addr{};
  23279. addr.sin_family = AF_INET;
  23280. addr.sin_port = htons(static_cast<uint16_t>(port));
  23281. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23282. ASSERT_EQ(
  23283. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23284. << "attempt " << attempt;
  23285. ASSERT_TRUE(send_bytes(sock,
  23286. "GET /ws HTTP/1.1\r\n"
  23287. "Host: 127.0.0.1\r\n"
  23288. "Upgrade: websocket\r\n"
  23289. "Connection: Upgrade\r\n"
  23290. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23291. "Sec-WebSocket-Version: 13\r\n"
  23292. "\r\n"))
  23293. << "attempt " << attempt;
  23294. std::string response;
  23295. while (response.find("\r\n\r\n") == std::string::npos) {
  23296. char buf[512];
  23297. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23298. if (n <= 0) { break; }
  23299. response.append(buf, static_cast<size_t>(n));
  23300. }
  23301. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23302. << "attempt " << attempt;
  23303. // Send the header of a Binary message but only the first prefix_len bytes
  23304. // of its payload, leaving the reader thread stalled inside the payload.
  23305. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23306. expected.substr(0, prefix_len)))
  23307. << "attempt " << attempt;
  23308. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23309. peer_stalled = true;
  23310. // Let close() send its Close frame and park in its own read before the
  23311. // rest of the payload arrives, so both threads are waiting for it.
  23312. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23313. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23314. close_frame += static_cast<char>(0x03); // status 1000
  23315. close_frame += static_cast<char>(0xE8);
  23316. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23317. << "attempt " << attempt;
  23318. // Closing the peer releases the reader thread even on the buggy path,
  23319. // where it waits for bytes another thread already consumed.
  23320. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23321. detail::close_socket(sock);
  23322. sock = INVALID_SOCKET;
  23323. wait_for(handler_done);
  23324. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23325. }
  23326. std::lock_guard<std::mutex> guard(received_mutex);
  23327. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23328. << "a message in flight when close() ran was dropped";
  23329. for (size_t i = 0; i < received.size(); i++) {
  23330. EXPECT_EQ(expected, received[i]) << "message " << i;
  23331. }
  23332. }
  23333. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23334. // returning the socket, or INVALID_SOCKET.
  23335. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23336. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23337. if (sock == INVALID_SOCKET) { return sock; }
  23338. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23339. sockaddr_in addr{};
  23340. addr.sin_family = AF_INET;
  23341. addr.sin_port = htons(static_cast<uint16_t>(port));
  23342. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23343. std::string req = "GET " + path +
  23344. " HTTP/1.1\r\n"
  23345. "Host: 127.0.0.1\r\n"
  23346. "Upgrade: websocket\r\n"
  23347. "Connection: Upgrade\r\n"
  23348. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23349. "Sec-WebSocket-Version: 13\r\n"
  23350. "\r\n";
  23351. std::string res;
  23352. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23353. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23354. static_cast<int>(req.size())) {
  23355. char c;
  23356. while (res.find("\r\n\r\n") == std::string::npos &&
  23357. ::recv(sock, &c, 1, 0) == 1) {
  23358. res += c;
  23359. }
  23360. }
  23361. if (res.find(" 101 ") == std::string::npos) {
  23362. detail::close_socket(sock);
  23363. return INVALID_SOCKET;
  23364. }
  23365. return sock;
  23366. }
  23367. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23368. // The payload must fit the 7-bit length field.
  23369. static std::string masked_frame(uint8_t first_byte,
  23370. const std::string &payload) {
  23371. std::string f;
  23372. f += static_cast<char>(first_byte);
  23373. f += static_cast<char>(0x80 | payload.size());
  23374. f.append(4, '\0');
  23375. return f + payload;
  23376. }
  23377. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23378. std::atomic<bool> done{false};
  23379. std::string received;
  23380. Server svr;
  23381. svr.set_websocket_ping_interval(0);
  23382. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23383. std::string msg;
  23384. if (ws.read(msg) == ws::Binary) { received = msg; }
  23385. done = true;
  23386. });
  23387. auto port = svr.bind_to_any_port("127.0.0.1");
  23388. std::thread t([&]() { svr.listen_after_bind(); });
  23389. auto se = detail::scope_exit([&] {
  23390. svr.stop();
  23391. t.join();
  23392. });
  23393. svr.wait_until_ready();
  23394. auto sock = connect_raw_websocket(port, "/ws");
  23395. ASSERT_NE(INVALID_SOCKET, sock);
  23396. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23397. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23398. masked_frame(0x89, "p") + // FIN + Ping
  23399. masked_frame(0x80, "lo"); // FIN + Continuation
  23400. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23401. for (int i = 0; i < 500 && !done; i++) {
  23402. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23403. }
  23404. ASSERT_TRUE(done);
  23405. EXPECT_EQ("Hello", received);
  23406. // The Ping between the fragments is answered with a Pong.
  23407. char pong[3];
  23408. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23409. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23410. }
  23411. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23412. Server svr;
  23413. svr.set_websocket_ping_interval(-1);
  23414. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23415. std::string msg;
  23416. while (ws.read(msg)) {}
  23417. });
  23418. auto port = svr.bind_to_any_port("127.0.0.1");
  23419. std::thread t([&]() { svr.listen_after_bind(); });
  23420. auto se = detail::scope_exit([&] {
  23421. svr.stop();
  23422. t.join();
  23423. });
  23424. svr.wait_until_ready();
  23425. auto sock = connect_raw_websocket(port, "/ws");
  23426. ASSERT_NE(INVALID_SOCKET, sock);
  23427. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23428. // Nothing comes while the client stays quiet.
  23429. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23430. char c;
  23431. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23432. }
  23433. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23434. Server svr;
  23435. svr.set_websocket_ping_interval(0);
  23436. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23437. std::string msg;
  23438. while (ws.read(msg)) {}
  23439. });
  23440. auto port = svr.bind_to_any_port("127.0.0.1");
  23441. std::thread t([&]() { svr.listen_after_bind(); });
  23442. auto se = detail::scope_exit([&] {
  23443. svr.stop();
  23444. t.join();
  23445. });
  23446. svr.wait_until_ready();
  23447. // Each Close payload and the reply it should get: an echo when valid, 1002
  23448. // otherwise.
  23449. std::vector<std::pair<std::string, std::string>> cases = {
  23450. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23451. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23452. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23453. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23454. };
  23455. // Also between the fragments of a message.
  23456. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23457. for (const auto &c : cases) {
  23458. auto sock = connect_raw_websocket(port, "/ws");
  23459. ASSERT_NE(INVALID_SOCKET, sock);
  23460. auto frames = prefix + masked_frame(0x88, c.first);
  23461. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23462. std::string reply;
  23463. char buf[256];
  23464. while (reply.size() < 2 + c.second.size()) {
  23465. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23466. if (n <= 0) { break; }
  23467. reply.append(buf, static_cast<size_t>(n));
  23468. }
  23469. detail::close_socket(sock);
  23470. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23471. c.second,
  23472. reply);
  23473. }
  23474. }
  23475. }
  23476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23477. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23478. protected:
  23479. void SetUp() override {
  23480. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23481. SERVER_PRIVATE_KEY_FILE);
  23482. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23483. std::string msg;
  23484. ws::ReadResult ret;
  23485. while ((ret = ws.read(msg))) {
  23486. if (ret == ws::Binary) {
  23487. ws.send(msg.data(), msg.size());
  23488. } else {
  23489. ws.send(msg);
  23490. }
  23491. }
  23492. });
  23493. port_ = server_->bind_to_any_port(HOST);
  23494. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23495. server_->wait_until_ready();
  23496. }
  23497. void TearDown() override {
  23498. server_->stop();
  23499. if (server_thread_.joinable()) { server_thread_.join(); }
  23500. }
  23501. std::unique_ptr<SSLServer> server_;
  23502. std::thread server_thread_;
  23503. int port_ = 0;
  23504. };
  23505. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23506. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23507. {
  23508. ws::WebSocketClient client(url);
  23509. client.enable_server_certificate_verification(false);
  23510. auto calls = 0;
  23511. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23512. calls++;
  23513. return false;
  23514. });
  23515. EXPECT_FALSE(client.connect());
  23516. EXPECT_GT(calls, 0);
  23517. }
  23518. {
  23519. ws::WebSocketClient client(url);
  23520. client.enable_server_certificate_verification(false);
  23521. client.set_session_verifier([](tls::session_t) {
  23522. return SSLVerifierResponse::CertificateRejected;
  23523. });
  23524. EXPECT_FALSE(client.connect());
  23525. }
  23526. {
  23527. ws::WebSocketClient client(url);
  23528. client.enable_server_certificate_verification(false);
  23529. client.set_session_verifier([](tls::session_t) {
  23530. return SSLVerifierResponse::CertificateAccepted;
  23531. });
  23532. EXPECT_TRUE(client.connect());
  23533. }
  23534. }
  23535. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23536. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23537. "/ws-echo");
  23538. client.enable_server_certificate_verification(false);
  23539. ASSERT_TRUE(client.connect());
  23540. ASSERT_TRUE(client.is_open());
  23541. ASSERT_TRUE(client.send("Hello WSS"));
  23542. std::string msg;
  23543. EXPECT_EQ(ws::Text, client.read(msg));
  23544. EXPECT_EQ("Hello WSS", msg);
  23545. client.close();
  23546. }
  23547. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23548. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23549. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23550. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23551. // client (without calling close() first) is the only path that runs
  23552. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23553. // bug exactly.
  23554. //
  23555. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23556. // when linked against an instrumented libssl; run under Valgrind to catch it
  23557. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23558. // suite (the freed session otherwise stalls on the close handshake) — this test
  23559. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23560. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23561. {
  23562. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23563. "/ws-echo");
  23564. client.enable_server_certificate_verification(false);
  23565. client.set_read_timeout(2, 0);
  23566. client.set_write_timeout(2, 0);
  23567. ASSERT_TRUE(client.connect());
  23568. ASSERT_TRUE(client.is_open());
  23569. ASSERT_TRUE(client.send("still open"));
  23570. // Intentionally do NOT call client.close(): leaving scope runs
  23571. // shutdown_and_close() with the WebSocket still open, which must send the
  23572. // close frame while the TLS session is still alive.
  23573. }
  23574. }
  23575. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23576. // shutdown_and_close() at the start of connect(), reproducing the same
  23577. // use-after-free within the test body rather than at scope exit. The second
  23578. // connect must succeed and echo, proving the close handshake ran over a live
  23579. // session. See the note above about memory-tool requirements.
  23580. TEST_F(WebSocketSSLIntegrationTest,
  23581. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23582. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23583. "/ws-echo");
  23584. client.enable_server_certificate_verification(false);
  23585. client.set_read_timeout(2, 0);
  23586. client.set_write_timeout(2, 0);
  23587. ASSERT_TRUE(client.connect());
  23588. ASSERT_TRUE(client.is_open());
  23589. ASSERT_TRUE(client.send("still open"));
  23590. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23591. // the still-open connection, which must not touch a freed TLS session.
  23592. ASSERT_TRUE(client.connect());
  23593. ASSERT_TRUE(client.is_open());
  23594. ASSERT_TRUE(client.send("after reconnect"));
  23595. std::string msg;
  23596. EXPECT_EQ(ws::Text, client.read(msg));
  23597. EXPECT_EQ("after reconnect", msg);
  23598. client.close();
  23599. }
  23600. #endif
  23601. #ifdef CPPHTTPLIB_SSL_ENABLED
  23602. class WebSocketSSLCATest : public ::testing::Test {
  23603. protected:
  23604. void SetUp() override {
  23605. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23606. SERVER_PRIVATE_KEY_FILE);
  23607. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23608. std::string msg;
  23609. while (ws.read(msg)) {
  23610. ws.send(msg);
  23611. }
  23612. });
  23613. port_ = server_->bind_to_any_port("127.0.0.1");
  23614. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23615. server_->wait_until_ready();
  23616. }
  23617. void TearDown() override {
  23618. server_->stop();
  23619. if (server_thread_.joinable()) { server_thread_.join(); }
  23620. }
  23621. std::string url() const {
  23622. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23623. }
  23624. std::unique_ptr<SSLServer> server_;
  23625. std::thread server_thread_;
  23626. int port_ = 0;
  23627. };
  23628. // A custom CA loaded as PEM verifies the server with full certificate
  23629. // verification enabled
  23630. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23631. ws::WebSocketClient client(url());
  23632. std::string cert;
  23633. read_file(SERVER_CERT2_FILE, cert);
  23634. client.load_ca_cert_store(cert.c_str(), cert.size());
  23635. ASSERT_TRUE(client.connect());
  23636. ASSERT_TRUE(client.send("hello"));
  23637. std::string msg;
  23638. EXPECT_EQ(ws::Text, client.read(msg));
  23639. EXPECT_EQ("hello", msg);
  23640. client.close();
  23641. }
  23642. // A custom CA that does not cover the server must fail verification (the
  23643. // custom CA is exclusive; system certs are not loaded alongside it)
  23644. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23645. ws::WebSocketClient client(url());
  23646. std::string cert;
  23647. read_file(CLIENT_CA_CERT_FILE, cert);
  23648. client.load_ca_cert_store(cert.c_str(), cert.size());
  23649. auto res = client.connect();
  23650. ASSERT_FALSE(res);
  23651. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23652. EXPECT_EQ(-1, res.status());
  23653. EXPECT_NE(0u, res.ssl_backend_error());
  23654. }
  23655. // The same CA as a file path rather than PEM in memory
  23656. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23657. ws::WebSocketClient client(url());
  23658. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23659. ASSERT_TRUE(client.connect());
  23660. ASSERT_TRUE(client.send("hello"));
  23661. std::string msg;
  23662. EXPECT_EQ(ws::Text, client.read(msg));
  23663. EXPECT_EQ("hello", msg);
  23664. client.close();
  23665. }
  23666. // ...and a CA file that does not cover the server still fails, so it is the
  23667. // path above that decides the outcome
  23668. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23669. ws::WebSocketClient client(url());
  23670. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23671. ASSERT_FALSE(client.connect());
  23672. }
  23673. // Regression test: reconnecting with a native custom CA store used to reuse
  23674. // a store handle the previous TLS context had already freed (use-after-free
  23675. // under the OpenSSL backend). The context now lives as long as the client.
  23676. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23677. ws::WebSocketClient client(url());
  23678. std::string cert;
  23679. read_file(SERVER_CERT2_FILE, cert);
  23680. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23681. ASSERT_TRUE(client.connect());
  23682. client.close();
  23683. ASSERT_TRUE(client.connect());
  23684. ASSERT_TRUE(client.send("again"));
  23685. std::string msg;
  23686. EXPECT_EQ(ws::Text, client.read(msg));
  23687. EXPECT_EQ("again", msg);
  23688. client.close();
  23689. }
  23690. // Regression test: a certificate with a trusted chain but no identity match
  23691. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23692. // verification entirely for IP hosts, so this connection succeeded there.
  23693. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23694. // chain verification while the identity check must still fail.
  23695. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23697. ASSERT_TRUE(svr.is_valid());
  23698. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23699. std::string msg;
  23700. while (ws.read(msg)) {
  23701. ws.send(msg);
  23702. }
  23703. });
  23704. auto port = svr.bind_to_any_port("127.0.0.1");
  23705. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23706. auto se = detail::scope_exit([&] {
  23707. svr.stop();
  23708. t.join();
  23709. });
  23710. svr.wait_until_ready();
  23711. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23712. "/echo");
  23713. std::string cert;
  23714. read_file(SERVER_CERT_FILE, cert);
  23715. client.load_ca_cert_store(cert.c_str(), cert.size());
  23716. ASSERT_FALSE(client.connect());
  23717. }
  23718. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23719. // SNI, so nothing binds the host name to the TLS session. These bind the
  23720. // server to "localhost" instead, the only shape that exercises the SNI and
  23721. // hostname-verification path with certificate verification left enabled.
  23722. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23723. protected:
  23724. void Start(const char *cert_file) {
  23725. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23726. SERVER_PRIVATE_KEY_FILE);
  23727. ASSERT_TRUE(server_->is_valid());
  23728. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23729. std::string msg;
  23730. while (ws.read(msg)) {
  23731. ws.send(msg);
  23732. }
  23733. });
  23734. port_ = server_->bind_to_any_port("localhost");
  23735. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23736. server_->wait_until_ready();
  23737. }
  23738. void TearDown() override {
  23739. if (server_) { server_->stop(); }
  23740. if (server_thread_.joinable()) { server_thread_.join(); }
  23741. }
  23742. std::string url() const {
  23743. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23744. }
  23745. std::unique_ptr<SSLServer> server_;
  23746. std::thread server_thread_;
  23747. int port_ = 0;
  23748. };
  23749. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23750. // out and the connection is usable
  23751. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23752. Start(SERVER_CERT2_FILE);
  23753. ws::WebSocketClient client(url());
  23754. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23755. ASSERT_TRUE(client.connect());
  23756. ASSERT_TRUE(client.send("hello"));
  23757. std::string msg;
  23758. EXPECT_EQ(ws::Text, client.read(msg));
  23759. EXPECT_EQ("hello", msg);
  23760. client.close();
  23761. }
  23762. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23763. // while the identity check must still reject "localhost"
  23764. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23765. Start(SERVER_CERT_FILE);
  23766. ws::WebSocketClient client(url());
  23767. client.set_ca_cert_path(SERVER_CERT_FILE);
  23768. auto res = client.connect();
  23769. ASSERT_FALSE(res);
  23770. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23771. EXPECT_EQ(-1, res.status());
  23772. }
  23773. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23774. // disabled: the chain is still checked, only the identity check is skipped
  23775. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23776. Start(SERVER_CERT_FILE);
  23777. ws::WebSocketClient client(url());
  23778. client.set_ca_cert_path(SERVER_CERT_FILE);
  23779. client.enable_server_hostname_verification(false);
  23780. ASSERT_TRUE(client.connect());
  23781. ASSERT_TRUE(client.send("hello"));
  23782. std::string msg;
  23783. EXPECT_EQ(ws::Text, client.read(msg));
  23784. EXPECT_EQ("hello", msg);
  23785. client.close();
  23786. }
  23787. // A CA that did not sign the server certificate fails the chain, even though
  23788. // the name would match
  23789. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23790. Start(SERVER_CERT2_FILE);
  23791. ws::WebSocketClient client(url());
  23792. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23793. ASSERT_FALSE(client.connect());
  23794. }
  23795. // With verification disabled, neither the chain nor the name is checked
  23796. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23797. Start(SERVER_CERT_FILE);
  23798. ws::WebSocketClient client(url());
  23799. client.enable_server_certificate_verification(false);
  23800. ASSERT_TRUE(client.connect());
  23801. ASSERT_TRUE(client.send("hello"));
  23802. std::string msg;
  23803. EXPECT_EQ(ws::Text, client.read(msg));
  23804. EXPECT_EQ("hello", msg);
  23805. client.close();
  23806. }
  23807. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23808. protected:
  23809. void SetUp() override {
  23810. server_ = httplib::detail::make_unique<SSLServer>(
  23811. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23812. ASSERT_TRUE(server_->is_valid());
  23813. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23814. std::string msg;
  23815. while (ws.read(msg)) {
  23816. ws.send(msg);
  23817. }
  23818. });
  23819. port_ = server_->bind_to_any_port("localhost");
  23820. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23821. server_->wait_until_ready();
  23822. }
  23823. void TearDown() override {
  23824. server_->stop();
  23825. if (server_thread_.joinable()) { server_thread_.join(); }
  23826. }
  23827. std::string url() const {
  23828. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23829. }
  23830. void ConnectWithClientCert(const std::string &client_cert_file,
  23831. const std::string &client_private_key_file,
  23832. const char *private_key_password) {
  23833. std::string cert_pem, key_pem;
  23834. read_file(client_cert_file, cert_pem);
  23835. read_file(client_private_key_file, key_pem);
  23836. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23837. key_pem.c_str(), key_pem.size(),
  23838. private_key_password};
  23839. ws::WebSocketClient client(url(), pem);
  23840. ASSERT_TRUE(client.is_valid());
  23841. client.enable_server_certificate_verification(false);
  23842. ASSERT_TRUE(client.connect());
  23843. ASSERT_TRUE(client.send("hello"));
  23844. std::string msg;
  23845. EXPECT_EQ(ws::Text, client.read(msg));
  23846. EXPECT_EQ("hello", msg);
  23847. client.close();
  23848. }
  23849. std::unique_ptr<SSLServer> server_;
  23850. std::thread server_thread_;
  23851. int port_ = 0;
  23852. };
  23853. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23854. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23855. }
  23856. // Control for the tests above: the fixture's server really does require a
  23857. // client certificate, so it is the PEM the constructor installed that decides
  23858. // the outcome.
  23859. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23860. ws::WebSocketClient client(url());
  23861. ASSERT_TRUE(client.is_valid());
  23862. client.enable_server_certificate_verification(false);
  23863. EXPECT_FALSE(client.connect());
  23864. }
  23865. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23866. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23867. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23868. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23869. }
  23870. #endif
  23871. #if !defined(_WIN32)
  23872. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23873. auto secret_dir = std::string("./symlink_test_secret");
  23874. auto served_dir = std::string("./symlink_test_served");
  23875. auto secret_file = secret_dir + "/secret.txt";
  23876. auto symlink_path = served_dir + "/escape";
  23877. // Setup: create directories and files
  23878. mkdir(secret_dir.c_str(), 0755);
  23879. mkdir(served_dir.c_str(), 0755);
  23880. {
  23881. std::ofstream ofs(secret_file);
  23882. ofs << "SECRET_DATA";
  23883. }
  23884. // Create symlink using absolute path so it resolves correctly
  23885. #ifdef PATH_MAX
  23886. char abs_secret[PATH_MAX];
  23887. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23888. #else
  23889. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23890. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23891. ASSERT_NE(nullptr, abs_secret);
  23892. #endif
  23893. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23894. auto se = detail::scope_exit([&] {
  23895. unlink(symlink_path.c_str());
  23896. unlink(secret_file.c_str());
  23897. rmdir(served_dir.c_str());
  23898. rmdir(secret_dir.c_str());
  23899. });
  23900. Server svr;
  23901. svr.set_mount_point("/", served_dir);
  23902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23903. auto se2 = detail::scope_exit([&] {
  23904. svr.stop();
  23905. listen_thread.join();
  23906. });
  23907. svr.wait_until_ready();
  23908. Client cli("localhost", PORT);
  23909. // Symlink pointing outside base dir should be blocked
  23910. auto res = cli.Get("/escape/secret.txt");
  23911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23912. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23913. }
  23914. #endif
  23915. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23916. // "GET /smuggled" request), reads the first response, and only then sends the
  23917. // embedded request as the body. Returns how many times /smuggled ran.
  23918. //
  23919. // The body is sent AFTER receiving the first response (as in the original
  23920. // PoC) so that the stream_line_reader cannot buffer it together with the
  23921. // headers of the first request.
  23922. static int count_smuggled_requests(const std::string &outer_head,
  23923. std::string &first_response) {
  23924. Server svr;
  23925. svr.set_mount_point("/", "./www");
  23926. std::atomic<int> smuggled_count(0);
  23927. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23928. smuggled_count++;
  23929. res.set_content("oops", "text/plain");
  23930. });
  23931. svr.Post("/post", [&](const Request &req, Response &res) {
  23932. res.set_content(req.body, "text/plain");
  23933. });
  23934. auto port = svr.bind_to_any_port("localhost");
  23935. thread t = thread([&] { svr.listen_after_bind(); });
  23936. auto se = detail::scope_exit([&] {
  23937. svr.stop();
  23938. t.join();
  23939. });
  23940. svr.wait_until_ready();
  23941. auto error = Error::Success;
  23942. auto sock = detail::create_client_socket(
  23943. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23944. /*connection_timeout_sec=*/2, 0,
  23945. /*read_timeout_sec=*/2, 0,
  23946. /*write_timeout_sec=*/2, 0, std::string(), error);
  23947. EXPECT_NE(INVALID_SOCKET, sock);
  23948. if (sock == INVALID_SOCKET) { return -1; }
  23949. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23950. // The "smuggled" request will be sent as the body of the outer request
  23951. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23952. "Host: localhost\r\n"
  23953. "Connection: close\r\n"
  23954. "\r\n";
  23955. auto head = outer_head;
  23956. auto len = std::to_string(smuggled.size());
  23957. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23958. pos = head.find("{len}", pos + len.size())) {
  23959. head.replace(pos, 5, len);
  23960. }
  23961. // Step 1: Send only the outer request headers (no body yet)
  23962. auto sent = send(sock, head.data(), head.size(), 0);
  23963. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23964. // Step 2: Read the first response
  23965. char buf[4096];
  23966. for (;;) {
  23967. auto n = recv(sock, buf, sizeof(buf), 0);
  23968. if (n <= 0) break;
  23969. first_response.append(buf, static_cast<size_t>(n));
  23970. // Stop once we have a complete response (headers + body)
  23971. auto hdr_end = first_response.find("\r\n\r\n");
  23972. if (hdr_end != std::string::npos) {
  23973. // Check for Content-Length to know when the body is complete
  23974. auto cl_pos = first_response.find("Content-Length:");
  23975. if (cl_pos != std::string::npos) {
  23976. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23977. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23978. auto cl = std::stoul(
  23979. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23980. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23981. } else {
  23982. break; // No Content-Length, assume headers-only response
  23983. }
  23984. }
  23985. }
  23986. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23987. // vulnerable server the keep-alive loop reads this as a second request. The
  23988. // server may already have closed the connection, so the result is ignored.
  23989. send(sock, smuggled.data(), smuggled.size(), 0);
  23990. // Half-close so that a server which drained the body sees EOF and closes,
  23991. // instead of the read below waiting for the read timeout.
  23992. #ifdef _WIN32
  23993. ::shutdown(sock, SD_SEND);
  23994. #else
  23995. ::shutdown(sock, SHUT_WR);
  23996. #endif
  23997. // Step 4: Read until the server closes the connection
  23998. for (;;) {
  23999. auto n = recv(sock, buf, sizeof(buf), 0);
  24000. if (n <= 0) break;
  24001. }
  24002. return smuggled_count.load();
  24003. }
  24004. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24005. // A GET request with Content-Length to a static file handler must have its
  24006. // body drained before the keep-alive connection is reused. Otherwise the
  24007. // unread body bytes are interpreted as the next HTTP request.
  24008. std::string first_response;
  24009. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24010. "Host: localhost\r\n"
  24011. "Content-Length: {len}\r\n"
  24012. "\r\n",
  24013. first_response));
  24014. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24015. }
  24016. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24017. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24018. // be answered with 400 and the connection closed. Treating it as "no body"
  24019. // leaves the body to be parsed as the next request.
  24020. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24021. const char *targets[] = {
  24022. "GET /file", // handler that never reads the body
  24023. "GET /not-found", // no handler matches (404)
  24024. "POST /post", // handler that reads the body
  24025. };
  24026. for (auto target : targets) {
  24027. for (auto value : values) {
  24028. std::string first_response;
  24029. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24030. " HTTP/1.1\r\n"
  24031. "Host: localhost\r\n"
  24032. "Content-Length: " +
  24033. value + "\r\n\r\n",
  24034. first_response))
  24035. << target << " with Content-Length: " << value;
  24036. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24037. << target << " with Content-Length: " << value;
  24038. }
  24039. }
  24040. }
  24041. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24042. // A 400 for an unparseable request line leaves the rest of the message
  24043. // unread, so the connection must be closed rather than reused.
  24044. std::string first_response;
  24045. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24046. "Host: localhost\r\n"
  24047. "Content-Length: {len}\r\n"
  24048. "\r\n",
  24049. first_response));
  24050. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24051. }
  24052. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24053. // Same as above for a header block that fails to parse.
  24054. std::string first_response;
  24055. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24056. "Host: localhost\r\n"
  24057. "Bad Header\r\n"
  24058. "Content-Length: {len}\r\n"
  24059. "\r\n",
  24060. first_response));
  24061. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24062. }
  24063. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24064. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24065. // server must not read another request on that connection, even when the
  24066. // request had no body to drain.
  24067. std::string first_response;
  24068. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24069. "Host: localhost\r\n"
  24070. "\r\n",
  24071. first_response));
  24072. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24073. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24074. }
  24075. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24076. // A content reader that stops early leaves the stream inside the body.
  24077. // Draining the whole Content-Length from there, or reading the body again,
  24078. // reads into the next request, and whatever follows is parsed as a request
  24079. // of its own.
  24080. Server svr;
  24081. std::atomic<int> smuggled_count(0);
  24082. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24083. svr.Post("/upload", [](const Request &req, Response &res,
  24084. const ContentReader &content_reader) {
  24085. // Stop at the last chunk, so the whole body has been read however it
  24086. // arrives.
  24087. auto length = req.get_header_value_u64("Content-Length");
  24088. size_t total = 0;
  24089. auto consumed = content_reader([&](const char *, size_t n) {
  24090. total += n;
  24091. return total < length;
  24092. });
  24093. EXPECT_FALSE(consumed);
  24094. if (req.has_param("retry")) {
  24095. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24096. }
  24097. // Replace the 400 the aborted read set, which would close the connection.
  24098. res.set_redirect("/done");
  24099. });
  24100. auto port = svr.bind_to_any_port(HOST);
  24101. thread t = thread([&] { svr.listen_after_bind(); });
  24102. auto se = detail::scope_exit([&] {
  24103. svr.stop();
  24104. t.join();
  24105. });
  24106. svr.wait_until_ready();
  24107. // A front end sees the second request as a POST whose body is the GET. The
  24108. // first body is as long as the POST's headers, so draining it again reads
  24109. // exactly those and leaves the GET to be parsed next.
  24110. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24111. "Host: localhost\r\n"
  24112. "\r\n";
  24113. std::string second_head = "POST /post HTTP/1.1\r\n"
  24114. "Host: localhost\r\n"
  24115. "Content-Length: " +
  24116. std::to_string(inner.size()) +
  24117. "\r\n"
  24118. "\r\n";
  24119. for (auto target : {"/upload", "/upload?retry"}) {
  24120. smuggled_count = 0;
  24121. std::string request = "POST " + std::string(target) +
  24122. " HTTP/1.1\r\n"
  24123. "Host: localhost\r\n"
  24124. "Content-Length: " +
  24125. std::to_string(second_head.size()) +
  24126. "\r\n"
  24127. "\r\n" +
  24128. std::string(second_head.size(), 'A') + second_head +
  24129. inner;
  24130. std::string response;
  24131. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24132. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24133. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24134. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24135. EXPECT_EQ(0, smuggled_count.load()) << target;
  24136. }
  24137. }
  24138. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24139. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24140. // must be rejected with 400 Bad Request.
  24141. Server svr;
  24142. svr.Post("/test", [&](const Request &, Response &res) {
  24143. res.set_content("ok", "text/plain");
  24144. });
  24145. thread t = thread([&] { svr.listen(HOST, PORT); });
  24146. auto se = detail::scope_exit([&] {
  24147. svr.stop();
  24148. t.join();
  24149. ASSERT_FALSE(svr.is_running());
  24150. });
  24151. svr.wait_until_ready();
  24152. // Exact "chunked"
  24153. {
  24154. auto req = "POST /test HTTP/1.1\r\n"
  24155. "Host: localhost\r\n"
  24156. "Content-Length: 5\r\n"
  24157. "Transfer-Encoding: chunked\r\n"
  24158. "Connection: close\r\n"
  24159. "\r\n"
  24160. "hello";
  24161. std::string response;
  24162. ASSERT_TRUE(send_request(1, req, &response));
  24163. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24164. response.substr(0, response.find("\r\n")));
  24165. }
  24166. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24167. {
  24168. auto req = "POST /test HTTP/1.1\r\n"
  24169. "Host: localhost\r\n"
  24170. "Content-Length: 5\r\n"
  24171. "Transfer-Encoding: gzip, chunked\r\n"
  24172. "Connection: close\r\n"
  24173. "\r\n"
  24174. "hello";
  24175. std::string response;
  24176. ASSERT_TRUE(send_request(1, req, &response));
  24177. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24178. response.substr(0, response.find("\r\n")));
  24179. }
  24180. }
  24181. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24182. Server svr;
  24183. svr.Post("/test", [&](const Request &, Response &res) {
  24184. res.set_content("ok", "text/plain");
  24185. });
  24186. thread t = thread([&] { svr.listen(HOST, PORT); });
  24187. auto se = detail::scope_exit([&] {
  24188. svr.stop();
  24189. t.join();
  24190. ASSERT_FALSE(svr.is_running());
  24191. });
  24192. svr.wait_until_ready();
  24193. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24194. // length cannot be determined, so the server must answer 400 and close
  24195. // rather than treat the request as bodyless and leave the body in the
  24196. // socket for the next request to pick up.
  24197. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24198. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24199. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24200. std::string response;
  24201. ASSERT_TRUE(send_request(1, req, &response));
  24202. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24203. response.substr(0, response.find("\r\n")))
  24204. << transfer_encoding;
  24205. }
  24206. // RFC 9110 5.3: the codings may also be split across several
  24207. // Transfer-Encoding lines, which combine in the order they were received.
  24208. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24209. // just like the single-line "chunked, gzip" above.
  24210. {
  24211. auto req = "POST /test HTTP/1.1\r\n"
  24212. "Host: localhost\r\n"
  24213. "Transfer-Encoding: chunked\r\n"
  24214. "Transfer-Encoding: gzip\r\n"
  24215. "\r\n"
  24216. "0\r\n\r\n";
  24217. std::string response;
  24218. ASSERT_TRUE(send_request(1, req, &response));
  24219. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24220. response.substr(0, response.find("\r\n")));
  24221. }
  24222. // A sequence ending in chunked stays valid.
  24223. auto req = "POST /test HTTP/1.1\r\n"
  24224. "Host: localhost\r\n"
  24225. "Transfer-Encoding: gzip, chunked\r\n"
  24226. "Connection: close\r\n"
  24227. "\r\n"
  24228. "0\r\n\r\n";
  24229. std::string response;
  24230. ASSERT_TRUE(send_request(1, req, &response));
  24231. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24232. // ...including when it is spread over several lines.
  24233. auto split_req = "POST /test HTTP/1.1\r\n"
  24234. "Host: localhost\r\n"
  24235. "Transfer-Encoding: gzip\r\n"
  24236. "Transfer-Encoding: chunked\r\n"
  24237. "Connection: close\r\n"
  24238. "\r\n"
  24239. "0\r\n\r\n";
  24240. std::string split_response;
  24241. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24242. EXPECT_EQ("HTTP/1.1 200 OK",
  24243. split_response.substr(0, split_response.find("\r\n")));
  24244. }
  24245. // Regression for issue #2450: a DELETE without Content-Length on a
  24246. // keep-alive connection must not let the post-response drain consume the
  24247. // next request's bytes.
  24248. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24249. Server svr;
  24250. std::atomic<int> delete_count(0);
  24251. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24252. delete_count++;
  24253. res.status = StatusCode::NoContent_204;
  24254. });
  24255. auto port = svr.bind_to_any_port(HOST);
  24256. thread t = thread([&] { svr.listen_after_bind(); });
  24257. auto se = detail::scope_exit([&] {
  24258. svr.stop();
  24259. t.join();
  24260. });
  24261. svr.wait_until_ready();
  24262. auto error = Error::Success;
  24263. auto sock = detail::create_client_socket(
  24264. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24265. /*connection_timeout_sec=*/2, 0,
  24266. /*read_timeout_sec=*/2, 0,
  24267. /*write_timeout_sec=*/2, 0, std::string(), error);
  24268. ASSERT_NE(INVALID_SOCKET, sock);
  24269. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24270. auto send_request_and_read_response = [&](const std::string &req,
  24271. std::string &out) -> bool {
  24272. auto sent = send(sock, req.data(), req.size(), 0);
  24273. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24274. char buf[4096];
  24275. for (;;) {
  24276. auto n = recv(sock, buf, sizeof(buf), 0);
  24277. if (n <= 0) { return !out.empty(); }
  24278. out.append(buf, static_cast<size_t>(n));
  24279. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24280. }
  24281. };
  24282. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24283. "Host: localhost\r\n"
  24284. "\r\n";
  24285. std::string resp1;
  24286. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24287. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24288. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24289. "Host: localhost\r\n"
  24290. "Connection: close\r\n"
  24291. "\r\n";
  24292. std::string resp2;
  24293. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24294. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24295. EXPECT_EQ(2, delete_count.load());
  24296. }
  24297. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24298. Server svr;
  24299. svr.Post("/ingest", [&](const Request &, Response &res,
  24300. const ContentReader &content_reader) {
  24301. auto consumed = content_reader([](const char *, size_t) { return false; });
  24302. EXPECT_FALSE(consumed);
  24303. res.status = StatusCode::Conflict_409;
  24304. res.set_header("Connection", "close");
  24305. });
  24306. auto port = svr.bind_to_any_port(HOST);
  24307. thread t = thread([&] { svr.listen_after_bind(); });
  24308. auto se = detail::scope_exit([&] {
  24309. svr.stop();
  24310. t.join();
  24311. });
  24312. svr.wait_until_ready();
  24313. auto error = Error::Success;
  24314. auto sock = detail::create_client_socket(
  24315. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24316. /*connection_timeout_sec=*/2, 0,
  24317. /*read_timeout_sec=*/1, 0,
  24318. /*write_timeout_sec=*/2, 0, std::string(), error);
  24319. ASSERT_NE(INVALID_SOCKET, sock);
  24320. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24321. std::string request = "POST /ingest HTTP/1.1\r\n"
  24322. "Host: localhost\r\n"
  24323. "Transfer-Encoding: chunked\r\n"
  24324. "\r\n"
  24325. "4\r\n"
  24326. "data\r\n";
  24327. auto sent = send(sock, request.data(), request.size(), 0);
  24328. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24329. std::string response;
  24330. ssize_t received = 0;
  24331. do {
  24332. char buf[4096];
  24333. received = recv(sock, buf, sizeof(buf), 0);
  24334. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24335. } while (received > 0);
  24336. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24337. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24338. EXPECT_EQ(0, received);
  24339. }
  24340. namespace no_proxy_test {
  24341. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24342. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24343. // calling listen().
  24344. class ScopedServer {
  24345. public:
  24346. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24347. ~ScopedServer() {
  24348. svr_.stop();
  24349. if (th_.joinable()) { th_.join(); }
  24350. }
  24351. Server &svr() { return svr_; }
  24352. int port() const { return port_; }
  24353. void listen() {
  24354. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24355. svr_.wait_until_ready();
  24356. }
  24357. private:
  24358. Server svr_;
  24359. std::thread th_;
  24360. int port_ = 0;
  24361. };
  24362. class ProxyAndTargetServers {
  24363. public:
  24364. ProxyAndTargetServers() {
  24365. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24366. proxy_hits_++;
  24367. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24368. res.set_content("via-proxy", "text/plain");
  24369. });
  24370. target_.Get(".*", [this](const Request &req, Response &res) {
  24371. target_hits_++;
  24372. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24373. res.set_content("direct", "text/plain");
  24374. });
  24375. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24376. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24377. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24378. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24379. proxy_mock_.wait_until_ready();
  24380. target_.wait_until_ready();
  24381. }
  24382. ~ProxyAndTargetServers() {
  24383. proxy_mock_.stop();
  24384. target_.stop();
  24385. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24386. if (target_thread_.joinable()) { target_thread_.join(); }
  24387. }
  24388. Server &proxy_mock() { return proxy_mock_; }
  24389. Server &target() { return target_; }
  24390. int proxy_port() const { return proxy_port_; }
  24391. int target_port() const { return target_port_; }
  24392. int proxy_hits() const { return proxy_hits_.load(); }
  24393. int target_hits() const { return target_hits_.load(); }
  24394. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24395. void reset_counters() {
  24396. proxy_hits_ = 0;
  24397. target_hits_ = 0;
  24398. last_had_proxy_authz_ = false;
  24399. }
  24400. private:
  24401. Server proxy_mock_;
  24402. Server target_;
  24403. std::thread proxy_thread_;
  24404. std::thread target_thread_;
  24405. int proxy_port_ = 0;
  24406. int target_port_ = 0;
  24407. std::atomic<int> proxy_hits_{0};
  24408. std::atomic<int> target_hits_{0};
  24409. std::atomic<bool> last_had_proxy_authz_{false};
  24410. };
  24411. inline std::unique_ptr<Client> make_client(const std::string &host,
  24412. ProxyAndTargetServers &s) {
  24413. auto cli = detail::make_unique<Client>(host, s.target_port());
  24414. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24415. cli->set_proxy("127.0.0.1", s.proxy_port());
  24416. return cli;
  24417. }
  24418. } // namespace no_proxy_test
  24419. using no_proxy_test::make_client;
  24420. using no_proxy_test::ProxyAndTargetServers;
  24421. TEST(NoProxyTest, ExactHostnameBypasses) {
  24422. ProxyAndTargetServers s;
  24423. auto cli = make_client("example.com", s);
  24424. cli->set_no_proxy({"example.com"});
  24425. auto res = cli->Get("/");
  24426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24427. EXPECT_EQ(0, s.proxy_hits());
  24428. EXPECT_EQ(1, s.target_hits());
  24429. }
  24430. TEST(NoProxyTest, SubdomainBypasses) {
  24431. ProxyAndTargetServers s;
  24432. auto cli = make_client("foo.example.com", s);
  24433. cli->set_no_proxy({"example.com"});
  24434. auto res = cli->Get("/");
  24435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24436. EXPECT_EQ(0, s.proxy_hits());
  24437. EXPECT_EQ(1, s.target_hits());
  24438. }
  24439. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24440. // Regression guard: "evilexample.com" must not be considered a subdomain
  24441. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24442. // check would let traffic bypass the proxy and leak credentials direct
  24443. // to the attacker host.
  24444. ProxyAndTargetServers s;
  24445. auto cli = make_client("evilexample.com", s);
  24446. cli->set_no_proxy({"example.com"});
  24447. auto res = cli->Get("/");
  24448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24449. EXPECT_GE(s.proxy_hits(), 1);
  24450. EXPECT_EQ(0, s.target_hits());
  24451. }
  24452. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24453. ProxyAndTargetServers s;
  24454. auto cli = make_client("example.com.evil.com", s);
  24455. cli->set_no_proxy({"example.com"});
  24456. auto res = cli->Get("/");
  24457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24458. EXPECT_GE(s.proxy_hits(), 1);
  24459. EXPECT_EQ(0, s.target_hits());
  24460. }
  24461. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24462. ProxyAndTargetServers s;
  24463. auto cli = make_client("example.com", s);
  24464. cli->set_no_proxy({".example.com"});
  24465. auto res = cli->Get("/");
  24466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24467. EXPECT_EQ(0, s.proxy_hits());
  24468. EXPECT_EQ(1, s.target_hits());
  24469. }
  24470. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24471. ProxyAndTargetServers s;
  24472. auto cli = make_client("Example.COM", s);
  24473. cli->set_no_proxy({"EXAMPLE.com"});
  24474. auto res = cli->Get("/");
  24475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24476. EXPECT_EQ(0, s.proxy_hits());
  24477. EXPECT_EQ(1, s.target_hits());
  24478. }
  24479. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24480. ProxyAndTargetServers s;
  24481. auto cli = make_client("example.com.", s);
  24482. cli->set_no_proxy({"example.com"});
  24483. auto res = cli->Get("/");
  24484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24485. EXPECT_EQ(0, s.proxy_hits());
  24486. EXPECT_EQ(1, s.target_hits());
  24487. }
  24488. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24489. // Trailing dots must be normalized on BOTH sides — host and entry.
  24490. // An implementation that only strips the host-side trailing dot would
  24491. // fail to match host "example.com" against entry "example.com." because
  24492. // a literal substring search would compare 11 chars against 12.
  24493. ProxyAndTargetServers s;
  24494. auto cli = make_client("example.com", s);
  24495. cli->set_no_proxy({"example.com."});
  24496. auto res = cli->Get("/");
  24497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24498. EXPECT_EQ(0, s.proxy_hits());
  24499. EXPECT_EQ(1, s.target_hits());
  24500. }
  24501. TEST(NoProxyTest, WildcardBypassesEverything) {
  24502. ProxyAndTargetServers s;
  24503. auto cli = make_client("anything.invalid.test", s);
  24504. cli->set_no_proxy({"*"});
  24505. auto res = cli->Get("/");
  24506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24507. EXPECT_EQ(0, s.proxy_hits());
  24508. EXPECT_EQ(1, s.target_hits());
  24509. }
  24510. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24511. ProxyAndTargetServers s;
  24512. Client cli("127.0.0.1", s.target_port());
  24513. cli.set_proxy("127.0.0.1", s.proxy_port());
  24514. cli.set_no_proxy({"127.0.0.1"});
  24515. auto res = cli.Get("/");
  24516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24517. EXPECT_EQ(0, s.proxy_hits());
  24518. EXPECT_EQ(1, s.target_hits());
  24519. }
  24520. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24521. ProxyAndTargetServers s;
  24522. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24523. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24524. cli.set_proxy("127.0.0.1", s.proxy_port());
  24525. cli.set_no_proxy({"::1"});
  24526. auto res = cli.Get("/");
  24527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24528. EXPECT_EQ(0, s.proxy_hits());
  24529. EXPECT_EQ(1, s.target_hits());
  24530. }
  24531. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24532. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24533. // must still be recognized as IPv6 for CIDR matching. Implementations
  24534. // that detect IPv6 only when the host begins with '[' would parse the
  24535. // host as a hostname and miss the match.
  24536. ProxyAndTargetServers s;
  24537. Client cli("fe80::1", s.target_port());
  24538. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24539. cli.set_proxy("127.0.0.1", s.proxy_port());
  24540. cli.set_no_proxy({"fe80::/10"});
  24541. auto res = cli.Get("/");
  24542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24543. EXPECT_EQ(0, s.proxy_hits());
  24544. EXPECT_EQ(1, s.target_hits());
  24545. }
  24546. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24547. ProxyAndTargetServers s;
  24548. Client cli("::1", s.target_port());
  24549. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24550. cli.set_proxy("127.0.0.1", s.proxy_port());
  24551. cli.set_no_proxy({"[::1]"});
  24552. auto res = cli.Get("/");
  24553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24554. EXPECT_EQ(0, s.proxy_hits());
  24555. EXPECT_EQ(1, s.target_hits());
  24556. }
  24557. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24558. ProxyAndTargetServers s;
  24559. Client cli("fe80::1", s.target_port());
  24560. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24561. cli.set_proxy("127.0.0.1", s.proxy_port());
  24562. cli.set_no_proxy({"[fe80::]/10"});
  24563. auto res = cli.Get("/");
  24564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24565. EXPECT_EQ(0, s.proxy_hits());
  24566. EXPECT_EQ(1, s.target_hits());
  24567. }
  24568. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24569. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24570. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24571. // tricks via address-family conversion.
  24572. ProxyAndTargetServers s;
  24573. Client cli("::ffff:127.0.0.1", s.target_port());
  24574. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24575. cli.set_proxy("127.0.0.1", s.proxy_port());
  24576. cli.set_no_proxy({"127.0.0.1"});
  24577. auto res = cli.Get("/");
  24578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24579. EXPECT_GE(s.proxy_hits(), 1);
  24580. EXPECT_EQ(0, s.target_hits());
  24581. }
  24582. TEST(NoProxyTest, IPv4CidrMatch) {
  24583. ProxyAndTargetServers s;
  24584. Client cli("127.0.0.1", s.target_port());
  24585. cli.set_proxy("127.0.0.1", s.proxy_port());
  24586. cli.set_no_proxy({"127.0.0.0/8"});
  24587. auto res = cli.Get("/");
  24588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24589. EXPECT_EQ(0, s.proxy_hits());
  24590. EXPECT_EQ(1, s.target_hits());
  24591. }
  24592. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24593. ProxyAndTargetServers s;
  24594. Client cli("127.0.0.1", s.target_port());
  24595. cli.set_proxy("127.0.0.1", s.proxy_port());
  24596. cli.set_no_proxy({"10.0.0.0/8"});
  24597. auto res = cli.Get("/");
  24598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24599. EXPECT_GE(s.proxy_hits(), 1);
  24600. EXPECT_EQ(0, s.target_hits());
  24601. }
  24602. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24603. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24604. // IPv4 target matches.
  24605. ProxyAndTargetServers s;
  24606. Client cli("127.0.0.1", s.target_port());
  24607. cli.set_proxy("127.0.0.1", s.proxy_port());
  24608. cli.set_no_proxy({"0.0.0.0/0"});
  24609. auto res = cli.Get("/");
  24610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24611. EXPECT_EQ(0, s.proxy_hits());
  24612. EXPECT_EQ(1, s.target_hits());
  24613. }
  24614. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24615. ProxyAndTargetServers s;
  24616. Client cli("127.0.0.1", s.target_port());
  24617. cli.set_proxy("127.0.0.1", s.proxy_port());
  24618. cli.set_no_proxy({"127.0.0.1"});
  24619. auto res = cli.Get("/");
  24620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24621. EXPECT_EQ(0, s.proxy_hits());
  24622. EXPECT_EQ(1, s.target_hits());
  24623. }
  24624. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24625. ProxyAndTargetServers s;
  24626. Client cli("127.0.0.1", s.target_port());
  24627. cli.set_proxy("127.0.0.1", s.proxy_port());
  24628. cli.set_no_proxy({"127.0.0.0/33"});
  24629. auto res = cli.Get("/");
  24630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24631. EXPECT_GE(s.proxy_hits(), 1);
  24632. EXPECT_EQ(0, s.target_hits());
  24633. }
  24634. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24635. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24636. ProxyAndTargetServers s;
  24637. Client cli("127.0.0.1", s.target_port());
  24638. cli.set_proxy("127.0.0.1", s.proxy_port());
  24639. cli.set_no_proxy({"127.0.0.1/"});
  24640. auto res = cli.Get("/");
  24641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24642. EXPECT_GE(s.proxy_hits(), 1);
  24643. EXPECT_EQ(0, s.target_hits());
  24644. }
  24645. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24646. ProxyAndTargetServers s;
  24647. auto cli = make_client("internal.corp", s);
  24648. cli->set_proxy_basic_auth("u", "p");
  24649. cli->set_no_proxy({"internal.corp"});
  24650. auto res = cli->Get("/");
  24651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24652. EXPECT_EQ(1, s.target_hits());
  24653. EXPECT_EQ(0, s.proxy_hits());
  24654. EXPECT_FALSE(s.last_had_proxy_authz())
  24655. << "Proxy-Authorization must not be sent direct to the target";
  24656. }
  24657. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24658. ProxyAndTargetServers s;
  24659. auto cli = make_client("public.example", s);
  24660. cli->set_proxy_basic_auth("u", "p");
  24661. cli->set_no_proxy({"internal.corp"}); // does not match
  24662. auto res = cli->Get("/");
  24663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24664. EXPECT_GE(s.proxy_hits(), 1);
  24665. EXPECT_TRUE(s.last_had_proxy_authz());
  24666. }
  24667. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24668. std::atomic<int> hits{0};
  24669. std::atomic<int> hits_with_authz{0};
  24670. no_proxy_test::ScopedServer proxy_mock;
  24671. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24672. hits++;
  24673. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24674. if (req.target.find("/redir") != std::string::npos) {
  24675. res.set_redirect("http://other.example/landed");
  24676. } else {
  24677. res.set_content("via-proxy", "text/plain");
  24678. }
  24679. });
  24680. proxy_mock.listen();
  24681. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24682. hits = 0;
  24683. hits_with_authz = 0;
  24684. Client cli("public.example", 80);
  24685. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24686. cli.set_proxy_basic_auth(c.first, c.second);
  24687. cli.set_follow_location(true);
  24688. // The redirect to another host goes through the proxy as well
  24689. auto res = cli.Get("/redir");
  24690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24691. EXPECT_EQ(2, hits.load());
  24692. EXPECT_EQ(2, hits_with_authz.load());
  24693. }
  24694. }
  24695. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24696. ProxyAndTargetServers s;
  24697. auto cli = make_client("anything.test", s);
  24698. auto res = cli->Get("/");
  24699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24700. EXPECT_GE(s.proxy_hits(), 1);
  24701. EXPECT_EQ(0, s.target_hits());
  24702. }
  24703. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24704. ProxyAndTargetServers s;
  24705. auto cli = make_client("example.com", s);
  24706. cli->set_no_proxy({"example.com:8080"});
  24707. auto res = cli->Get("/");
  24708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24709. EXPECT_GE(s.proxy_hits(), 1);
  24710. EXPECT_EQ(0, s.target_hits());
  24711. }
  24712. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24713. ProxyAndTargetServers s;
  24714. auto cli = make_client("anything.test", s);
  24715. cli->set_no_proxy({"", " ", "\t"});
  24716. auto res = cli->Get("/");
  24717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24718. EXPECT_GE(s.proxy_hits(), 1);
  24719. EXPECT_EQ(0, s.target_hits());
  24720. }
  24721. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24722. // An entry with leading/trailing whitespace must still match — env-style
  24723. // values are commonly pasted with stray spaces and an implementation
  24724. // that feeds the raw token directly to inet_pton would fail to match
  24725. // valid CIDRs because of the spaces.
  24726. ProxyAndTargetServers s;
  24727. Client cli("127.0.0.1", s.target_port());
  24728. cli.set_proxy("127.0.0.1", s.proxy_port());
  24729. cli.set_no_proxy({" 127.0.0.0/8 "});
  24730. auto res = cli.Get("/");
  24731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24732. EXPECT_EQ(0, s.proxy_hits());
  24733. EXPECT_EQ(1, s.target_hits());
  24734. }
  24735. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24736. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24737. // go direct and must NOT carry Proxy-Authorization.
  24738. std::atomic<int> proxy_hits{0};
  24739. std::atomic<int> target_hits{0};
  24740. std::atomic<bool> target_saw_authz{false};
  24741. no_proxy_test::ScopedServer proxy_mock, target;
  24742. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24743. proxy_hits++;
  24744. res.status = 302;
  24745. res.set_header("Location", "http://127.0.0.1:" +
  24746. std::to_string(target.port()) + "/landed");
  24747. });
  24748. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24749. target_hits++;
  24750. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24751. res.set_content("direct", "text/plain");
  24752. });
  24753. proxy_mock.listen();
  24754. target.listen();
  24755. Client cli("public.example", target.port());
  24756. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24757. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24758. cli.set_proxy_basic_auth("u", "p");
  24759. cli.set_no_proxy({"127.0.0.1"});
  24760. cli.set_follow_location(true);
  24761. auto res = cli.Get("/redir");
  24762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24763. EXPECT_GE(proxy_hits.load(), 1);
  24764. EXPECT_GE(target_hits.load(), 1);
  24765. EXPECT_FALSE(target_saw_authz.load());
  24766. }
  24767. #ifdef CPPHTTPLIB_SSL_ENABLED
  24768. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24769. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24770. // proxy creds would be sent to the (possibly hostile) origin.
  24771. std::atomic<int> target_hits{0};
  24772. std::atomic<bool> target_saw_proxy_authz{false};
  24773. no_proxy_test::ScopedServer target;
  24774. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24775. target_hits++;
  24776. if (req.has_header("Proxy-Authorization")) {
  24777. target_saw_proxy_authz = true;
  24778. }
  24779. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24780. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24781. "nonce=\"abc\", algorithm=MD5");
  24782. });
  24783. target.listen();
  24784. // The proxy address is set to the target's port: the bypass MUST kick in;
  24785. // if it doesn't, the test still routes "via proxy" to the same server and
  24786. // the Proxy-Authorization assertion below catches the leak.
  24787. Client cli("evil.example", target.port());
  24788. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24789. cli.set_proxy("127.0.0.1", target.port());
  24790. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24791. cli.set_no_proxy({"evil.example"});
  24792. auto res = cli.Get("/x");
  24793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24794. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24795. EXPECT_EQ(1, target_hits.load());
  24796. EXPECT_FALSE(target_saw_proxy_authz.load());
  24797. }
  24798. #endif
  24799. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24800. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24801. std::atomic<int> proxy_hits{0};
  24802. std::atomic<int> bypass_hits{0};
  24803. std::atomic<bool> proxy_saw_c_url{false};
  24804. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24805. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24806. proxy_hits++;
  24807. if (req.path.find("/start") != std::string::npos) {
  24808. res.status = 302;
  24809. res.set_header("Location", "http://127.0.0.1:" +
  24810. std::to_string(bypass_server.port()) +
  24811. "/middle");
  24812. return;
  24813. }
  24814. if (req.path.find("/end") != std::string::npos) {
  24815. proxy_saw_c_url = true;
  24816. res.set_content("c-via-proxy", "text/plain");
  24817. return;
  24818. }
  24819. res.set_content("unexpected", "text/plain");
  24820. });
  24821. // public.example's "advertised" port is arbitrary (the request never lands
  24822. // there — it goes through the proxy), but use a dynamic value to stay
  24823. // friendly with sharded parallel runs.
  24824. int public_port = bypass_server.port();
  24825. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24826. bypass_hits++;
  24827. res.status = 302;
  24828. res.set_header("Location", "http://public.example:" +
  24829. std::to_string(public_port) + "/end");
  24830. });
  24831. proxy_mock.listen();
  24832. bypass_server.listen();
  24833. Client cli("public.example", public_port);
  24834. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24835. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24836. cli.set_no_proxy({"127.0.0.1"});
  24837. cli.set_follow_location(true);
  24838. auto res = cli.Get("/start");
  24839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24840. EXPECT_EQ(StatusCode::OK_200, res->status);
  24841. EXPECT_EQ("c-via-proxy", res->body);
  24842. EXPECT_GE(proxy_hits.load(), 2);
  24843. EXPECT_GE(bypass_hits.load(), 1);
  24844. EXPECT_TRUE(proxy_saw_c_url.load());
  24845. }
  24846. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24847. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24848. // request reconnects to the correct endpoint.
  24849. std::atomic<int> proxy_hits{0};
  24850. std::atomic<int> target_hits{0};
  24851. no_proxy_test::ScopedServer proxy_mock, target;
  24852. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24853. proxy_hits++;
  24854. res.set_content("via-proxy", "text/plain");
  24855. });
  24856. target.svr().Get(".*", [&](const Request &, Response &res) {
  24857. target_hits++;
  24858. res.set_content("direct", "text/plain");
  24859. });
  24860. proxy_mock.listen();
  24861. target.listen();
  24862. Client cli("public.example", target.port());
  24863. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24864. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24865. cli.set_keep_alive(true);
  24866. auto res1 = cli.Get("/a");
  24867. ASSERT_TRUE(res1);
  24868. EXPECT_EQ("via-proxy", res1->body);
  24869. EXPECT_EQ(1, proxy_hits.load());
  24870. EXPECT_EQ(0, target_hits.load());
  24871. cli.set_no_proxy({"public.example"});
  24872. auto res2 = cli.Get("/b");
  24873. ASSERT_TRUE(res2);
  24874. EXPECT_EQ("direct", res2->body);
  24875. EXPECT_EQ(1, proxy_hits.load());
  24876. EXPECT_EQ(1, target_hits.load());
  24877. }
  24878. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24879. namespace proxy_tunnel_test {
  24880. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24881. class ScopedSSLServer {
  24882. public:
  24883. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24884. port_ = svr_.bind_to_any_port("127.0.0.1");
  24885. }
  24886. ~ScopedSSLServer() {
  24887. svr_.stop();
  24888. if (th_.joinable()) { th_.join(); }
  24889. }
  24890. SSLServer &svr() { return svr_; }
  24891. int port() const { return port_; }
  24892. void listen() {
  24893. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24894. svr_.wait_until_ready();
  24895. }
  24896. private:
  24897. SSLServer svr_;
  24898. std::thread th_;
  24899. int port_ = 0;
  24900. };
  24901. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24902. class ScopedConnectProxy {
  24903. public:
  24904. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24905. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24906. if (listen_fd_ < 0) { return; }
  24907. int yes = 1;
  24908. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24909. sockaddr_in a{};
  24910. a.sin_family = AF_INET;
  24911. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24912. a.sin_port = 0;
  24913. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24914. return;
  24915. }
  24916. socklen_t alen = sizeof(a);
  24917. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24918. 0) {
  24919. return;
  24920. }
  24921. port_ = ntohs(a.sin_port);
  24922. if (::listen(listen_fd_, 1) != 0) { return; }
  24923. th_ = std::thread([this] { run(); });
  24924. }
  24925. ~ScopedConnectProxy() {
  24926. stop_ = true;
  24927. if (listen_fd_ >= 0) {
  24928. ::shutdown(listen_fd_, SHUT_RDWR);
  24929. ::close(listen_fd_);
  24930. }
  24931. if (th_.joinable()) { th_.join(); }
  24932. }
  24933. int port() const { return port_; }
  24934. int connect_hits() const { return connect_hits_.load(); }
  24935. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24936. std::string connect_request() const {
  24937. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24938. return connect_request_;
  24939. }
  24940. private:
  24941. void run() {
  24942. while (!stop_.load()) {
  24943. fd_set rfds;
  24944. FD_ZERO(&rfds);
  24945. FD_SET(listen_fd_, &rfds);
  24946. timeval tv{0, 100 * 1000};
  24947. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24948. if (sel <= 0) { continue; }
  24949. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24950. if (client_fd < 0) { continue; }
  24951. std::string req;
  24952. char buf[2048];
  24953. while (req.find("\r\n\r\n") == std::string::npos) {
  24954. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24955. if (n <= 0) { break; }
  24956. req.append(buf, static_cast<size_t>(n));
  24957. }
  24958. if (req.compare(0, 7, "CONNECT") != 0) {
  24959. ::close(client_fd);
  24960. continue;
  24961. }
  24962. connect_hits_++;
  24963. {
  24964. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24965. connect_request_ = req;
  24966. }
  24967. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24968. ::send(client_fd, ok, std::strlen(ok), 0);
  24969. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24970. sockaddr_in o{};
  24971. o.sin_family = AF_INET;
  24972. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24973. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24974. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24975. 0) {
  24976. ::close(client_fd);
  24977. ::close(origin_fd);
  24978. continue;
  24979. }
  24980. auto forward = [](int from, int to) {
  24981. char b[8192];
  24982. for (;;) {
  24983. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24984. if (n <= 0) { break; }
  24985. ssize_t off = 0;
  24986. while (off < n) {
  24987. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24988. if (s <= 0) {
  24989. off = n;
  24990. break;
  24991. }
  24992. off += s;
  24993. }
  24994. }
  24995. ::shutdown(to, SHUT_WR);
  24996. };
  24997. std::thread t1([&] { forward(client_fd, origin_fd); });
  24998. std::thread t2([&] { forward(origin_fd, client_fd); });
  24999. t1.join();
  25000. t2.join();
  25001. ::close(client_fd);
  25002. ::close(origin_fd);
  25003. }
  25004. }
  25005. int forward_port_ = -1;
  25006. int listen_fd_ = -1;
  25007. int port_ = 0;
  25008. std::thread th_;
  25009. std::atomic<bool> stop_{false};
  25010. std::atomic<int> connect_hits_{0};
  25011. mutable std::mutex connect_request_mutex_;
  25012. std::string connect_request_;
  25013. };
  25014. // Sends one request through the CONNECT proxy to the TLS origin with a
  25015. // credential configured for each hop, and checks that each credential reaches
  25016. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25017. // origin's (every header in origin_headers) on the tunnelled request.
  25018. void CredentialsStayWithTheirHop(
  25019. const std::function<void(SSLClient &)> &set_credentials,
  25020. const std::string &scheme,
  25021. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25022. std::atomic<int> origin_hits{0};
  25023. std::atomic<bool> origin_saw_proxy_authz{false};
  25024. std::atomic<bool> origin_saw_headers{false};
  25025. ScopedSSLServer origin;
  25026. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25027. origin_hits++;
  25028. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25029. origin_saw_headers =
  25030. std::all_of(origin_headers.begin(), origin_headers.end(),
  25031. [&](const std::string &h) { return req.has_header(h); });
  25032. res.set_content("ok", "text/plain");
  25033. });
  25034. origin.listen();
  25035. ScopedConnectProxy proxy(origin.port());
  25036. ASSERT_NE(0, proxy.port());
  25037. // Pinned to 127.0.0.1 for the same reason as the test below.
  25038. SSLClient cli("127.0.0.1", origin.port());
  25039. cli.enable_server_certificate_verification(false);
  25040. cli.set_proxy("127.0.0.1", proxy.port());
  25041. set_credentials(cli);
  25042. auto res = cli.Get("/x");
  25043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25044. EXPECT_EQ(StatusCode::OK_200, res->status);
  25045. EXPECT_EQ(1, origin_hits.load());
  25046. EXPECT_EQ(1, proxy.connect_hits());
  25047. EXPECT_TRUE(origin_saw_headers.load());
  25048. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25049. << "Proxy-Authorization must not be sent inside the tunnel";
  25050. auto connect_req = proxy.connect_request();
  25051. EXPECT_NE(std::string::npos,
  25052. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25053. for (const auto &h : origin_headers) {
  25054. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25055. << h << " must not be sent to the proxy on CONNECT";
  25056. }
  25057. }
  25058. } // namespace proxy_tunnel_test
  25059. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25060. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25061. [](SSLClient &cli) {
  25062. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25063. cli.set_basic_auth("origin-user", "origin-pass");
  25064. },
  25065. "Basic");
  25066. }
  25067. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25068. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25069. [](SSLClient &cli) {
  25070. cli.set_proxy_bearer_token_auth("proxy-token");
  25071. cli.set_bearer_token_auth("origin-token");
  25072. },
  25073. "Bearer");
  25074. }
  25075. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25076. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25077. [](SSLClient &cli) {
  25078. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25079. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25080. {"Cookie", "sid=origin-session"},
  25081. {"X-Api-Key", "origin-key"}});
  25082. },
  25083. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25084. }
  25085. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25086. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25087. // retry; otherwise proxy creds would be sent to the origin.
  25088. std::atomic<int> origin_hits{0};
  25089. std::atomic<bool> origin_saw_proxy_authz{false};
  25090. proxy_tunnel_test::ScopedSSLServer origin;
  25091. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25092. origin_hits++;
  25093. if (req.has_header("Proxy-Authorization")) {
  25094. origin_saw_proxy_authz = true;
  25095. }
  25096. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25097. res.set_header("Proxy-Authenticate",
  25098. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25099. "algorithm=MD5");
  25100. });
  25101. origin.listen();
  25102. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25103. ASSERT_NE(0, proxy.port());
  25104. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25105. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25106. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25107. // and answer with its own status, making this test flaky.
  25108. SSLClient cli("127.0.0.1", origin.port());
  25109. cli.enable_server_certificate_verification(false);
  25110. cli.set_proxy("127.0.0.1", proxy.port());
  25111. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25112. auto res = cli.Get("/x");
  25113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25114. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25115. EXPECT_EQ(1, origin_hits.load());
  25116. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25117. EXPECT_EQ(1, proxy.connect_hits());
  25118. }
  25119. #endif